简体   繁体   中英

Avoid n+1 query when indexing on elasticsearch rails

I have a Genre model which have it's name translated in a genre_translations table (using the globalize gem)

I'm trying to indexing the model using the elasticsearch-rails gem

def as_indexed_json(options = {})
  as_json(
    only: %i(type available),
    methods: %i(name),
  )
end

but when I do Genre.import I get the following on my rails console:

[1] pry(main)> Genre.import
  Genre Load (27.1ms)  SELECT  "genres".* FROM "genres"  ORDER BY "genres"."id" ASC LIMIT 1000
  Genre::Translation Load (23.9ms)  SELECT "genre_translations".* FROM "genre_translations" WHERE "genre_translations"."genre_id" = $1  [["genre_id", 1]]
  Genre::Translation Load (0.3ms)  SELECT "genre_translations".* FROM "genre_translations" WHERE "genre_translations"."genre_id" = $1  [["genre_id", 2]]
  Genre::Translation Load (0.3ms)  SELECT "genre_translations".* FROM "genre_translations" WHERE "genre_translations"."genre_id" = $1  [["genre_id", 3]]
  ...

Any suggestion on how to index all the Genre items with a join to avoid the N+1 behaviour?

From the doc here

    # @example Pass an ActiveRecord query to limit the imported records
    #
    #    Article.import query: -> { where(author_id: author_id) }

So you could do:

 Genre.import query: -> { includes(:translations) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM