ruby-on-railsruby-on-rails-3elasticsearchelasticsearch-railselasticsearch-model

How to import parent/child objects in Elasticsearch


I'm using the gems elasticsearch-rails and elasticsearch-model in my Rails app. I'm using this integration test as a template for setting up my mappings and such before importing existing data, which has the same basic association between the parent and child models.

I know the integration test works because of the callbacks and that it sets the parent id in those callbacks.

I would like to import existing Questions and Answers. It doesn't seem like it's enough to just call Questions.import and Answers.import. I get the questions, but I don't get any answers in my Elasticsearch store. I'd like to know how to import the Answers objects with the appropriate parent mapping. Can anyone give me any hints?


Solution

  • I'm going to answer my own question in case someone else is wondering the same thing.

    You can pass something to transform the data as you import it:

    transform = lambda do |a|
      {index: {_id: a.id, _parent: a.author_id, data: a.__elasticsearch__.as_indexed_json}}
    end
    
    Article.import transform: transform
    

    The elasticsearch-model gem has more documentation here: https://github.com/elastic/elasticsearch-rails/blob/ded20356920802c35d258756113acfd95b25ade6/elasticsearch-model/lib/elasticsearch/model/importing.rb