4

I need to return the number of children for each parent. That is my solution:

foreach (var person in someList)
{
  var countingFields = _elasticsearchClient.Search<SomeModel>(esModel=> esModel
                            .Aggregations(aggregation => aggregation
                                .Filter("Parents", filter => filter
                                    .Filter(innerFilter => innerFilter
                                        .Term(field => field.ParentId, person.Id))
                                    .Aggregations(innerAggregation => innerAggregation
                                        .ValueCount("Counting", count => count
                                            .Field(field => field.ParentId))))));
}

I need help to improve this, I want to get the same data with only one connection to ElasticSearch.

1 Answer 1

1

You can replace ValueCount with terms aggregation. So you will get result as:

ParentId Count
1        4
2        3

My test data set:

client.Index(new SomeModel {Id = 1, ParentId = 1});
client.Index(new SomeModel {Id = 2, ParentId = 2});
client.Index(new SomeModel {Id = 3, ParentId = 3});
client.Index(new SomeModel {Id = 4, ParentId = 1});

NEST terms aggregation syntax:

var someList = new List<int>{1,2,3,4};

var countingFields = client.Search<SomeModel>(esModel => esModel
    .Aggregations(aggregation => aggregation
        .Filter("Parents", filter => filter
            .Filter(innerFilter => innerFilter
                .Terms(field => field.ParentId, someList))
            .Aggregations(innerAggregation => innerAggregation
                .Terms("Counting", count => count
                    .Field(field => field.ParentId))))));

Response:

"aggregations": {
   "Parents": {
      "doc_count": 4,
      "Counting": {
         "doc_count_error_upper_bound": 0,
         "sum_other_doc_count": 0,
         "buckets": [
            {
               "key": 1,
               "doc_count": 2
            },
            {
               "key": 2,
               "doc_count": 1
            },
            {
               "key": 3,
               "doc_count": 1
            }
         ]
      }
   }
}

Hope it helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.