嵌套关联 - elasticsearch-rails 还是耐嚼的?

Nested associations - elasticsearch-rails or chewy?

我有一个 Rails 应用程序,其中包含 ActiveRecord 模型,它们之间存在关联。

为了简单起见,假设我有与 - 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.authors 只按 first_name 搜索。

Article.search(authors: {first_name: 'john'}) 无效。

以上的正确做法是什么?

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

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

更多阅读:

干杯!