Sha256: f736d91914b73a77aac1fa3500e077d149099af63a22bed0d50ea2974e1f9940

Contents?: true

Size: 1.3 KB

Versions: 1

Compression:

Stored size: 1.3 KB

Contents

module Elasticity
  class MultiSearch
    def initialize
      @searches = []
      yield self if block_given?
    end

    def add(name, search, documents: nil, active_records: nil)
      mapper = case
      when documents && active_records
        raise ArgumentError, "you can only pass either :documents or :active_records as an option"
      when documents
        Search::DocumentMapper.new(documents)
      when active_records
        Search::ActiveRecordMapper.new(active_records)
      else
        raise ArgumentError, "you need to provide either :documents or :active_records as an option"
      end

      @searches << [name, search, mapper]
    end

    def [](name)
      @results ||= fetch
      @results[name]
    end

    private

    def fetch
      multi_body = @searches.map do |name, search, _|
        { index: search.index.name, type: search.document_type, search: search.body }
      end

      response = ActiveSupport::Notifications.instrument("multi_search.elasticity", args: { body: multi_body }) do
        Elasticity.config.client.msearch(body: multi_body)
      end

      results = {}
      Array(response["responses"]).each_with_index do |resp, idx|
        name, search, mapper = @searches[idx]
        results[name] = Search::Result.new(resp, mapper)
      end

      results
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
es-elasticity-0.2.8 lib/elasticity/multi_search.rb