Method: Elasticsearch::Persistence::Repository::Search#count

Defined in:
lib/elasticsearch/persistence/repository/search.rb

#count(query_or_definition = nil, options = {}) ⇒ Integer

Return the number of domain object in the index

Examples:

Return the number of all domain objects


repository.count
# => 2

Return the count of domain object matching a simple query


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

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


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

Parameters:

  • query_or_definition (Hash, String) (defaults to: nil)

    The query or search definition.

  • options (Hash) (defaults to: {})

    The search options.

Returns:

  • (Integer)

Since:

  • 6.0.0

[View source]

98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# 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