1

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.

1 Answer 1

4

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"
      }
    }
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Russ cam, Please help on this stackoverflow.com/questions/54453469/…

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.