実行環境
elasticsearch version 2.3.3
やりたいこと
- 特定の場所(自分とかユーザーとか***駅とか)の周囲何キロメートルのお店を検索
- 検索結果では近い順にお店を返す
- 検索結果ではお店までの距離も返す
まずデータを作る
マッピング定義
shops.jsonを作成
geo_point
のtypeを持つフィールドを用意する
{
"mappings": {
"shop": {
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"address": {
"type": "string"
},
"phone_number": {
"type": "string"
},
"latidude": {
"type": "double"
},
"longitude": {
"type": "double"
},
"created": {
"format": "dateOptionalTime",
"type": "date"
},
"updated": {
"format": "dateOptionalTime",
"type": "date"
},
"geo_location": {
"type": "geo_point"
}
}
}
}
}
インデックスを作る
$ curl -XPOST localhost:9200/shops?pretty -d @shops.json
データを投入
※geo_locationは[ 経度(longitude), 緯度(latitude) ]
緯度経度はここで調べられる
http://www.geocoding.jp/
curl -XPUT localhost:9200/shops/shop/1?pretty -d '
{
"id": "1",
"name": "Curry Shop",
"address": "東京都世田谷区経堂2丁目",
"phone_number": "000-0000-0000",
"latitude": 35.651045,
"longitude": 139.636139,
"created": "2015-09-01'T'05:26:07.062421",
"updated": "2015-10-02'T'03:02:51.777291",
"geo_location": [ 139.636139, 35.651045 ]
}
'
位置情報を検索する
検索クエリ
-
geo_location
には特定の場所(自分とかユーザーとか***駅とか)の経度緯度を設定 -
distance
には特定の場所の周囲の距離(検索範囲)を設定
curl localhost:9200/shops/shop/_search?pretty -d '
{
"query": {
"match_all" : {}
},
"filter": {
"and": [
{
"geo_distance": {
"distance": "5km",
"geo_location": [ 139.62464, 35.647656 ]
}
}
]
},
"sort": [
{
"_geo_distance": {
"geo_location": {
"lat": 35.647656,
"lon": 139.62464
},
"order": "asc",
"unit": "km",
"distance_type": "plane"
}
}
]
}
'
レスポンス
sort
はお店までの距離
{
"took" : 10,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1,
"max_score" : null,
"hits" : [ {
"_index" : "shops",
"_type" : "shop",
"_id" : "1",
"_score" : null,
"_source" : {
"id" : "1",
"name" : "Curry Shop",
"address" : "東京都世田谷区経堂4丁目",
"phone_number" : "000-0000-0000",
"latitude" : 35.651045,
"longitude" : 139.636139,
"created" : "2015-09-01T05:26:07.062421",
"updated" : "2015-10-02T03:02:51.777291",
"geo_location" : [ 139.636139, 35.651045 ]
},
"sort" : [ 1.3344915446870738 ]
} ]
}
}