package es_01_document; import com.kwan.shuyu.SearchApplication; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.get.GetRequest; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.Strings; import org.elasticsearch.search.fetch.subphase.FetchSourceContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * 异步获取结果 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/10 14:00 */ @Slf4j @SpringBootTest(classes = SearchApplication.class) @RunWith(SpringRunner.class) public class TestDocument_02_get { @Autowired RestHighLevelClient client; @Test public void testGet() { //构建请求 GetRequest getRequest = new GetRequest("test_post", "1"); //添加可选参数 String[] includes = new String[]{"id", "title"}; String[] excludes = Strings.EMPTY_ARRAY; FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes); getRequest.fetchSourceContext(fetchSourceContext); //设置监听器 ActionListener listener = new ActionListener() { //成功时 public void onResponse(GetResponse getResponse) { log.info(getResponse.getId()); log.info(String.valueOf(getResponse.getVersion())); log.info(getResponse.getSourceAsString()); } //失败时 public void onFailure(Exception e) { e.printStackTrace(); log.info("数据获取异常"); } }; //异步查询 client.getAsync(getRequest, RequestOptions.DEFAULT, listener); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }