Search code examples
ruby-on-railselasticsearchelasticsearch-aggregationsearchkick

Searchkick aggregations by a model's class


My searchkick implementation searches across multiple indexes. It looks like this:

@results = Searchkick.search(
  params[:query],
  index_name: [Actors, Producers, Directors],
  fields: ["name"],
  indices_boost: {Actors => 4, Producers => 8, Directors => 2},
  page: params[:page],
  per_page: cookies[:per_page]
  )

How can I implement aggregations so I can filter the results based on class (actors, producers, directors)?


Solution

  • I was able to fix this by adding the following search_data to my model.

    def search_data
     {
       name: name,
       class_name: self.class.name
     }
    end
    

    And then updated the controller with:

    @results = Searchkick.search(
      params[:query],
      index_name: [Actors, Producers, Directors],
      fields: ["name"],
      indices_boost: {Actors => 4, Producers => 8, Directors => 2},
      aggs: {class_name:{}},
      page: params[:page],
      per_page: cookies[:per_page]
      )