加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 嵌套关联 – elasticsearch-rails还是耐嚼?

发布时间:2020-12-17 02:55:44 所属栏目:百科 来源:网络整理
导读:我有一个带有ActiveRecord模型的Rails应用程序,它们之间有关联. 为简单起见,假设我的数据库架构与-https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/examples/activerecord_associations.rb#L95完全相同 我想搜索名为“John
我有一个带有ActiveRecord模型的Rails应用程序,它们之间有关联.

为简单起见,假设我的数据库架构与-https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/examples/activerecord_associations.rb#L95完全相同

我想搜索名为“John”的文章作者.

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

我想更具体一点,只能通过first_name通过article.authors搜索文章.

Article.search(作者:{first_name:’john’})不起作用.

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

同样使用Elastic HQ,在文章索引中有字段作者.这是否意味着elasticsearch-rails索引是正确的并且嵌套作者?

elastic hq article mapping

解决方法

我假设你有可访问和工作的ElasticSearch实例.如果要使用嵌套实体的查询,则必须使用耐嚼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'})

更多阅读材料:

> chewy gem documentation
>惊人的Toptal article

干杯!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读