Reputation: 739
How can I dynamically combine multiple aggregations in one query dynamically?
I know to do it "hard-coded":
request.Aggregations = new TermsAggregation("agg_field1") {
Field = "field1"
}
&& new TermsAggregation("agg_field2") {
Field = "field2"
};
But since I use an array containing the fields I need something like the following. But I'm getting an compiler error because 'AggregationDictionary' and 'TermsAggregation' cannot be combined by the operator '&=':
string[] Fields = new[]{ "field1", "field2" }
foreach (string sField in Fields)
{
request.Aggregations &= new TermsAggregation("agg_" + sField)
{
Field = sField
};
}
I have article data with fields like "product", "brand", "modell". For this fields I want to get each distinct value by aggregation. It's for showing three comboboxes with the possible values for each field.
Upvotes: 1
Views: 1442
Reputation: 125538
There are a few different ways in which you could build up a collection of aggregations. The nearest to what you're trying to do would be
var request = new SearchRequest<object>();
string[] Fields = new[] { "field1", "field2" };
AggregationBase aggregations = null;
foreach (string sField in Fields)
{
var termsAggregation = new TermsAggregation("agg_" + sField)
{
Field = sField
};
if (aggregations == null)
{
aggregations = termsAggregation;
}
else
{
aggregations &= termsAggregation;
}
}
request.Aggregations = aggregations;
client.Search<object>(request);
which builds the following query
{
"aggs": {
"agg_field1": {
"terms": {
"field": "field1"
}
},
"agg_field2": {
"terms": {
"field": "field2"
}
}
}
}
Upvotes: 4