Java Code Examples for org.springframework.data.elasticsearch.core.query.FetchSourceFilter

The following examples show how to use org.springframework.data.elasticsearch.core.query.FetchSourceFilter. These examples are extracted from open source projects. 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 Project: ChengFeng1.5   Source File: ElasticSearchTest.java    License: 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 Project: spring-boot-demo   Source File: PersonRepositoryTest.java    License: 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 Project: spring-boot-demo   Source File: PersonRepositoryTest.java    License: 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 Project: spring-boot-demo   Source File: PersonRepositoryTest.java    License: 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 Project: onetwo   Source File: SimpleSearchQueryBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public NativeSearchQuery build(boolean rebuild){
		if(!rebuild && nativeSearchQuery!=null){
			return nativeSearchQuery;
		}
		
		if(queryBuilder!=null){
			searchQueryBuilder.withQuery(queryBuilder);
		}else if(matchAllIfQueryNotExists){
			searchQueryBuilder.withQuery(matchAllQuery());
		}
		if(booleanQuery!=null && booleanQuery.hasClauses()){
			booleanQuery.build();
			searchQueryBuilder.withFilter(booleanQuery.boolQuery);
		}
		this.nativeSearchQuery = searchQueryBuilder.build();
		this.nativeSearchQuery.addIndices(this.indices.toArray(new String[0]));
		this.nativeSearchQuery.addTypes(this.types.toArray(new String[0]));
		this.nativeSearchQuery.addSourceFilter(new FetchSourceFilter(includeSources, excludeSources));
		this.sorts.forEach(s->this.nativeSearchQuery.addSort(s));
//		built = true;
		return nativeSearchQuery;
	}
 
Example 6
Source Project: ChengFeng1.5   Source File: PurchaseInfoServiceImpl.java    License: 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 7
Source Project: sanshanblog   Source File: ElasticSearchService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 全部查询
 * 前期使用  应该尽量使用按类型搜索
 * 做返回字段判 不将content这种数据量大的进行返回到response中
 *
 * @param key
 * @param responseMsgVO
 */
public void queryAll(String key, Integer pageRows, Integer pageNum, ResponseMsgVO responseMsgVO) {
    //Es默认是从0开始分页 前端默认是从1开始分页 需要注意
    pageNum=pageNum-1;
    SourceFilter sourceFilter = new FetchSourceFilter(new String[]{}, new String[]{"content"});
    SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchQuery("_all", key)).withIndices("_all").withPageable(new PageRequest(pageNum, pageRows)).withSourceFilter(sourceFilter).build();
    template.query(query, (searchResponse) -> {
        ElasticResponseVO responseVO = assembleElasticReuturnSourceResponse(searchResponse);
        return responseMsgVO.buildOKWithData(responseVO);
    });
}
 
Example 8
Source Project: sanshanblog   Source File: ElasticSearchService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 博客信息查询
 *
 * @param key
 * @param responseMsgVO
 */
public void blogInfoSearch(String key, Integer pageRows, Integer pageNum, ResponseMsgVO responseMsgVO) {
    pageNum=pageNum-1;
    SourceFilter sourceFilter = new FetchSourceFilter(new String[]{}, new String[]{"content"});
    SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchQuery("_all", key)).withIndices(BLOGS_INDEX).withPageable(new PageRequest(pageNum, pageRows)).withSourceFilter(sourceFilter).build();
    template.query(query, (searchResponse) -> {
        ElasticResponseVO responseVO = assembleElasticReuturnSourceResponse(searchResponse);
        return responseMsgVO.buildOKWithData(responseVO);
    });
}
 
Example 9
Source Project: leyou   Source File: SearchService.java    License: 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);
}