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.BoolQueryBuilder; import org.elasticsearch.index.query.MatchQueryBuilder; import org.elasticsearch.index.query.MultiMatchQueryBuilder; 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; /** * bool搜索 * * @author : qinyingjie * @version : 2.2.0 * @date : 2023/5/13 18:01 */ @SpringBootTest @RunWith(SpringRunner.class) public class TestSearch_07_bool { @Autowired RestHighLevelClient client; @Test public void testSearchBool() throws IOException { // GET /book/_search // { // "query": { // "bool": { // "must": [ // { // "multi_match": { // "query": "java程序员", // "fields": ["name","description"] // } // } // ], // "should": [ // { // "match": { // "studymodel": "201001" // } // } // ] // } // } // } //1构建搜索请求 SearchRequest searchRequest = new SearchRequest("book"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); //构建multiMatch请求 MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("java程序员", "name", "description"); //构建match请求 MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("studymodel", "201001"); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); boolQueryBuilder.must(multiMatchQueryBuilder); boolQueryBuilder.should(matchQueryBuilder); searchSourceBuilder.query(boolQueryBuilder); 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("=========================="); } } }