LoginSignup
1
3

More than 5 years have passed since last update.

Elasticsearchで位置情報検索をする

Posted at

位置情報を使った検索をしたくて調べたので、そのメモです。

環境

  • elasticsearch 5系
  • ruby 2.4
  • rails 5.1
  • elasticsearch-rails

やったこと

mappingは以下のようにしました。

{
  "es_index_name_place":
    {
      "aliases":{},
      "mappings":{
        "place":{
          "_all":
            {
              "enabled":true,
              "analyzer":"kuromoji_analyzer"},
              "properties":{
               "id":
                {"type":"integer"},
               "location":
                 {
                   "type":"geo_point",
                   "fields":{
                     "lat":{"type":"keyword"},
                     "lon":{"type":"keyword"}
                   }
    // 以下省略 

}

上記のようにlocationというpropertyを定義してtypeをgeo_pointにします。で、緯度経度の値をlatとlonに入れるようにします。ここを違う値にしていたのですが、それだとmapping作成時にerrorが出て、(lat、lonが定義されていないというエラー)ダメだったので。
またtypeはkeywordです。ここもそれでないと怒られました。

検索

検索は以下のようにします

{
    "query": {
        "bool" : {
            "must" : {
                "match_all" : {}
            },
            "filter" : {
                "geo_distance" : {
                    "distance" : "20km",
                    "location" : {
                        "lat" : 40,
                        "lon" : -70
                    }
                }
            }
        }
    }
}

これだけです。このgeo_distanceを使うとlatとlonで指定した緯度経度の場所を中心にして半径20kmの範囲で検索します。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3