Search code examples
ruby-on-rails-4elasticsearchchewy-gem

Use chewy to connect a rails app to elasticsearch


I am using the chewy gem to tie ES to my rails app.I am new to chewy, so i am facing a problem when i try to index a field of my model. The field is a text field in the DB which i serialize as a Hash in my model. The hash is dynamic and might have 0 to n elements in it in the form. The field name is items Any help would be much appreciated.

{"0"=>{"property"=>"value","property"=>"value"},"1"=>{"property"=>"value","property"=>"value"}.......} 

how can I index such field in my index class when i do define_type?

This is my indexer

require 'typhoeus/adapters/faraday'
class ModelNameIndex < Chewy::Index
  define_type ModelName do
  field :user_id, type: 'integer'
  field :enduser_id, type: 'integer'
  field :items, type: 'object'
  field :created, type: 'date', include_in_all: false,
    value: ->{ created_at } 
  end
end

My model

class ModelName < ActiveRecord::Base
  update_index('IndexName#name') { self }
  belongs_to :user
  serialize :items, Hash
end

Solution

  • The code above works fine

    require 'typhoeus/adapters/faraday'
    class ModelNameIndex < Chewy::Index
      define_type ModelName do
      field :user_id, type: 'integer'
      field :enduser_id, type: 'integer'
      field :items, type: 'object'
      field :created, type: 'date', include_in_all: false,
             value: ->{ created_at } 
      end
    end
    

    If someone gets a parsing error make sure ElasticSearch does not has a any of they keys you are defining previously defined, or it will throw an error.