diff --git a/lib/chewy/query.rb b/lib/chewy/query.rb index cc93d65a8..bf411d93b 100644 --- a/lib/chewy/query.rb +++ b/lib/chewy/query.rb @@ -3,6 +3,7 @@ require 'chewy/query/scoping' require 'chewy/query/loading' require 'chewy/query/pagination' +require 'chewy/query/existance' module Chewy # Query allows you to create ES search requests with convenient @@ -17,6 +18,7 @@ class Query include Scoping include Loading include Pagination + include Existance delegate :each, :count, :size, to: :_collection alias_method :to_ary, :to_a diff --git a/lib/chewy/query/existance.rb b/lib/chewy/query/existance.rb new file mode 100644 index 000000000..f41c8b053 --- /dev/null +++ b/lib/chewy/query/existance.rb @@ -0,0 +1,13 @@ +module Chewy + class Query + module Existance + # Returns true if there are at least one document that matches the query + # + # PlacesIndex.query(...).filter(...).exists? + # + def exists? + search_type(:count).total > 0 + end + end + end +end diff --git a/spec/chewy/query/existance_spec.rb b/spec/chewy/query/existance_spec.rb new file mode 100644 index 000000000..2c6649b81 --- /dev/null +++ b/spec/chewy/query/existance_spec.rb @@ -0,0 +1,31 @@ +require 'spec_helper' + +describe Chewy::Query::Existance do + before { Chewy.massacre } + + before do + stub_index(:products) do + define_type(:product) do + field :name + field :age, type: 'integer' + end + end + end + + let(:search) { ProductsIndex.all } + + specify { expect(search.exists?).to eq false } + + context do + let(:data) { 10.times.map { |i| {id: i.next.to_s, name: "Name#{i.next}", age: 10 * i.next}.stringify_keys! } } + + before { ProductsIndex::Product.import!(data.map { |h| double(h) }) } + + describe '#count' do + specify { expect(search.exists?).to eq true } + specify { expect(search.limit(5).exists?).to eq true } + specify { expect(search.filter(range: {age: {gt: 20}}).limit(3).exists?).to eq true } + specify { expect(search.filter(range: {age: {lt: 0}}).exists?).to eq false } + end + end +end