package es_01_document; import com.kwan.shuyu.SearchApplication; import lombok.extern.slf4j.Slf4j; 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; import java.io.IOException; /** * 同步获取结果 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/10 14:00 */ @Slf4j @SpringBootTest(classes = SearchApplication.class) @RunWith(SpringRunner.class) public class TestDocument_01_get { @Autowired RestHighLevelClient client; @Test public void testGet() throws IOException { //构建请求 GetRequest getRequest = new GetRequest("test_post", "1"); //添加可选参数 String[] includes = new String[]{"id", "comment"}; String[] excludes = Strings.EMPTY_ARRAY; FetchSourceContext fetchSourceContext = new FetchSourceContext(true, includes, excludes); getRequest.fetchSourceContext(fetchSourceContext); //同步查询 GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT); //获取结果 if (getResponse.isExists()) { log.info(getResponse.getId()); log.info(String.valueOf(getResponse.getVersion())); log.info(getResponse.getSourceAsString());//以string获取数据 log.info(String.valueOf(getResponse.getSourceAsBytes()));////以Bytes获取数据 log.info(String.valueOf(getResponse.getSourceAsMap()));//以Map获取数据 } else { log.info("数据不存在"); } } }