2016-11-12 59 views
0

我使用Elasticsearch和Elasticsearch Rails gem。我有兩個通過ActiveRecord關聯的模型,我試圖用Elasticsearch對它們進行索引和搜索。Elasticsearch Rails索引問題

這裏是我的專賣店模式

store.rb

has_many :addresses 
has_many :jobs 

def as_indexed_json 
    self.as_json(include: { 
    customer: { include: { addresses: {}, jobs: {} } }, 
    vendors: {} 
    }) 
end 

settings index: { number_of_shards: 1 } do 
    mapping dynamic: 'false' do 
    indexes :id 
    indexes :store_number 
    indexes :manager 
    indexes :customer do 
     indexes :first_name 
     indexes :addresses do 
     indexes :city 
     indexes :state 
     end 
     indexes :jobs do 
     indexes :job_number 
     end 
    end 
    end 
end 

這裏是我的地址模型:

def as_indexed_json 

end 

settings index: { number_of_shards: 1 } do 
    mapping dynamic: 'false' do 
    indexes :city 
    indexes :state 
    end 
end 

我也使用Searchkit我的前端UI。 Searchkit能夠聚合並顯示商店模型中的所有屬性(例如商店編號和經理)。但是,它無法查看嵌套的項目。換句話說,我無法在客戶下面的工作中聚合和檢索job_number。我能夠查看客戶名稱等。我曾嘗試在作業和所有其他對象旁邊使用類型:「嵌套」,但這沒有什麼區別。我曾嘗試調整as_indexed_json而沒有任何運氣。任何人對此有任何想法?我沉迷於這一個。

回答

0

試着改變你的as_indexed_json方法是:

def as_indexed_json() { 
    hash = self.as_json() 
    hash['jobs'] = self.jobs.map(&:job_number) 
    hash['address_state'] = self.addresses.map(&:state) 
    hash['address_city'] = self.addresses.map(&:city) 
    hash 
} 

覆蓋的searchstore模型是這樣的:

def self.search(query) 
    @search_definition = { 
    query: {} 
    } 
    unless query.blank? 
    @search_definition[:query] = { 
    bool: { 
     should: [ 
     { 
      multi_match: { 
      query: query, 
      fields: ['store_number', 'manager', 'jobs', 'address_state', 'address_city'], 
      operator: 'and' 
      } 
     } 
     ] 
    } 
    } 
    else 
    @search_definition[:query] = { match_all: {} } 
    end 
    __elasticsearch__.search(@search_definition) 
end 

您還需要更改映射設置是這樣的:

settings index: { number_of_shards: 1 } do 
    mapping do 
    indexes :store_number, analyzer: 'keyword' 
    indexes :jobs, analyzer: 'keyword' 
    indexes :address_state, analyzer: 'keyword' 
    indexes :address_city, analyzer: 'keyword' 
    indexes :manager, type: 'multi_field' do 
      indexes :manager, analyzer: 'snowball' 
      indexes :tokenized, analyzer: 'simple' 
    end 
    end 
end 

Thes索引的設置僅僅是示例。您可以使用最適合您的用例的typesanalyzerstokenizers

有了這個當你搜索一個店由它的索引字段,並與job_numbercitystate就會得到結果,但如果你想使用社團如過濾器,搜索方法和映射會有所不同。

+0

感謝所有這些,我想我遵循你所說的話。我認爲唯一不確定的是當你說重寫as_indexed_json方法時。地址和工作都在客戶模型上。那麼,我應該把它放在客戶模型中嗎?我所擁有的層次是商店 - >顧客 - >地址或商店 - >顧客 - >工作。我瞭解self.addresses.map(&:city),只是想確定我放在哪裏。再次感謝您的幫助。 –

+0

@MikeRiley從你發佈的代碼中,'store'模型'has_many''地址'和'store'也'has_many''作業',我假設'store'是你可搜索的模型,即你想搜索「商店」記錄。如果是這樣的話,我發佈的所有內容都會進入「商店」模式。 –