Skip to content

Commit

Permalink
Add Query#exists? method that bases on :count search_type
Browse files Browse the repository at this point in the history
  • Loading branch information
Sergey Kintsel committed May 17, 2016
1 parent 01baeb4 commit f62c584
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/chewy/query.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions lib/chewy/query/existance.rb
Original file line number Diff line number Diff line change
@@ -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
31 changes: 31 additions & 0 deletions spec/chewy/query/existance_spec.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit f62c584

Please sign in to comment.