4

我試圖索引一個模型,當我有一個has_many, :through關聯,但沒有結果顯示。Rails:Elasticsearch:通過關聯映射

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 

我可以搜索業務的項目,但是當我試圖尋找的東西在服務中,我得到一個空的結果。

回答

3

我不相信有一種方法可以與Tire建立關聯關係。您想要做的是使用: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 
+0

這種方法仍然不適用於我。我仍然獲得零輸出 – hellomello

+0

您是否重新編制了模型索引?如果是這樣,請嘗試使用Sense chrome擴展來瀏覽您創建的索引,以查看您是否在新列中有任何數據。 – Houen

+0

我做了重新索引模型,並檢查了感覺,它只是給了我空陣列。我不確定它是否正在從'services'獲得模型 – hellomello

3

與測繪掙扎後,我創建了一個寶石,使搜索更容易一點。 http://ankane.github.io/searchkick/

可以使用search_data方法來實現:

class Business < ActiveRecord::Base 
    searchkick 

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

我還需要輪胎嗎?因爲我試圖使用搜索引擎,但是我使用Tire獲得了這個錯誤,並且我試圖斷開它,現在我無法在沒有Tire的情況下進行搜索。 – hellomello

+0

Searchkick在內部使用Tire,但是當您使用它時,您想要移除所有與輪胎相關的代碼,如to_indexed_json,mapping等。 –

+0

我收到500錯誤'Tyre :: Search :: SearchRequestFailed',我刪除了所有內容只是做了@biz = Business.search params [:q]',我還保留了'include tyre'東西 – hellomello

0

輪胎能與協會聯繫起來,我已經將它用於上的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回調更新索引。

+0

你能跟我分享你做過has_many協會嗎? –