2015-09-14 56 views
4

我有一個Rails應用程序與ActiveRecord模型之間有聯繫。嵌套關聯 - elasticsearch-rails或耐嚼?

爲了簡單起見,可以說我有完全相同的數據庫架構中 - https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/examples/activerecord_associations.rb#L95

而且我要搜索名爲「約翰」文章作者。

Article.search('john')article.authors'按照預期指定的字段first_name和last_name。

我想要更具體一些,並說通過article.authors只通過first_name從文章搜索。

Article.search(authors: {first_name: 'john'})不起作用。

上述的正確方法是什麼?

也使用Elastic HQ,在文章索引中有作者。這是否意味着elasticsearch-rails索引是正確的並且嵌套了作者? elastic hq article mapping

回答

5

我假設你有可訪問和正在使用的ElasticSearch實例。如果你想使用嵌套實體查詢,你必須使用由chewy gem提供的接口,即定義自定義索引字段。這裏是vanilla documentation的例子。首先,你需要創建/app/chewy/article_index.rb

class ArticleIndex < Chewy::Index 
    define_type Article.published.includes(:author_name) do 
    # `published` above is example scope of published-only articles 
    # I guess you may have :title and :body fields in model 
    field :title, :body 
    # Here is custom index field with *full* author name. 
    # We use lambda to extract it from article: 
    field :author_name, value: ->(article) { "#{article.author.first_name} #{article.author.last_name}" } 
    end 
end 

現在查詢它爲:

UsersIndex.query(text: {author_name: 'John'}) 
# or 
UsersIndex.query(text: {author_name: 'Smith'}) 
# or even ... 
UsersIndex.query(text: {author_name: 'John Smith'}) 

更多閱讀:

乾杯!

+1

給了其他人足夠的時間後,我接受你的答案。我選擇了ElasticSearch-Rails作爲工作項目,但對於一個個人項目,我選擇了Chewy。從長遠來看,我可能會說耐嚼更好。 6個月後我們可能會切換到耐嚼:) –