我有一个带有ActiveRecord模型的Rails应用程序,它们之间有关联。
为了简单起见,让我们假设我的DB模式与- associations.rb#L95中的完全相同。
我想找一个名叫“约翰”的文章作者。
Article.search('john')按预期在article.authors的指定字段first_name和last_name中搜索。
我想说得更具体一些,只想通过first_name .从文章中搜索
Article.search(authors: {first_name: 'john'})不起作用。
做以上事情的正确方法是什么?
还使用弹性总部,在文章索引中有字段作者。这是否意味着elasticsearch索引是正确的和嵌套的作者?

发布于 2015-09-14 08:23:41
我假设您有可访问的和正在工作的ElasticSearch实例。如果要对嵌套实体使用查询,则必须使用chewy gem提供的接口,即定义自定义索引字段。下面是来自香草文献的示例。首先,您需要创建/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'}) 更多读数:
干杯!
https://stackoverflow.com/questions/32556637
复制相似问题