WoJ
WoJ

Reputation: 30007

How to aggregate over several alternative terms?

I have documents which may have several, well defined, attributes I want to aggregate over:

{
  name: "john",
  age: "51"
},
{
  name: "mary",
  years_since_born: "34"
},
{
  name: "mike",
  age: "34"
},

The fields age and years_since_born mean the same thing, but have a different name.

I would like to aggregate the documents by age OR years_since_born. Is that possible?

I tried to push a bool condition in my terms but it apparently only accepts strings.

Upvotes: 0

Views: 31

Answers (1)

Val
Val

Reputation: 217344

You can do this using a script in your terms aggregation, like this:

POST index/_search
{
  "size": 0,
  "aggs": {
    "ages": {
      "terms": {
        "script": "params._source.age != null ? params._source.age : params._source.years_since_born"
      }
    }
  }
}

Note: however, the performance can get bad depending on your document count. It'd be better if all documents use the same field.

Upvotes: 1

Related Questions