4
votes

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

For the sake of simplicity, lets 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 want to search for Article author named 'John'.

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

I want to be more specific and say search from Article through article.authors by first_name only.

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

What is the correct way to do the above?

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

1

1 Answers

6
votes

I assume you have accessible and working ElasticSearch instance. If you want to use queries with nested entities you have to use interfaces provided by chewy gem i.e. define custom index field. Here is example from 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 query it as:

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

More readings:

Cheers!