knagode
knagode

Reputation: 6135

Elastic search + translated content in Rails 4

I would like to setup ElasticSearch on a table "content" which also have translation table "content_translation" for localization purpose (Globalize gem). We have 10 languages.

I want to implement Elasticsearch for my data model. In SQL I would search like:

SELECT id, content_translation.content 
FROM content 
LEFT JOIN content_translation on content.id = content_translation.content_id
WHERE content_translation.content LIKE '%???????%'

I wonder what is the best strategy to do "left join" like search with ElasticSearch?

Should I create just "content" index with all translation data in it?

{"id":21, "translations":{"en":{"content":"Lorem..."}, "de":{"content":"Lorem..."} ..}

Should I create "content_translation" index and just filter results for specific locale?

{"content_id":21, "locale":"en", "content": "Lorem ..."}

Are there some good practices how to do it?

Should I take care of maintaining index by myself or should I use something like "Tire gem" which takes care about indexing by itself.

Upvotes: 1

Views: 978

Answers (1)

Srikanth Venugopalan
Srikanth Venugopalan

Reputation: 9049

I would recommend the second alternative (one document per language), assuming that you wouldn't need to show content from multiple languages.

i.e.

{"content_id":21, "locale":"en", "content": "Lorem ..."}

I recommend a gem like Tire, and exploit it's DSL to your advantage.

You could have your content model to look like:

class Content < ActiveRecord:Base

    include Tire::Model::Search
    include Tire::Model::Callbacks

    ...

end

Then you could do have a search method that would do something like

Content.search do
    query do
        ...
    end
    filter :terms, :locale => I18n.locale.to_s
end

Your application would need to maintain locale at all times, to serve the respective localized content. You could just use I18n's locale and look up data. Just pass this in as a filter and you could have the separation you wish. Bonus is, you get fallback for free if you have enabled it in i18n for rails.

However, if you have a use case where you need to show multi-lingual content side by side, then this fails and you could look at a single document holding all language content.

Upvotes: 3

Related Questions