Ant*_*nov 4 ruby-on-rails elasticsearch elasticsearch-rails
我有一个带有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(authors: {first_name: 'john'}) 不起作用.
做上述事情的正确方法是什么?
同样使用Elastic HQ,在文章索引中有字段作者.这是否意味着elasticsearch-rails索引是正确的并且嵌套作者? 
我假设你有可访问和工作的ElasticSearch实例.如果要使用嵌套实体的查询,则必须使用chewygem 提供的接口,即定义自定义索引字段.这是vanilla文档的示例.首先,你需要创建/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
Run Code Online (Sandbox Code Playgroud)
现在查询为:
UsersIndex.query(text: {author_name: 'John'})
# or
UsersIndex.query(text: {author_name: 'Smith'})
# or even ...
UsersIndex.query(text: {author_name: 'John Smith'})
Run Code Online (Sandbox Code Playgroud)
更多阅读材料:
chewy 宝石文档干杯!
| 归档时间: |
|
| 查看次数: |
1501 次 |
| 最近记录: |