Search code examples
ruby-on-railssearchkick

SearchKick get total results count


I am using SearchKick for searching the data. And i am performing pagination. How can i get the total result count in this case:

My searchkick result:

       #<Searchkick::Results:0x007faeeef8ed88
   @facets=nil,
   @max_score=0.0,
   @options=
    {:load=>true,
     :payload=>
      {:query=>{:match_all=>{}},
       :size=>20,
       :from=>0,
       :sort=>{"created_at"=>:desc},
       :filter=>{:and=>[{:term=>{"sub_category_id"=>2}}]},
       :fields=>[]},
     :size=>20,
     :from=>0,
     :term=>"*"},
   @response=
    {"took"=>4,
     "timed_out"=>false,
     "_shards"=>{"total"=>5, "successful"=>5, "failed"=>0},
     "hits"=>
      {"total"=>1925,
       "max_score"=>nil,
       "hits"=>
        [{"_index"=>"products_..", "_type"=>"product", "_id"=>"..", "_score"=>nil, "sort"=>[..]},....]}},
   @results=
    [#<Product>,...]....

One more thing i am not able to do:

SearchKickResult.response

It returns me error saying:

undefined methodresponse'`


Solution

  • Searchkick provides a #total_count method which counts the total hits of the response:

    https://github.com/ankane/searchkick/blob/7a24684bb470abd5ceca7a40b21d28584b910a4c/lib/searchkick/results.rb#L89

    def total_count
      response["hits"]["total"]
    end
    alias_method :total_entries, :total_count