module Elasticsearch::Persistence::Repository::Search

Returns a collection of domain objects by an Elasticsearch query

Constants

COUNT

The key for accessing the count in a Elasticsearch query response.

Public Instance Methods

count(query_or_definition=nil, options={}) click to toggle source

Return the number of domain object in the index

@example Return the number of all domain objects

repository.count
# => 2

@example Return the count of domain object matching a simple query

repository.count('fox or dog')
# => 1

@example Return the count of domain object matching a query in the Elasticsearch DSL

repository.count(query: { match: { title: 'fox dog' } })
# => 1

@param [ Hash, String ] query_or_definition The query or search definition. @param [ Hash ] options The search options.

@return [Integer]

# File lib/elasticsearch/persistence/repository/search.rb, line 98
def count(query_or_definition=nil, options={})
  query_or_definition ||= { query: { match_all: {} } }
  request = { index: index_name }

  if query_or_definition.respond_to?(:to_hash)
    request[:body] = query_or_definition.to_hash
  elsif query_or_definition.is_a?(String)
    request[:q] = query_or_definition
  else
    raise ArgumentError, "[!] Pass the search definition as a Hash-like object or pass the query as a String" +
        " -- #{query_or_definition.class} given."
  end

  client.count(request.merge(options))[COUNT]
end