user1541069
user1541069

Reputation: 55

Count filtered data in Elasticsearch(ElasticClient nest)

I am using ElasticClient 2.4.4.

I have one query

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")
            ));

than I wanted to count how many items are with RegionSegments = s1. As I understand I should use Aggregations but cant find good example how solve this issue.Any ideas?

Upvotes: 0

Views: 713

Answers (1)

Russ Cam
Russ Cam

Reputation: 125528

If you simply need a count of each of s1, s2 and s3 RegionSegment documents, then you can do a multi_search for this, specifying a count search_type for all

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"))
    )
);

This produces the following request

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"}}}]}}}

The to get the total for each search result is similar to the following

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

Upvotes: 1

Related Questions