Search code examples
ruby-on-railsrubysearchkick

SearchKick search_data vs searchable


For the sake of this question, let's say I have two models:

  • Book, which has a name, created_at, updated_at, and an associated Author model.
  • Author, which has a name and birthdate.

For the purposes of searching, I want to two distinct searches:

  • Search Books by their name or author.name
  • Search Authors by their name

  1. Is search_data necessary if I only have direct mappings of model fields to ElasticSearch fields? For example, is it sufficient on my Author model to only have searchkick searchable %i[name], or do I also need:
def search_data
  {
    name: name
  }
end
  1. How do you define nested data in Searchkick to search the Book's Author.name? Currently, I would do something like this, however, it seems from the Nested Data section of the README that there might be another way to accomplish the same thing.
def search_data
  {
    name: name,
    author_name: author.name
  }
end
  1. What if a Book had many Authors? What is the suggested way to search a book by any of its author's names? Something like this is the best I could come up with so far:
def search_data
  {
    name: name,
    author_names: author.pluck(:name)
  }
end

Solution

    1. If you only need model fields, you don't need to define search_data. Searchkick does this automatically. You can check this with Author.first.search_data.

    2. Searchkick has limited support for nested data. The example you gave looks good.

    3. That's exactly what's suggested for multiple authors.