当前位置: 首页 > 工具软件 > Dante Cloud > 使用案例 >

spring cloud elasticsearch组合查询,高亮,聚合函数

隗瑞
2023-12-01

安装教程参考

https://blog.csdn.net/u011421988/article/details/115465901

1.在pom文件引入相关的jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
     <groupId>org.projectlombok</groupId>
     <artifactId>lombok</artifactId>
 </dependency>
 <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.75</version>
 </dependency>

2.创建acount实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private Long accountNumber;

    private Long balance;

    private String firstname;

    private String lastname;

    private Integer age;

    private String gender;

    private String address;

    private String employer;

    private String email;

    private String city;

    private String state;
}

3.组合查询代码

@SneakyThrows
@Test
void boolSearch() {
    // 指定搜索索引
    SearchRequest searchRequest = new SearchRequest(BANK_INDEX);
    // 组装搜索条件
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    sourceBuilder.query(QueryBuilders.boolQuery()
            .must(QueryBuilders.matchQuery("city", "Brogan Dante")));
    //sourceBuilder.query(QueryBuilders.boolQuery()
    //        .must(QueryBuilders.matchQuery("age", 30))
                // 范围查询
    //        .filter(QueryBuilders.rangeQuery("balance").gte(2000).lte(3000))
    //);
    //高亮显示
    HighlightBuilder highlightBuilder = new HighlightBuilder();
    highlightBuilder.field("city");
    highlightBuilder.requireFieldMatch(false);
    highlightBuilder.preTags("<span style='color:red'>");
    highlightBuilder.postTags("</span>");
    sourceBuilder.highlighter(highlightBuilder);

    // 添加搜索数据源
    searchRequest.source(sourceBuilder);
    // 返回结果
    SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    log.info("searchResponse>>{}", searchResponse);

    SearchHit[] hits = searchResponse.getHits().getHits();
    for (SearchHit hit : hits) {
        Map<String, HighlightField> highlightFields = hit.getHighlightFields();
        // 获取高亮查询字段
        HighlightField city = highlightFields.get("city");
        Map<String, Object> source = hit.getSourceAsMap();
        //转换成实体方便返回
        Account account = JSON.parseObject(JSON.toJSONString(source), Account.class);
        if (null != city){
            Text[] texts = city.fragments();
            String new_city = "";
            for (Text text : texts) {
                new_city += text;
            }
            account.setCity(new_city);
        }
        log.info("account-->{}", account);
    }
}

4.聚合查询

@SneakyThrows
@Test
void aggregation(){
    SearchRequest searchRequest = new SearchRequest(BANK_INDEX);

    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    // 字符串分组的字段需要加  .keyword 不然会报错
    TermsAggregationBuilder aggregationBuilder = AggregationBuilders.terms("group_by_state")
            .field("state.keyword")
            .size(50)
            .order(BucketOrder.aggregation("average_balance", false))
            // 子集合
            .subAggregation(AggregationBuilders.avg("average_balance").field("balance"));
    sourceBuilder.aggregation(aggregationBuilder);

    searchRequest.source(sourceBuilder);
    SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
    log.info("searchResponse>>{}", searchResponse);
}

5.更多聚合操作可参考中文文档

https://learnku.com/docs/elasticsearch73/7.3/article-11/6889

 类似资料: