ES查询 Java RestHighLevelClient API方法

    测试环境准备     查询所有文档           分页查询            关键字查询                 根据id查询

    matchQuery      multiMatchQuery     BoolQuery     filter过滤器                     sort排序     高亮 

took:本次操作花费的时间,单位为毫秒。     timed_out:请求是否超时       _shards:说明本次操作共搜索了哪些分片
hits:搜索命中的记录       hits.total : 符合条件的文档总数 hits.hits :匹配度较高的前N个文档
hits.max_score:文档匹配得分,这里为最高分    _score:每个文档都有一个匹配度得分,按照降序排列。
_source:显示了文档的原始内容。

测试环境准备

 1.创建xc_course 索引库       2.创建映射配置    3.插入三条文档

@SpringBootTest
@RunWith(SpringRunner.class)
public class TestSearch {
    @Autowired
    RestHighLevelClient client;
    @Autowired
    RestClient restClient;
}

 查询所有文档

 1.构建 searchRequest 搜索请求对象                 2.设置请求对象的搜索对象的类型      

 3.构建搜索源对象searchSourceBuilder            4.设置搜索源对象的搜索方式                5.设置搜索源对象的过滤条件

 6.向搜索请求对象中设置 搜索源对象                   7.执行搜索,获得搜索结果对象searchResponse

  8.获得搜索结果数组  SearchHits [ ]

     @Test
    public void testSearchAll() throws Exception {
        //构建搜索请求对象
        SearchRequest searchRequest = new SearchRequest("xc_course");
        //设置搜索对象的类型
        searchRequest.types("doc");
        //构建搜索源对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //搜索源搜索方式
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        //过滤条件 第一个要显示的字段,第二个不显示的
        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
        //向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);
        //执行搜索,向ES发起Http请求,获得结果对象
        SearchResponse searchResponse = client.search(searchRequest);
        //搜索结果
        SearchHits hits = searchResponse.getHits();
        //获得匹配总记录
        long totalHits = hits.getTotalHits();
        //得到匹配度高的文档
        SearchHit[] searchHits = hits.getHits();
        //日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for(SearchHit hit:searchHits){
            //文档的主键
            String id = hit.getId();
            //源文档内容
            Map sourceAsMap = hit.getSourceAsMap();
            String name = (String) sourceAsMap.get("name");
            //由于前边设置了源文档字段过虑,这时description是取不到的
            String description = (String) sourceAsMap.get("description");
            //学习模式
            String studymodel = (String) sourceAsMap.get("studymodel");
            //价格
            Double price = (Double) sourceAsMap.get("price");
            //日期
            Date timestamp = dateFormat.parse((String) sourceAsMap.get("timestamp"));
            System.out.println(name);
            System.out.println(studymodel);
            System.out.println(description);
        }

    }

分页查询

    只用在构建搜索源对象后设置参数   即可

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        int page = 1;
        //每页记录数
        int size = 1;
        //计算出记录起始下标
        int from  = (page-1)*size;
        searchSourceBuilder.from(from);//起始记录下标,从0开始
        searchSourceBuilder.size(size);//每页显示的记录数
        //搜索源搜索方式
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());

 关键字查询

  设置搜索源对象的查询方式为  termQuery("name","Spring")  表示查询字段为name的   关键字为Spring

        searchSourceBuilder.query(QueryBuilders.termQuery("name","spring"));
        //设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
        //向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);
        //执行搜索,向ES发起http请求
        SearchResponse searchResponse = client.search(searchRequest);
        //搜索结果
        SearchHits hits = searchResponse.getHits();
        //匹配到的总记录数
        long totalHits = hits.getTotalHits();
        //得到匹配度高的文档
        SearchHit[] searchHits = hits.getHits();

根据id查询

   可以根据多个id查询  所以searchSourceBuilder.query(QueryBuilders.termsQuery("_id",ids));  中传入一个数组

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //搜索方式  根据id查询
        String[] ids = new String[]{"1","2"};
        searchSourceBuilder.query(QueryBuilders.termsQuery("_id",ids));
        //设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
        //向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);

matchQuery

   匹配查询   匹配字段 description     搜索关键字  spring 开发 框架会被分词为三个        

    minimumShouldMatch   为匹配度   0.8*3 =2.4 向下取整  2     所以在 description字段中只要有两个词就算匹配成功

    QueryBuilders.matchQuery("description","spring开发框架").minimumShouldMatch("80%")) 

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //搜索方式MatchQuery
        searchSourceBuilder.query(QueryBuilders.matchQuery("description","spring开发框架")
                .minimumShouldMatch("80%"));
        //设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
        //向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);

 multiMatchQuery

   匹配搜索多个字段

   QueryBuilders.multiMatchQuery("spring css","name","description")  .minimumShouldMatch("50%") .field("name",10)

   设置搜索方式时,使用multiMatchQuery 第一个参数: 搜索的关键字      第二个参数可以为多个:   要搜索的字段(filed)

   使用minimumShouldMatch  设置匹配度   这里是只要有一个词就算

   field  提升name 字段的得分 权限       每个结果搜索出来后都会有一个得分   这里设置name属性 提升10倍的得分

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //搜索方式
        //MultiMatchQuery
        searchSourceBuilder.query(QueryBuilders.multiMatchQuery("spring css","name","description")
                .minimumShouldMatch("50%")
                .field("name",10));
        //设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});
        //向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);

BoolQuery

   用于组合查询上述的查询方式

    1.定义一个  MultiMatchQueryBuilder      2.定一个  TermQueryBuilder             3.定一个BoolQueryBuilder

    4.使用 BoolQueryBuilder 将他们组合起来   

      boolQueryBuilder.must(multiMatchQueryBuilder);     boolQueryBuilder.must(termQueryBuilder);

     5.将  BoolQueryBuilder  放入searchSourceBuilder() 设置查询方式

    @Test
    public void testBoolQuery() throws IOException, ParseException {
        //搜索请求对象
        SearchRequest searchRequest = new SearchRequest("xc_course");
        //指定类型
        searchRequest.types("doc");
        //搜索源构建对象
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //boolQuery搜索方式
        //先定义一个MultiMatchQuery
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring css", "name", "description")
                .minimumShouldMatch("50%")
                .field("name", 10);
        //再定义一个termQuery
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("studymodel", "201001");

        //定义一个boolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(multiMatchQueryBuilder);
        boolQueryBuilder.must(termQueryBuilder);

        searchSourceBuilder.query(boolQueryBuilder);
    }

filter过滤器

   BoolQueryBuilder   不仅可以组合 普通的查询   还可以组合过滤器 性能更高   对查询出来的结果进行过滤

   boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel","201001"));        表示  只需要 studymodel字段为  201001的
  boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(90).lte(100));       表示过滤价格  大于等于90  小于等于100的

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //boolQuery搜索方式  先定义一个MultiMatchQuery
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("spring css", "name", "description")
                .minimumShouldMatch("50%")
                .field("name", 10);

        //定义一个boolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(multiMatchQueryBuilder);
        //定义过虑器
        boolQueryBuilder.filter(QueryBuilders.termQuery("studymodel","201001"));
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(90).lte(100));

        searchSourceBuilder.query(boolQueryBuilder);

sort排序

 对查询后结果进行排序,  searchSourceBuilder 使用

   searchSourceBuilder.sort("studymodel", SortOrder.DESC);
   searchSourceBuilder.sort("price", SortOrder.ASC);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //boolQuery搜索方式
        //定义一个boolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //定义过虑器
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));

        searchSourceBuilder.query(boolQueryBuilder);
        //添加排序
        searchSourceBuilder.sort("studymodel", SortOrder.DESC);
        searchSourceBuilder.sort("price", SortOrder.ASC);

  高亮 

  1. 定义高亮对象  HighlightBuilder( )

   2.在关键字前,后  设置标签 highlightBuilder.preTags("");                                                                                                           highlightBuilder.postTags("");

   3.设置需要高亮的字段   highlightBuilder.fields().add(new HighlightBuilder.Field("name"));

  4.设置源数据 高亮   searchSourceBuilder.highlighter(highlightBuilder);

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //boolQuery搜索方式先定义一个MultiMatchQuery
        MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery("开发框架", "name", "description")
                .minimumShouldMatch("50%")
                .field("name", 10);

        //定义一个boolQuery
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(multiMatchQueryBuilder);
        //定义过虑器
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(0).lte(100));

        searchSourceBuilder.query(boolQueryBuilder);
        //设置源字段过虑,第一个参数结果集包括哪些字段,第二个参数表示结果集不包括哪些字段
        searchSourceBuilder.fetchSource(new String[]{"name","studymodel","price","timestamp"},new String[]{});

        //设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("");
        highlightBuilder.postTags("");
        highlightBuilder.fields().add(new HighlightBuilder.Field("name"));
//        highlightBuilder.fields().add(new HighlightBuilder.Field("description"));
        searchSourceBuilder.highlighter(highlightBuilder);

        //向搜索请求对象中设置搜索源
        searchRequest.source(searchSourceBuilder);
        //执行搜索,向ES发起http请求
        SearchResponse searchResponse = client.search(searchRequest);

综合结构图

{ 
 
"_source" : [ "name", "studymodel", "description","price"], 
   "query": { 
 "bool" : { 
     "must":[  
         { 
    
        "multi_match" : { 
             
    "query" : "开发框架", 
                 
    "minimum_should_match": "50%", 
             
    "fields": [ "name^10", "description" ], 
             
    "type":"best_fields" 
    } 
    } 
             ], 
 
    "filter": [  
         
    { "range": { "price": { "gte": 0 ,"lte" : 100}}}  
        ]   
 } 
    }, 
   "sort" : [ 
        { 
        "price" : "asc" 
          } 
            ], 

"highlight": { 
    "pre_tags": [""], 
    "post_tags": [""],  
    "fields": { 
      "name": {}, 
      "description":{} 
    } 
  } 
}

 

 

你可能感兴趣的:(Elasticsearch)