Sanjay
Sanjay

Reputation: 111

Elastic Search: How to Fetch Results for Multiple combinations of 3 or more fields

In Elastic search, If i have documents with attribtutes say Foo Bar Baz Qux and a bunch of other attributes.

I need to query in such a way that i get the results in below manner

Foo Bar Baz Qux
foo1 bar1 baz1 qux1
foo1 bar1 baz1 qux2
foo1 bar1 baz2 qux1
foo1 bar1 baz2 qux2
foo1 bar2 baz1 qux1

Basically, I need all the combinations available with doc_count. Using the result, it can be said that With Foo=foo1, Bar=bar1, Baz=baz1, Qux=qux1, there are 20 documents/records

Crude Way is, to use terms aggregation inside termsaggregation(4 times in this case).

There should be some easier way to do this.

Thanks in Advance

Upvotes: 1

Views: 709

Answers (1)

Val
Val

Reputation: 217474

The way your mention with 4 embedded terms aggregation is a good one.

Another way would be to use a single terms aggregation with a script that would create a fake term made up of the four terms you're trying to aggregate, like this:

{
   "size": 0,
   "aggs": {
      "combinations": {
          "terms": {
              "script": "[doc.foo.value, doc.bar.value, doc.baz.value, doc.qux.value].join(',')"
          }
      }
   }
}

Note: make sure to enable dynamic scripting in order to use the above script aggregation.

Yet another solution in order to spare some cycles at search time would be to create that aggregate term at indexing time in another field, which you would then use in a single terms aggregation.

EDIT: If the order of results are important, and should be sorted based on doc_count of foo

{
   "size": 0,
   "aggs": {
        "primary": {
            "terms": {
                "field": "foo"
            },
           "aggs": {
               "combinations": {
                   "terms": {
                   "script": "[doc.foo.value, doc.bar.value, doc.baz.value, doc.qux.value].join(',')"
                   }
               }
           }
     }
}

Upvotes: 2

Related Questions