Elasticsearch 7.2 在 Laravel 中實踐 --經緯度及距離查詢

mution發表於2019-09-26

上一篇文件中選擇的擴充套件<babenkoivan/scout-elasticsearch-driver>,該擴充套件已有方法whereGeoDistance查詢指定經緯度範圍內的資料,但是無法根據距離排序,由於依賴於laravel-scout,而該擴充套件並沒有實現Geo的sort,但是經過透過Elasticsearch官方文件及該擴充套件原始碼的閱讀,還是找到兩個途徑實現該功能:
1.1在ScoutBuilderServiceProvider的boot中macro排序的sort方法:

    public function boot()
    {
        \Laravel\Scout\Builder::macro('sortRaw', function (array $value) {

            $this->orders[] = $value;

            return $this;
        });
    }

1.2在ElasticEngine的map方法中增加對sort的處理

                    if (isset($hit['highlight'])) {
                        $model->highlight = new Highlight($hit['highlight']);
                    }
                    if (isset($hit['sort'])) {
                        $model->sort = $hit['sort'];
                    }

1.3呼叫

        $para = $request->input('para');
        $position = [130, -20];
        $sort_geo_distance = [
            '_geo_distance' => [
                'location' => $position,
                'order' => 'asc',
                'unit' => 'km',
                'distance_type' => 'plane',
            ]
        ];
        $re = Shop::search($para)
                 ->whereGeoDistance('location', $position, '10km')
                 ->sortRaw($sort_geo_distance) ->get();

1.4 由於該方法涉及到擴充套件原始碼的修改,所有並不推薦使用,下面是第二種比較通用的實現
2.使用已有的searchRaw方法實現排序

        $position = [130, -20];
        $sort_geo_distance = [
            '_geo_distance' => [
                'location' => $position,
                'order' => 'asc',
                'unit' => 'km',
                'distance_type' => 'plane',
            ]
        ];
        $query = [
            "bool" => [
                'must' => [
                    'match' => [
                        'name' => $para
                    ]
                ],
                "filter" => [
                    "geo_distance" => [
                        "distance" => "10000km",
                        "location" => $position
                    ]
                ]
            ]
        ];
        $result = Shop::searchRaw([
                      'query' => $query,
                      'sort' => $sort_geo_distance
        ]);

由於返回結果巢狀太多其他資料,並不直觀,所以封裝一個方法來對結果進行處理

function format_elastic_result($results)
    {
        return Collection::make($results['hits']['hits'])
            ->map(function ($hit)  {
                $model = $hit['_source'];

                if (isset($hit['highlight'])) {
                    $model['highlight'] = new Highlight($hit['highlight']);
                }
                if (isset($hit['sort'])) {
                    $model['sort'] = $hit['sort'];
                }
                return $model;
            })
            ->filter()
            ->values();
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章