Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Query#exists? method that bases on :count search_type #386

Merged
merged 1 commit into from
May 18, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions lib/chewy/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/chewy/query_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand Down