简体   繁体   English

在elasticsearch rails上建立索引时避免使用n + 1查询

[英]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) 我有一个Genre模型,它的名字翻译在genre_translations表中(使用globalize gem)

I'm trying to indexing the model using the elasticsearch-rails gem 我正在尝试使用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: 但是当我做Genre.import时,我在rails控制台上得到以下内容:

[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? 有关如何使用连接索引所有Genre项目以避免N + 1行为的任何建议?

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) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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