Adding geo distance to a top_hits aggregation

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'],
        ]
    ]

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