# Adding geo distance to a top\_hits aggregation

**URL:** <https://discuss.elastic.co/t/adding-geo-distance-to-a-top-hits-aggregation/91494>\
**Category:** Elasticsearch\
**Created:** [June 30, 2017, 9:07pm UTC](https://discuss.elastic.co/t/adding-geo-distance-to-a-top-hits-aggregation/91494 "2017-06-30T21:07:33Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![practiscore](https://avatars.discourse-cdn.com/v4/letter/p/f1d935/32.png) [@practiscore](https://discuss.elastic.co/u/practiscore)\
**Post date:** [June 30, 2017, 9:07pm UTC](https://discuss.elastic.co/t/adding-geo-distance-to-a-top-hits-aggregation/91494/1 "2017-06-30T21:07:33Z")

</div>

I'm attempting to select the top hit from a distinct term sorted by distance. I have been able to get the top\_hits working correctly however I'm not able to order the buckets by the top\_hits distance.

The snippet #1 returns buckets by match\_uuid order. I have tired to include another agg next to `top`(Snippet #2) then add an `order` to `top_matchIds.terms`. I can't seem to figure out what value to set `order` as to sort the buckets by distance from origin.

Also, forgive for me for I have sinned. I'm using elasticsearch with PHP. If you need to convert syntax back to normal then `=>` is `:`, and `[]` are `{ }`.

Snippet #1

```
        "aggs" => [
    "top_matchIds" => [
        "terms" => [
            "field" => "match_uuid.keyword",
            "size" => 1000
        ],
        "aggs" => [
            "top" => [
                "top_hits" => [
                    "size" => 2,
                    "sort" => [
                        [
                            "_geo_distance" => [
                                "location" => $location,
                                "order" => "asc",
                                "unit" => "mi",
                            ]
                        ],
                        [
                            "search_date" => [
                                "order" => "desc"
                            ]
                        ]
                    ],
                ]
            ]
        ]
    ]
]

```

Snippet #2

```
    "distance" => [
        "geo_distance" => [
            "field" => "location",
            "origin" => $location['lat'].",".$location['lon'],
        ]
    ]
```

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 28, 2017, 9:07pm UTC](https://discuss.elastic.co/t/adding-geo-distance-to-a-top-hits-aggregation/91494/2 "2017-07-28T21:07:43Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
