module Elasticsearch::Persistence::Repository::Search

Returns a collection of domain objects by an Elasticsearch query

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.search(query: { match: { title: 'fox dog' } })
# => 1

@return [Integer]

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

  request = { index: index_name, body: query_or_definition.to_hash }
  response = cache_query(to_curl(request.merge(options), "_count"), klass) { client.count(request.merge(options)) }

  response
end

Private Instance Methods

to_curl(arguments = {}, end_point = "_search") click to toggle source

TODO: Not happy with where this is living right now.

# File lib/elasticsearch/persistence/repository/search.rb, line 92
def to_curl(arguments = {}, end_point = "_search")
  host = client.transport.options[:hosts]&.first || client.transport.options[:url]
  arguments[:index] = "_all" if !arguments[:index] && arguments[:type]

  valid_params = [
    :analyzer,
    :analyze_wildcard,
    :default_operator,
    :df,
    :explain,
    :fields,
    :from,
    :ignore_indices,
    :ignore_unavailable,
    :allow_no_indices,
    :expand_wildcards,
    :lenient,
    :lowercase_expanded_terms,
    :preference,
    :q,
    :routing,
    :scroll,
    :search_type,
    :size,
    :sort,
    :source,
    :_source,
    :_source_include,
    :_source_exclude,
    :stats,
    :suggest_field,
    :suggest_mode,
    :suggest_size,
    :suggest_text,
    :timeout,
    :version,
  ]

  method = "GET"
  path = Elasticsearch::API::Utils.__pathify(Elasticsearch::API::Utils.__listify(arguments[:index]), end_point)

  params = Elasticsearch::API::Utils.__validate_and_extract_params arguments, valid_params
  body = arguments[:body]

  params[:fields] = Elasticsearch::API::Utils.__listify(params[:fields]) if params[:fields]

  url = path

  unless host.is_a? String
    host_parts = "#{host[:protocol].to_s}://#{host[:host]}"
    host_parts = "#{host_parts}:#{host[:port]}" if host[:port]
  else
    host_parts = host
  end

  trace_url = "#{host_parts}/#{url}"
  trace_url += "?#{::Faraday::Utils::ParamsHash[params].to_query}" unless params.blank?
  trace_body = body ? " -d '#{body.to_json}'" : ""

  Rainbow("curl -X #{method.to_s.upcase} '#{CGI.unescape(trace_url)}'#{trace_body}\n").color :white
end