diff --git a/docs/extras/elasticsearch_rails.md b/docs/extras/elasticsearch_rails.md index f801b0422..bd44811fb 100644 --- a/docs/extras/elasticsearch_rails.md +++ b/docs/extras/elasticsearch_rails.md @@ -20,7 +20,7 @@ require 'pagy/extras/elasticsearch_rails' If you have an already paginated `Elasticsearch::Model::Response::Response` object, you can get the `Pagy` object out of it: ```ruby -@response = Model.search('*', from: 0; size: 10, ...) +@response = Model.search('*', from: 0, size: 10, ...) @pagy = Pagy.new_from_elasticsearch_rails(@response, ...) ``` diff --git a/lib/pagy/extras/elasticsearch_rails.rb b/lib/pagy/extras/elasticsearch_rails.rb index 7a40a5dba..68b078ce9 100644 --- a/lib/pagy/extras/elasticsearch_rails.rb +++ b/lib/pagy/extras/elasticsearch_rails.rb @@ -13,7 +13,11 @@ class Pagy def self.new_from_elasticsearch_rails(response, vars={}) vars[:items] = response.search.options[:size] || 10 vars[:page] = (response.search.options[:from] || 0) / vars[:items] + 1 - total = response.raw_response['hits']['total'] + total = if response.respond_to?(:raw_response) + response.raw_response['hits']['total'] + else + response.response['hits']['total'] + end vars[:count] = total.is_a?(Hash) ? total['value'] : total new(vars) end diff --git a/test/mock_helpers/elasticsearch_rails.rb b/test/mock_helpers/elasticsearch_rails.rb index a84fe341e..b8ad6a205 100644 --- a/test/mock_helpers/elasticsearch_rails.rb +++ b/test/mock_helpers/elasticsearch_rails.rb @@ -60,4 +60,31 @@ def self.search(*args) end end + + class ResponseES5 + + attr_reader :search, :response + + def initialize(query, options={}) + @search = Search.new(query, options) + @response = {'hits' => {'hits' => @search.results, 'total' => RESULTS[query].size}} + end + + def records + @response['hits']['hits'].map{|r| "R-#{r}"} + end + + def count + @response['hits']['hits'].size + end + + end + + class ModelES5 < Model + + def self.search(*args) + ResponseES5.new(*args) + end + + end end diff --git a/test/pagy/extras/elasticsearch_rails_test.rb b/test/pagy/extras/elasticsearch_rails_test.rb index a6a5bb40e..27b781a7a 100644 --- a/test/pagy/extras/elasticsearch_rails_test.rb +++ b/test/pagy/extras/elasticsearch_rails_test.rb @@ -182,6 +182,24 @@ _(pagy.vars[:link_extra]).must_equal 'X' end + it 'paginates response with defaults on Elasticearch 5' do + response = MockElasticsearchRails::ModelES5.search('a') + pagy = Pagy.new_from_elasticsearch_rails(response) + _(pagy).must_be_instance_of Pagy + _(pagy.count).must_equal 1000 + _(pagy.items).must_equal 10 + _(pagy.page).must_equal 1 + end + + it 'paginates response with vars on Elasticsearch 5' do + response = MockElasticsearchRails::ModelES5.search('b', from: 15, size: 15) + pagy = Pagy.new_from_elasticsearch_rails(response, link_extra: 'X') + _(pagy).must_be_instance_of Pagy + _(pagy.count).must_equal 1000 + _(pagy.items).must_equal 15 + _(pagy.page).must_equal 2 + _(pagy.vars[:link_extra]).must_equal 'X' + end end end