RestClient的基本操作2

文档的条件查询

match查询

match匹配具体及分词内容

@Test
void testMatch() throws IOException {
    SearchRequest request = new SearchRequest("hotel");
    request.source().query(QueryBuilders.matchQuery("all","如家"));
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    //4、解析响应
    handleResponse(response);
}

term查询

term具体匹配,不分词

@Test
void testTerm() throws IOException {
    SearchRequest request = new SearchRequest("hotel");
    request.source().query(QueryBuilders.termQuery("city","上海"));
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    handleResponse(response);
}

range查询

range范围查询

@Test
void testRange() throws IOException {
    SearchRequest request = new SearchRequest("hotel");
    request.source().query(QueryBuilders.rangeQuery("price").gte(100).lte(2000));
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    handleResponse(response);
}

bool查询

多条件查询

@Test
void testBoolQuery() throws IOException {
    SearchRequest request = new SearchRequest("hotel");
    //组装bool条件
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    boolQueryBuilder.must(QueryBuilders.termQuery("city","上海"));
    boolQueryBuilder.must(QueryBuilders.termQuery("brand","如家"));
    boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(250));
    request.source().query(boolQueryBuilder);
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    handleResponse(response);

page分页

分页和排序

还记得我们mysql的分页吗?

@Test
void pageAndSort() throws IOException {
    int page = 1,size = 5;
    SearchRequest request = new SearchRequest("hotel");
    request.source().query(QueryBuilders.matchAllQuery());
    //排序
    request.source().sort("price", SortOrder.ASC);
    //分页
    request.source().from((page-1)*size).size(size);
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    handleResponse(response);
}

高亮显示

标签包裹会高亮显示

我们这里后端处理,当然前端也可以

@Test
void testHighlight() throws IOException {
    SearchRequest request = new SearchRequest("hotel");
    request.source().query(QueryBuilders.matchQuery("name","如家"));
    request.source().highlighter(new HighlightBuilder()
            .field("name").requireFieldMatch(false));
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    handleResponse(response);
}

封装的response解析方法

代码冗长,将解析单独封装

我的案例解析皆为此方法

private void handleResponse(SearchResponse response) {
    SearchHits searchHits = response.getHits();
    //4.1、获取总条数
    long total = searchHits.getTotalHits().value;
    System.out.println("共搜索到" + total + "条");
    //4.2、文档数组
    SearchHit[] hits = searchHits.getHits();
    for (SearchHit hit : hits) {
        String json = hit.getSourceAsString();
        HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
        //获取高亮结果
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        if(!CollectionUtils.isEmpty(highlightFields)){
            //根据字段获取高亮结果
            HighlightField highlightField = highlightFields.get("name");
            //获取高亮值
            String name = highlightField.getFragments()[0].string();
            //覆盖非高亮值
            if(name!=null){
                //判空处理
                hotelDoc.setName(name);
            }
        }
        System.out.println("hotelDoc=>" + hotelDoc);
    }
}

聚合数据

单个属性聚合

@Test
void testAggregation() throws IOException {
    //准备request
    SearchRequest request = new SearchRequest("hotel");
    //准备DSL
    //设置size、清除文档数据
    request.source().size(0);
    //聚合
    request.source().aggregation(AggregationBuilders
            .terms("brand")
            .size(20)
            .field("brand")) ;
    //发出请求
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    //解析结果
    Aggregations aggregations = response.getAggregations();
    Terms brands = aggregations.get("brand");
    List<? extends Terms.Bucket> buckets = brands.getBuckets();
    for (Terms.Bucket bucket: buckets){
        String key = bucket.getKeyAsString();
        System.out.println(key);
    }
}

多个属性聚合

@Test
void testAggregations() throws IOException {
    //准备request
    SearchRequest request = new SearchRequest("hotel");
    //准备DSL、限定查询范围
    //设置size、清除文档数据
    request.source().size(0);
    //聚合
    buildAggregation(request);
    //发出请求
    SearchResponse response = client.search(request,RequestOptions.DEFAULT);
    //解析结果
    Map<String,List<String>> map = new HashMap<>();
    Aggregations aggregations = response.getAggregations();
    //根据名称放入品牌结果
    List<String> brandList = getAggByName(aggregations,"brand");
    List<String> cityList = getAggByName(aggregations,"city");
    map.put("品牌",brandList);
    map.put("city",cityList);
    System.out.println(map);
}
private void buildAggregation(SearchRequest request) {
    request.source().aggregation(AggregationBuilders
            .terms("brand")
            .size(200)
            .field("brand")) ;
    request.source().aggregation(AggregationBuilders
            .terms("city")
            .size(200)
            .field("city")) ;
}
private List<String> getAggByName(Aggregations aggregations,String aggName) {
    Terms brands = aggregations.get(aggName);
    List<? extends Terms.Bucket> buckets = brands.getBuckets();
    List<String> brandList = new ArrayList<>();
    for (Terms.Bucket bucket: buckets){
        String key = bucket.getKeyAsString();
        brandList.add(key);
    }
    return brandList;
}

自动补全

自动补全需要pinyin分词器,需要在github上自行下载

@Test
void testSuggest() throws IOException {
    //准备request
    SearchRequest request = new SearchRequest("hotel");
    //准备DSL
    request.source().suggest(new SuggestBuilder().addSuggestion(
            "suggestions",
            //补全的字段
            SuggestBuilders.completionSuggestion("suggestion")
                    .prefix("sh")
                    .skipDuplicates(true)
                    .size(10)
    ));
    //发起请求
    SearchResponse response = client.search(request, RequestOptions.DEFAULT);
    //解析结果
    Suggest suggest = response.getSuggest();
    CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
    List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
    for(CompletionSuggestion.Entry.Option option :options){
        String text = option.getText().toString();
        System.out.println(text);
    }
}

总结

  • 准备request
  • 准备DSL、query的条件或者聚合分页处理等
  • 发出request
  • 解析response

你可能感兴趣的:(分布式组件,java,数据库,servlet)