karmi / retire

A rich Ruby API and DSL for the Elasticsearch search engine
http://karmi.github.com/retire/
MIT License
1.86k stars 533 forks source link

Indexing has_many :through associations #898

Open levelingup opened 10 years ago

levelingup commented 10 years ago

I'm trying to set up elasticsearch with associations with has_many :through, but I'm not getting any results when I have the following indexes:

  has_many :services, :through => :professionals
  after_touch() { tire.update_index }

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

  def self.search(params)
    tire.search(load: true, page: params[:page], per_page: 10) do
      query do
        boolean do
          must { string params[:q], default_operator: "AND" } if params[:q].present?
          #must { filter :term, loc: params[:loc] } if params[:loc]
        end
      end
      raise to_curl
    end
  end

  mapping do
    indexes :id, type: 'integer'
    indexes :user_id, type: 'integer'
    indexes :latitude
    indexes :longitude
    #indexes :service_name, type: 'string', :as => proc{service_name}
    #indexes :service_description, type: 'string', :as => proc{service_description}
    indexes :services do
      indexes :service, analyzer: 'snowball'
      indexes :description
    end
  end

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

  def service_name
    services.map(&:service)
    #self.service.service if self.service.present?
  end
  def service_description
    #services.description
    services.map(&:description)
    #self.service.description if self.service.present?
  end

I've tried various options, but I'm not getting any results that I should. I was hoping that someone can shed some light?

Thanks

FabianOudhaarlem commented 9 years ago

Try this:

has_many :services, through:  :professionals, after_add: [lambda { |a, c| a.__elasticsearch__.index_document }],
           after_remove: [lambda { |a, c| a.__elasticsearch__.index_document }]