class Chewy::MultiSearch

‘Chewy::MultiSearch` provides an interface for executing multiple queries via the Elasticsearch Multi Search API. When a MultiSearch is performed it wraps the responses from Elasticsearch and assigns them to the appropriate queries.

Attributes

client[R]
queries[R]

Public Class Methods

new(queries, client: Chewy.client) click to toggle source

Instantiate a new MultiSearch instance.

@param queries [Array<Chewy::Search::Request>] @option [Elasticsearch::Transport::Client] :client (Chewy.client)

The Elasticsearch client that should be used for issuing requests.
# File lib/chewy/multi_search.rb, line 16
def initialize(queries, client: Chewy.client)
  @client = client
  @queries = Array(queries)
end

Public Instance Methods

add_query(query) click to toggle source

Adds a query to be performed by the MultiSearch

@param query [Chewy::Search::Request]

# File lib/chewy/multi_search.rb, line 24
def add_query(query)
  @queries << query
end
perform() click to toggle source

Performs any unperformed queries.

# File lib/chewy/multi_search.rb, line 37
def perform
  unperformed_queries = queries.reject(&:performed?)
  return if unperformed_queries.empty?

  responses = msearch(unperformed_queries)['responses']
  unperformed_queries.zip(responses).map { |query, response| query.response = response }
end
responses() click to toggle source

Performs any unperformed queries and returns the responses for all queries.

@return [Array<Chewy::Search::Response>]

# File lib/chewy/multi_search.rb, line 31
def responses
  perform
  queries.map(&:response)
end

Private Instance Methods

msearch(queries_to_search) click to toggle source
# File lib/chewy/multi_search.rb, line 49
def msearch(queries_to_search)
  body = queries_to_search.flat_map do |query|
    rendered = query.render
    [rendered.except(:body), rendered[:body]]
  end

  client.msearch(body: body)
end