Java Code Examples for org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder#addAggregation()

The following examples show how to use org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder#addAggregation() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElasticSearchTest.java    From ChengFeng1.5 with MIT License 6 votes vote down vote up
@Test
public void demo(){
    NativeSearchQueryBuilder builder=new NativeSearchQueryBuilder();
    // 不查询任何结果
    builder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));


    builder.addAggregation(
            AggregationBuilders.terms("品牌").field("subtitle"));
    // 2、查询,需要把结果强转为AggregatedPage类型
    AggregatedPage<PurchaseInfoDto> aggPage = (AggregatedPage<PurchaseInfoDto>) this.purchaseInfoRepository.search(builder.build());

    StringTerms agg = (StringTerms) aggPage.getAggregation("subtitle");
    // 3.2、获取桶
    List<StringTerms.Bucket> buckets = agg.getBuckets();
    // 3.3、遍历
    for (StringTerms.Bucket bucket : buckets) {
        // 3.4、获取桶中的key,即品牌名称
        System.out.println(bucket.getKeyAsString());
        // 3.5、获取桶中的文档数量
        System.out.println(bucket.getDocCount());
    }


}
 
Example 2
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 测试聚合,测试平均年龄
 */
@Test
public void agg() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 不查询任何结果
    queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));

    // 平均年龄
    queryBuilder.addAggregation(AggregationBuilders.avg("avg").field("age"));

    log.info("【queryBuilder】= {}", JSONUtil.toJsonStr(queryBuilder.build()));

    AggregatedPage<Person> people = (AggregatedPage<Person>) repo.search(queryBuilder.build());
    double avgAge = ((InternalAvg) people.getAggregation("avg")).getValue();
    log.info("【avgAge】= {}", avgAge);
}
 
Example 3
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 测试聚合,测试平均年龄
 */
@Test
public void agg() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 不查询任何结果
    queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));

    // 平均年龄
    queryBuilder.addAggregation(AggregationBuilders.avg("avg").field("age"));

    log.info("【queryBuilder】= {}", JSONUtil.toJsonStr(queryBuilder.build()));

    AggregatedPage<Person> people = (AggregatedPage<Person>) repo.search(queryBuilder.build());
    double avgAge = ((InternalAvg) people.getAggregation("avg")).getValue();
    log.info("【avgAge】= {}", avgAge);
}
 
Example 4
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 测试聚合,测试平均年龄
 */
@Test
public void agg() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 不查询任何结果
    queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));

    // 平均年龄
    queryBuilder.addAggregation(AggregationBuilders.avg("avg").field("age"));

    log.info("【queryBuilder】= {}", JSONUtil.toJsonStr(queryBuilder.build()));

    AggregatedPage<Person> people = (AggregatedPage<Person>) repo.search(queryBuilder.build());
    double avgAge = ((InternalAvg) people.getAggregation("avg")).getValue();
    log.info("【avgAge】= {}", avgAge);
}
 
Example 5
Source File: PurchaseInfoServiceImpl.java    From ChengFeng1.5 with MIT License 5 votes vote down vote up
@Override
public List<PurchaseInfoVo> getPurchaseInfo() {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    // 不查询任何结果
    builder.withSourceFilter(new FetchSourceFilter(new String[]{""}, null));


    builder.addAggregation(
            AggregationBuilders.terms("subtitle").field("subtitle")
                    .subAggregation(AggregationBuilders.avg("sales").field("sales")));
    // 2、查询,需要把结果强转为AggregatedPage类型
    AggregatedPage<PurchaseInfoDto> aggPage =
            (AggregatedPage<PurchaseInfoDto>) this.purchaseInfoRepository.search(builder.build());

    StringTerms agg = (StringTerms) aggPage.getAggregation("subtitle");
    // 3.2、获取桶
    List<StringTerms.Bucket> buckets = agg.getBuckets();
    List<PurchaseInfoVo> purchaseInfoVos= Lists.newArrayList();
    // 3.3、遍历
    for (StringTerms.Bucket bucket : buckets) {
        // 3.4、获取桶中的key,即品牌名称
        System.out.println(bucket.getKeyAsString());
        InternalAvg sales= (InternalAvg) bucket.getAggregations().asMap().get("sales");

        purchaseInfoVos.add(new PurchaseInfoVo(bucket.getKeyAsString(),sales.getValue()));
    }
    return purchaseInfoVos;
}
 
Example 6
Source File: EsProductServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
                    .subAggregation(AggregationBuilders.terms("attrIds")
                            .field("attrValueList.productAttributeId")
                            .subAggregation(AggregationBuilders.terms("attrValues")
                                    .field("attrValueList.value"))
                            .subAggregation(AggregationBuilders.terms("attrNames")
                                    .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example 7
Source File: EsProductServiceImpl.java    From mall-swarm with Apache License 2.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
            .subAggregation(AggregationBuilders.terms("attrIds")
                    .field("attrValueList.productAttributeId")
                    .subAggregation(AggregationBuilders.terms("attrValues")
                            .field("attrValueList.value"))
                    .subAggregation(AggregationBuilders.terms("attrNames")
                            .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example 8
Source File: EsProductServiceImpl.java    From macrozheng with Apache License 2.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
            .subAggregation(AggregationBuilders.terms("attrIds")
                    .field("attrValueList.productAttributeId")
                    .subAggregation(AggregationBuilders.terms("attrValues")
                            .field("attrValueList.value"))
                    .subAggregation(AggregationBuilders.terms("attrNames")
                            .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example 9
Source File: EsProductServiceImpl.java    From mall with Apache License 2.0 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues","attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs",QueryBuilders.termQuery("attrValueList.type",1))
                    .subAggregation(AggregationBuilders.terms("attrIds")
                            .field("attrValueList.productAttributeId")
                            .subAggregation(AggregationBuilders.terms("attrValues")
                                    .field("attrValueList.value"))
                            .subAggregation(AggregationBuilders.terms("attrNames")
                                    .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example 10
Source File: EsProductServiceImpl.java    From macrozheng-mall with MIT License 5 votes vote down vote up
@Override
public EsProductRelatedInfo searchRelatedInfo(String keyword) {
    NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
    //搜索条件
    if(StringUtils.isEmpty(keyword)){
        builder.withQuery(QueryBuilders.matchAllQuery());
    }else{
        builder.withQuery(QueryBuilders.multiMatchQuery(keyword,"name","subTitle","keywords"));
    }
    //聚合搜索品牌名称
    builder.addAggregation(AggregationBuilders.terms("brandNames").field("brandName"));
    //集合搜索分类名称
    builder.addAggregation(AggregationBuilders.terms("productCategoryNames").field("productCategoryName"));
    //聚合搜索商品属性,去除type=1的属性
    AbstractAggregationBuilder aggregationBuilder = AggregationBuilders.nested("allAttrValues")
            .path("attrValueList")
            .subAggregation(AggregationBuilders.filter("productAttrs")
            .filter(QueryBuilders.termQuery("attrValueList.type",1))
            .subAggregation(AggregationBuilders.terms("attrIds")
                    .field("attrValueList.productAttributeId")
                    .subAggregation(AggregationBuilders.terms("attrValues")
                            .field("attrValueList.value"))
                    .subAggregation(AggregationBuilders.terms("attrNames")
                            .field("attrValueList.name"))));
    builder.addAggregation(aggregationBuilder);
    NativeSearchQuery searchQuery = builder.build();
    return elasticsearchTemplate.query(searchQuery, response -> {
        LOGGER.info("DSL:{}",searchQuery.getQuery().toString());
        return convertProductRelatedInfo(response);
    });
}
 
Example 11
Source File: SearchService.java    From leyou with Apache License 2.0 4 votes vote down vote up
/**
 * 搜索商品
 *
 * @param request
 * @return
 */
public SearchResult search(SearchRequest request) {
    // 判断是否有搜索条件,如果没有,直接返回null。不允许搜索全部商品
    if (StringUtils.isBlank(request.getKey())) {
        return null;
    }

    // 1、初始化自定义查询构建器
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    //QueryBuilder basicQuery = QueryBuilders.matchQuery("all", request.getKey()).operator(Operator.AND);
    BoolQueryBuilder boolQueryBuilder = buildBooleanQueryBuilder(request);
    // 1.1、基本查询
    //queryBuilder.withQuery(basicQuery);
    queryBuilder.withQuery(boolQueryBuilder);
    // 通过sourceFilter设置返回的结果字段,我们只需要id、subTitle、skus
    queryBuilder.withSourceFilter(new FetchSourceFilter(new String[]{"id", "subTitle", "skus"}, null));

    // 1.2.分页排序
    // 获取分页参数
    Integer page = request.getPage();
    Integer size = request.getSize();
    // 添加分页
    queryBuilder.withPageable(PageRequest.of(page - 1, size));

    // 1.3、聚合
    // 聚合名称
    String categoryAggName = "categories"; // 商品分类聚合名称
    String brandAggName = "brands"; // 品牌聚合名称
    // 对商品分类进行聚合
    queryBuilder.addAggregation(AggregationBuilders.terms(categoryAggName).field("cid3"));
    // 对品牌进行聚合
    queryBuilder.addAggregation(AggregationBuilders.terms(brandAggName).field("brandId"));

    // 2、查询,获取结果
    AggregatedPage<Goods> goodsPage = (AggregatedPage<Goods>) this.goodsRepository.search(queryBuilder.build());

    // 3、解析查询结果
    // 3.1、分页信息
    Long total = goodsPage.getTotalElements();
    int totalPage = (total.intValue() + request.getSize() - 1) / request.getSize();
    // 3.2、商品分类的聚合结果
    List<Map<String, Object>> categories = getCategoryAggResult(goodsPage.getAggregation(categoryAggName));
    // 3.3、品牌的聚合结果
    List<Brand> brands = getBrandAggResult(goodsPage.getAggregation(brandAggName));

    // 根据商品分类个数判断是否需要聚合
    List<Map<String, Object>> specs = null;
    if (!CollectionUtils.isEmpty(categories) && categories.size() == 1) {
        // 如果商品分类只有一个才进行聚合,并根据分类与基本查询条件聚合
        specs = getParamAggResult((Long) categories.get(0).get("id"), boolQueryBuilder);
    }

    // 返回结果
    return new SearchResult(total, totalPage, goodsPage.getContent(), categories, brands, specs);
}
 
Example 12
Source File: EsServiceImpl.java    From mall with Apache License 2.0 2 votes vote down vote up
/**
 * 增加属性的聚合
 *
 * @param nativeSearchQueryBuilder 查询主体
 */
private void addAttributeAggregation(NativeSearchQueryBuilder nativeSearchQueryBuilder) {
    nativeSearchQueryBuilder.addAggregation(AggregationBuilders.nested("esAttributes", "esAttributes").subAggregation(AggregationBuilders.terms("attributeName").field("esAttributes.attributeName").subAggregation(AggregationBuilders.terms("attributeValue").field("esAttributes.attributeValue"))));
}