LoginSignup
10
4

More than 5 years have passed since last update.

GraphQLでN+1を考える

Last updated at Posted at 2016-12-09

RailsでGraphQLをつかうためには次のgemを使うことになると思う。
https://github.com/rmosolgo/graphql-ruby

GraphQLを利用すると、容易にN+1が発生する。
そこで次のようなコードを考えた。

module ShopsResolver
  def self.call(obj, args, ctx)
    limit    = args[:limit]
    order    = args[:order]
    bookable = args[:bookable]

    shops = Shop.visible
    shops = shops.limit(limit)              if limit.present?
    shops = shops.order('RAND()')           if order == "TRENDING" # 仮実装
    shops = shops.order('RAND()')           if order == "RANKING"  # 仮実装
    shops = shops.where(bookable: bookable) if bookable.present?

    shops = shops.includes(:area)
    shops = shops.includes(:categories)
    shops = shops.includes(:shop_categories)
    shops = shops.includes(:category_subs)
    shops = shops.includes(:shop_category_subs)
    shops = shops.includes(:situations)

    shops
  end
end

むやみにincludesをつけまくると、余計なSQL発行が発生して良くない。
そこで、対策を検索した。

とりあえずincludesを全部消して https://github.com/salsify/goldiloader を入れて対応した。
goldiloaderを使ってみたところ、GraphQLではうまく動いたが、一部システムが動かなくなった。

影響範囲が大きかったため https://github.com/Shopify/graphql-batch を試すことにした(続く)

10
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
4