从java中的elasticsearch查询返回一定数量的文档

时间:2014-10-16 12:44:23

标签: java elasticsearch

我正在尝试限制我的查询返回的文档大小。我想让我们只回10个文档,我的查询通常只显示22,我将如何购买设置返回输出的限制。我知道我可以通过创建一个列表并添加到该列表来限制列表大小,但我想在查询级别上执行此操作。 我的查询:提前致谢:)

ueryBuilder raceGenderQuery = QueryBuilders.boolQuery()
            .must(termQuery("lep_etg_desc", "indian"))
            .must(termQuery("lep_gen_desc", "male"));

    Set<String> suburbanLocationSet = new HashSet<String>();
    suburbanLocationSet.add("queensburgh");
    suburbanLocationSet.add("umhlanga");
    suburbanLocationSet.add("tongaat");
    suburbanLocationSet.add("phoenix");
    suburbanLocationSet.add("shallcross");
    suburbanLocationSet.add("balito");

    //Build the necessary location query.
    QueryBuilder locationQuery = QueryBuilders.boolQuery().must(termsQuery("lep_suburb_home", suburbanLocationSet));

    //Combine all Queries so that its filtered to get exact results.
    FilteredQueryBuilder finalSearchQuery = QueryBuilders.filteredQuery(QueryBuilders.boolQuery().must(raceGenderQuery).must(locationQuery), FilterBuilders.boolFilter().must(FilterBuilders.rangeFilter("lep_age").gte(25).lte(45)).must(FilterBuilders.rangeFilter("lep_max_income").gte(25000).lte(45000)));

    //Run Query through elasticsearch iterating through documents in the traceps index for query matches.
    List<Leads> finalLeadsList = new ArrayList<Leads>();
    for (Leads leads : this.leadsRepository.search(finalSearchQuery)) {
        finalLeadsList.add(leads);
    }

1 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

    SearchResponse response = client.prepareSearch().setSearchType(SearchType.QUERY_THEN_FETCH).setSize(10).setQuery(finalSearchQuery).execute().get

您必须使用QUERY_THEN_FETCH才能准确返回size个结果,否则会从每个分片中获得size个结果。