使用Tire在ElasticSearch中映射geo_point字段

时间:2012-11-06 22:39:00

标签: ruby-on-rails geolocation elasticsearch tire

我正在尝试使用Tire gem索引Elasticsearch中的geo_point字段。这是我的ActiveRecord模型的轮胎映射:

class Availability < ActiveRecord::Base
  belongs_to :user
  attr_accessible :date, :latitude, :longitude

  include Tire::Model::Search
  include Tire::Model::Callbacks

  tire do
    mapping do
      indexes :id,                  type: 'integer',  index: 'not_analysed'
      indexes :user_id,                 type: 'integer',  index: 'not_analysed'
      indexes :user_firstname,      type: 'string',   as: 'user_firstname' 
      indexes :user_lastname,       type: 'string',   as: 'user_lastname' 
      indexes :user_level,          type: 'integer',  as: 'user_level' 
      indexes :date,                type: 'date'
      indexes :location,            type: 'geo_type', as: 'location'
    end
  end

  # def location
  #   "#{latitude},#{longitude}"
  # end

  def location
    [longitude.to_f, latitude.to_f]
  end

  def user_firstname
    user.firstname
  end

  def user_lastname
    user.lastname
  end

  def user_level
    user.level
  end
end

当我创建映射(bundle exec rake environment tire:import CLASS=Availability FORCE=true)时,Elasticsearch似乎忽略了geo_point字段的location类型。

以下是http://localhost:9200/availabilities/_mapping电话的结果:

{
  availabilities: {
    availability: {
      properties: {
        date: {...},
        id: {...},
        location: {
          type: "double"
        },
        user_firstname: {...},
        user_id: {...},
        user_lastname: {...},
        user_level: {...}
      }
    }
  }
}

位置字段被索引为文档上的double数组(http://localhost:9200/availabilities/_search的结果):

{
  id: 8,
  ...
  location: [
    2.301643,
    48.780651
  ]
}

当我将location方法更改为:

  def location
    "#{latitude},#{longitude}"
  end

根据文档(http://www.elasticsearch.org/guide/reference/mapping/geo-point-type.html)索引geo_point字段的另一种解决方案是,该结果为位置映射是:

  location: {
    type: "string"
  },

当然,location字段被索引为字符串:

{
  id: 4,
  ...
  location: "48.780651,2.301643"
}

知道我的映射中忽略了geo_point的原因吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

location索引类型输入错误。

您使用geo_type代替geo_point

indexes :location, type: 'geo_point', as: 'location'