如何在elasticsearch索引中添加地理位置

时间:2017-08-08 12:26:00

标签: php elasticsearch

我正在使用elasticsearchphp,我希望使用地理距离查询进行搜索,但在阅读谷歌上的一些文章后,我必须在我当前的索引代码中添加geo location但未获得任何想法如何添加。

$indexed = $client->index([
    'index' => 'users',
    'type' => 'user',
    'body' => [
        'name' => $name,
        'email' => $email,
        'company' => $company,
        'phone' => $phone,
        'streetAddress' => $streetAddress,
        'route' => $route,
        'city' => $locality,
        'state' => $state,
        'postalCode' => $postalCode,
        'country' => $country,
        'latitude' => $latitude,
        'longitude' => $longitude,
        'content' => $content,
        'date' => strtotime(date('Y-m-d H:i:s'))
    ]
]);

我指的是这篇Geo Location and Search文章,但没有想到如何实现和使用搜索查询。

有什么想法吗?

感谢。

1 个答案:

答案 0 :(得分:0)

在您的文档中,您需要注入位置,如下所示:

$indexed = $client->index([
'index' => 'users',
'type' => 'user',
'body' => [
    'name' => $name,
    'email' => $email,
    'company' => $company,
    'phone' => $phone,
    'streetAddress' => $streetAddress,
    'route' => $route,
    'city' => $locality,
    'state' => $state,
    'postalCode' => $postalCode,
    'country' => $country,
    'content' => $content,
    'date' => strtotime(date('Y-m-d H:i:s')),
    'location' => [
        'lat' => $latitude,
        'lon' => $longitude
    ]
]
]);

您还需要在文档中添加属性(mapping):

请求弹性搜索,例如:localhost:9200/users/_mapping/user

  "properties" : {
        "location" : {
            "type" : "geo_point"
        }
  }

并在您发送的查询中:

{
"filtered" : {
    "query" : {
    },
    "filter" : {
        "geo_distance" : {
            "distance" : "12km",
            "user.location" : {
                "lat" : 40,
                "lon" : -70
            }
        }
    }
}
}