ElasticSearch filter aggregation
I need to return the number of children for each parent. This is my decision:
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.
+3
source to share
1 answer
You can replace it ValueCount
with aggregation terms
. Thus, you will get the result as:
ParentId Count
1 4
2 3
My test case:
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});
The syntax for aggregating NEST terms is:
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))))));
Answer:
"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 this helps you.
+1
source to share