0

I have documents in my index which have a nested object locations in them.

"locations": [
    {
        "name": "California",
        "coordinates": {
            "lat": 36.78,
            "long": -119.42
        }
    }, ...
]

I have written a terms aggregation to create buckets for location names that appear in the dataset:

"aggs": {
    "global": {
        "nested": {
            "path": "locations"
        },
        "aggs":{
            "locations": {
                "terms": { 
                    "field": "locations.name.keyword"
                }
            }
        }
    }
}

What I would like to do is create buckets for the full location object, so that I can use both the name and the coordinates of the location in my code.

Is there something like a terms aggregation that works on an object rather than just a keyword?

Or (as the coordinates are always the same for the same location) is it possible to return the coordinates of the first location for each bucket along with the count?

Carasel
  • 2,740
  • 5
  • 32
  • 51
  • Is your `locations` array mapped as a `nested` field? – Val May 01 '18 at 14:55
  • @Val it's not at the moment, but easily could be – Carasel May 01 '18 at 14:57
  • Well, you should, otherwise your buckets will be wrong. – Val May 01 '18 at 15:00
  • @Val Each location only appears a maximum of once per document, so I think the results should be ok, but you're right, it is meant to be mapped as nested. – Carasel May 01 '18 at 15:14
  • If it is an array, then it means you may have several locations (and in this case it should be nested), otherwise there's no point in having an array – Val May 01 '18 at 18:53
  • @Val I've updated the question to show the nested aggregation I'm using – Carasel May 02 '18 at 09:07

1 Answers1

1

Ok, great start. Now to get the coordinates of the first location for each bucket along with the count, you can do it by adding a top_hits sub-aggregation like this:

"aggs": {
    "global": {
        "nested": {
            "path": "locations"
        },
        "aggs":{
            "locations": {
                "terms": { 
                    "field": "locations.name.keyword"
                },
                "aggs": {
                   "location": {
                      "top_hits": {
                         "size": 1,
                         "_source": ["locations.coordinates"]
                      }
                   }
                }
            }
        }
    }
}
Val
  • 207,596
  • 13
  • 358
  • 360