2015-09-14 132 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个月后我们可能会切换到耐嚼:) –