Rails:Elasticsearch:通过关联映射

时间:2013-11-01 05:13:54

标签: ruby-on-rails ruby-on-rails-3.2 associations elasticsearch tire

当我有has_many, :through关联时,我正在尝试索引模型,但没有显示任何结果。

class Business < ActiveRecord::Base
  include Tire::Model::Search
  include Tire::Model::Callbacks

  def self.search(params)
    tire.search(load: true) do
      query { string params[:q]} if params[:q].present?
    end
  end

  mapping do
    indexes :service_name
    indexes :service_description
    indexes :latitude
    indexes :longitude
    indexes :services do
      indexes :service
      indexes :description
    end
  end

  def to_indexed_json #returns json data that should index (the model that should be searched)
    to_json(methods: [:service_name, :service_description], include: { services: [:service, :description]})
  end

  def service_name
    services.map(&:service)
  end

  def service_description
    services.map(&:description)
  end

  has_many :professionals
  has_many :services, :through => :professionals

end

然后这是服务模型

class Service < ActiveRecord::Base
  attr_accessible :service, :user_id, :description
  belongs_to :professional
  belongs_to :servicable, polymorphic: true
end

我还使用这个重新索引:

rake environment tire:import CLASS=Business FORCE=true

我可以在Business中搜索项目,但是当我尝试在Service中搜索某些内容时,我得到一个空的结果。

3 个答案:

答案 0 :(得分:5)

在挣扎着映射之后,我创建了一个宝石,使搜索更容易一些。 https://github.com/ankane/searchkick

您可以使用search_data方法来完成此任务:

class Business < ActiveRecord::Base
  searchkick

  def search_data
    {
      service_name: services.map(&:name),
      service_description: services.map(&:description)
    }
  end
end

答案 1 :(得分:3)

我认为没有办法对与蒂尔的关联进行映射。你想要做的是使用:as方法和proc来定义易于搜索的字段。这样你也可以摆脱to_indexed_json方法(你真的需要)

mapping do
  indexes :service_name
  indexes :service_description
  indexes :latitude
  indexes :longitude    
  indexes :service_name, type: 'string', :as => proc{service_name}
  indexes :service_description, type: 'string', :as => proc{service_description}
end

答案 2 :(得分:0)

Tire可以与关联关联,我用它来对has_many关联进行索引,但还没有尝试过has_many,:还没有。尝试对象索引?

mapping do
  indexes :service_name
  indexes :service_description
  indexes :latitude
  indexes :longitude
  indexes :services, type: 'object',
    properties: {
      service: {type: 'string'}
      description: {type: 'string'}
    }
end

此外,有一个触摸方法可能是好的:

class Service < ActiveRecord::Base
  attr_accessible :service, :user_id, :description
  belongs_to :professional, touch: true
  belongs_to :servicable, polymorphic: true
end

和after_touch回调以更新索引。