【问题标题】:Nested associations - elasticsearch-rails or chewy?嵌套关联 - elasticsearch-rails 还是耐嚼的?
【发布时间】:2015-12-09 23:20:57
【问题描述】:

我有一个带有 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 中搜索。

我想更具体地说,从 Article 到 article.authors 仅按名字搜索。

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

上述操作的正确方法是什么?

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

【问题讨论】:

    标签: ruby-on-rails elasticsearch elasticsearch-rails


    【解决方案1】:

    我假设您有可访问且正常工作的 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'}) 
    

    更多阅读:

    干杯!

    【讨论】:

    • 在给其他人足够的时间之后,我接受你的回答。我为工作项目选择了 ElasticSearch-Rails,但对于个人项目,我选择了 Chewy。从长远来看,我可能会说 Chewy 更好。我们可能会在 6 个月后改用 Chewy :)
    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多