计算Elasticsearch中的过滤数据(ElasticClient嵌套)

时间:2016-09-05 16:30:57

标签: c# elasticsearch nest

我正在使用ElasticClient 2.4.4。

我有一个查询

var sample = client.Search<TestMenuItem>(s => s
            .Query(q =>
                q.Term(p => p.RegionSegments, "s1")
                && q.Term(p => p.RegionSegments, "s2")
                 && q.Term(p => p.RegionSegments, "s3")
            ));

比想要计算RegionSegments = s1的项数。 据我所知,我应该使用聚合,但无法找到解决这个问题的好例子。任何想法?

1 个答案:

答案 0 :(得分:1)

如果您只需要对s1s2s3 RegionSegment文档中的每一个进行计数,那么您可以为此执行multi_search,指定一个计数{{ 3}}为所有

var multiSearchResponse = client.MultiSearch(ms => ms
    // this is the default index for multi_search. Can override
    // on each Search call if needed
    .Index<TestMenuItem>()
    // this is the default type for mulit_search. Can override
    // on each search call if needed
    .Type<TestMenuItem>()
    // this is the default search_type. Can override on
    // each search call if needed
    .SearchType(SearchType.Count)
    .Search<TestMenuItem>("s1", s => s
        .Query(q => +q.Term(p => p.RegionSegments, "s1"))
    )
    .Search<TestMenuItem>("s2", s => s
        .Query(q => +q.Term(p => p.RegionSegments, "s2"))
    )
    .Search<TestMenuItem>("s3", s => s
        .Query(q => +q.Term(p => p.RegionSegments, "s3"))
    )
);

这会产生以下请求

POST http://localhost:9200/testmenuitem-index/testmenuitem/_msearch?search_type=count 
{}
{"query":{"bool":{"filter":[{"term":{"regionSegments":{"value":"s1"}}}]}}}
{}
{"query":{"bool":{"filter":[{"term":{"regionSegments":{"value":"s2"}}}]}}}
{}
{"query":{"bool":{"filter":[{"term":{"regionSegments":{"value":"s3"}}}]}}}

获取每个搜索结果的总计类似于以下

var s1Total = multiSearchResponse.GetResponse<TestMenuItem>("s1").Total;