Nested associations - elasticsearch rails or chewable?

I have a Rails application with ActiveRecord models that have associations between them.

For simplicity, let's say I have exactly the same DB schema as in https://github.com/elastic/elasticsearch-rails/blob/master/elasticsearch-model/examples/activerecord_associations.rb#L95

And I would like to find the author of the article under the name "John".

Article.search('john') searches the specified fields for article.authors first_name and last_name as expected.

I want to be more specific and say search from an article through article.authors only with the name first_name.

Article.search(authors: {first_name: 'john'}) does not work.

What is the right way to do this?

Also using Elastic HQ, there are field authors in the article index. Does this mean that elasticsearch-rails indexing is correct and nested by the authors?elastic hq article mapping

+4
source share
1 answer

I assume that you have an available and working instance of ElasticSearch. If you want to use queries with nested objects, you need to use the interfaces provided by chewygem ie Define a custom index field. Here is an example from the vanilla documentation . First of all you need to create/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

Now request it as:

UsersIndex.query(text: {author_name: 'John'})
# or
UsersIndex.query(text: {author_name: 'Smith'})
# or even ...
UsersIndex.query(text: {author_name: 'John Smith'}) 

Other readings:

Hurrah!

+5
source

Source: https://habr.com/ru/post/1607210/


All Articles