package es_03_search; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; 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; import java.util.Map; /** * ids搜索 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/13 18:01 */ @SpringBootTest @RunWith(SpringRunner.class) public class TestSearch_03_ids { @Autowired RestHighLevelClient client; @Test public void testSearchIds() throws IOException { // GET /book/_search // { // "query": { // "ids" : { // "values" : ["1", "4", "100"] // } // } // } //1构建搜索请求 SearchRequest searchRequest = new SearchRequest("book"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.idsQuery().addIds("1", "4", "100")); searchRequest.source(searchSourceBuilder); //2执行搜索 SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT); //3获取结果 SearchHits hits = searchResponse.getHits(); //数据数据 SearchHit[] searchHits = hits.getHits(); System.out.println("--------------------------"); for (SearchHit hit : searchHits) { String id = hit.getId(); float score = hit.getScore(); Map sourceAsMap = hit.getSourceAsMap(); String name = (String) sourceAsMap.get("name"); String description = (String) sourceAsMap.get("description"); Double price = (Double) sourceAsMap.get("price"); System.out.println("id:" + id); System.out.println("name:" + name); System.out.println("description:" + description); System.out.println("price:" + price); System.out.println("=========================="); } } }