Search code examples
ruby-on-railselasticsearchsearchkick

Search Kick Rails 5


Quick one.

I am using Searchkick gem for searching in my Rails app. I notice if I try search some text in the Post model it works fine.

Everything is set up correctly however, say I wish to search for author of the Post. It's example relation is Post.user.name

When I search "users name" I get no results. I suspect it is to do with the data being in the User model and not the Post model but in my Post views I can see this as a string.

Is this something simple I am missing? I thought addding

searchkick inheritance: true

to my Post model and reindexing the Post and User model then it would work but nothings changed.

Any ideas? Thanks.


Solution

  • Searchkick is backed by ElasticSearch. All of the searching happens there - not your database. You need to get the data you want to search on in to ElasticSearch somehow. Searchkick provides this via indexing your data with the search_data method (https://github.com/ankane/searchkick#indexing). So if you had an association that had a field you wanted to search on, you can follow something similar to the example set forth on Searchkick's Github page, and do (for your case):

    class Post
    
      belongs_to :author, class_name: 'User' # or whatever your association is
    
      def search_data
        {
           title: title,
           author_name: author.name
        }
      end
    end
    

    Don't forget to reindex afterwards, so you can see the results.

    Post.reindex
    

    And don't forget that if your association's data changes, like if your Author's name goes from Bob to Robert, the data is not automatically synced. You need to manually call Post.reindex, or set up an after_commit hook on Author that calls out to reindex Post when an author changes. See the docs for more information about that.