From 9d44d2018acb2a9c7fd3a0eda26f9ba6cff498d6 Mon Sep 17 00:00:00 2001 From: Ryan Schlesinger Date: Wed, 7 Mar 2018 16:41:14 -0800 Subject: [PATCH] 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 2c395bd84..7b188e9cd 100644 --- a/elasticsearch-model/lib/elasticsearch/model.rb +++ b/elasticsearch-model/lib/elasticsearch/model.rb @@ -205,6 +205,30 @@ def inheritance_enabled def inheritance_enabled=(inheritance_enabled) @inheritance_enabled = inheritance_enabled 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