module OssActiveRecord module Searchable extend ActiveSupport::Concern module ClassMethods @@field_types= [:integer, :text, :string, :time] #supported field types @@index_instances = {} def searchable(options = {}, &block) yield unless options[:auto_index] == false after_save :index end end def index_instance idx_inst = @@index_instances[self.name.downcase] if idx_inst.nil? idx_inst = IndexInstance.new(self.name.downcase) @@index_instances[self.name.downcase] = idx_inst end idx_inst end def reindex! index_instance.oss_index.delete! index_instance.create_schema! self.all.find_in_batches do |group| group.each { |doc| doc.index(index_instance) } end end def method_missing(method, *args, &block) index_instance.add_field(args[0], method, block) if @@field_types.include? method end def search(*args, &block) searchRequest = SearchRequest.new(index_instance) searchRequest.returns index_instance.fields.map {|f|"#{f[:name]}|#{f[:type]}"} find_results(searchRequest.execute(&block), index_instance.field_id) end def find_results(search_result, field_id) id_field_name = "#{field_id[:name]}|#{field_id[:type]}" results = [] search_result['documents'].each do |document| document['fields'].each do |field| id = field['values'].map {|f|f.to_i}.uniq if field['fieldName'] == id_field_name results<