class SearchProductService {

    public SearchProductConditionBO getSearchProductCondition(String keyword, Collection<String> fields) {
        // 创建 ES 搜索条件
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        // 筛选
        if (StringUtils.hasText(keyword)) { // 如果有 keyword ，就去匹配
            nativeSearchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(keyword,
                    "name", "sellPoint", "categoryName"));
        } else {
            nativeSearchQueryBuilder.withQuery(QueryBuilders.matchAllQuery());
        }
        // 聚合
        if (fields.contains("category")) { // 商品分类
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms("cids").field("cid"));
        }
        // 执行查询，返回结果
        return elasticsearchTemplate.query(nativeSearchQueryBuilder.build(), response -> {
            SearchProductConditionBO result = new SearchProductConditionBO();
            // categoryIds 聚合
            Aggregation categoryIdsAggregation = response.getAggregations().get("cids");
            if (categoryIdsAggregation != null) {
                result.setCids(new ArrayList<>());
                for (LongTerms.Bucket bucket  : (((LongTerms) categoryIdsAggregation).getBuckets())) {
                    result.getCids().add(bucket.getKeyAsNumber().intValue());
                }
            }
            // 返回结果
            return result;
        });
    }

}