From 5fb33fd194e76fbf7ff06d0a52496b53acb50f89 Mon Sep 17 00:00:00 2001 From: Sergey Kintsel Date: Tue, 17 May 2016 21:30:36 +0700 Subject: [PATCH] Add Query#exists? method that bases on :count search_type --- lib/chewy/query.rb | 8 ++++++++ spec/chewy/query_spec.rb | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/lib/chewy/query.rb b/lib/chewy/query.rb index cc93d65a8..2d3aeb757 100644 --- a/lib/chewy/query.rb +++ b/lib/chewy/query.rb @@ -953,6 +953,14 @@ def find *ids ids.one? && !ids.first.is_a?(Array) ? results.first : results end + # 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 + # Returns request total time elapsed as reported by elasticsearch # # UsersIndex.query(...).filter(...).took diff --git a/spec/chewy/query_spec.rb b/spec/chewy/query_spec.rb index e97d36ac4..408eb4306 100644 --- a/spec/chewy/query_spec.rb +++ b/spec/chewy/query_spec.rb @@ -452,6 +452,17 @@ specify { expect { subject.find([10, 20]) }.to raise_error Chewy::DocumentNotFound } end + describe '#exists?' 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) }) } + + specify { expect(subject.exists?).to eq true } + specify { expect(subject.limit(5).exists?).to eq true } + specify { expect(subject.filter(range: {age: {gt: 20}}).limit(3).exists?).to eq true } + specify { expect(subject.filter(range: {age: {lt: 0}}).exists?).to eq false } + end + describe '#none' do specify { expect(subject.none).to be_a described_class } specify { expect(subject.none).not_to eq(subject) }