首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套关联- elasticsearch-rails还是chewy?

嵌套关联- elasticsearch-rails还是chewy?
EN

Stack Overflow用户
提问于 2015-09-14 02:47:45
回答 1查看 2.1K关注 0票数 4

我有一个带有ActiveRecord模型的Rails应用程序,它们之间有关联。

为了简单起见,让我们假设我的DB模式与- associations.rb#L95中的完全相同。

我想找一个名叫“约翰”的文章作者。

Article.search('john')按预期在article.authors的指定字段first_name和last_name中搜索。

我想说得更具体一些,只想通过first_name .从文章中搜索

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

做以上事情的正确方法是什么?

还使用弹性总部,在文章索引中有字段作者。这是否意味着elasticsearch索引是正确的和嵌套的作者?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-14 08:23:41

我假设您有可访问的和正在工作的ElasticSearch实例。如果要对嵌套实体使用查询,则必须使用chewy gem提供的接口,即定义自定义索引字段。下面是来自香草文献的示例。首先,您需要创建/app/chewy/article_index.rb

代码语言:javascript
复制
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

现在将其查询为:

代码语言:javascript
复制
UsersIndex.query(text: {author_name: 'John'})
# or
UsersIndex.query(text: {author_name: 'Smith'})
# or even ...
UsersIndex.query(text: {author_name: 'John Smith'}) 

更多读数:

干杯!

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32556637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档