From f5a4fd3916c72e765d655ab7c6ad4a9018f2e6b0 Mon Sep 17 00:00:00 2001 From: Aaron Rustad Date: Mon, 15 Jun 2015 17:17:00 -0600 Subject: [PATCH] Add the ability to define how models are mapped to hits. --- .../lib/elasticsearch/model.rb | 24 +++++++++++++++++++ .../elasticsearch/model/adapters/multiple.rb | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/elasticsearch-model/lib/elasticsearch/model.rb b/elasticsearch-model/lib/elasticsearch/model.rb index ce05d215d..8ad314c76 100644 --- a/elasticsearch-model/lib/elasticsearch/model.rb +++ b/elasticsearch-model/lib/elasticsearch/model.rb @@ -179,6 +179,30 @@ def search(query_or_payload, models=[], options={}) request = Searching::SearchRequest.new(models, query_or_payload, options) Response::Response.new(models, request) end + + # Define a rule for mapping hits to models when searching across multiple models + # + # @param model_to_hit_selector [lambda(model,hit)] - Must return a boolean + # + # @example Map indices to models that operate against aliases + # + # Elasticsearch::model_to_hit_selector = lambda do |model, hit| + # /#{model.index_name}-.*/ =~ hit[:_index] && model.document_type == hit[:_type] + # end + # + # @example Map indices to models but disregard the model's index name + # + # Elasticsearch::model_to_hit_selector = lambda do |model, hit| + # model.document_type == hit[:_type] + # end + # + def model_to_hit_selector=(model_to_hit_selector) + @model_to_hit_selector = model_to_hit_selector + end + + def model_to_hit_selector + @model_to_hit_selector ||= lambda { |model, hit| model.index_name == hit[:_index] && model.document_type == hit[:_type] } + end end extend ClassMethods diff --git a/elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb b/elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb index 9a0bc4e8e..c82a23e17 100644 --- a/elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb +++ b/elasticsearch-model/lib/elasticsearch/model/adapters/multiple.rb @@ -93,7 +93,7 @@ def __type_for_hit(hit) @@__types[ "#{hit[:_index]}::#{hit[:_type]}" ] ||= begin Registry.all.detect do |model| - model.index_name == hit[:_index] && model.document_type == hit[:_type] + Model.model_to_hit_selector.call(model, hit) end end end