• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 9 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

fix n+1 aggregate sql functions for rails

EagerGroup

Build Status AwesomeCode Status for flyerhzm/eager_group

More explaination on our blog

Fix n+1 aggregate sql functions for rails, like

SELECT "posts".* FROM "posts";
SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = 1 AND "comments"."status" = 'approved'
SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = 2 AND "comments"."status" = 'approved'
SELECT COUNT(*) FROM "comments" WHERE "comments"."post_id" = 3 AND "comments"."status" = 'approved'

=>

SELECT "posts".* FROM "posts";
SELECT COUNT(*) AS count_all, post_id AS post_id FROM "comments" WHERE "comments"."post_id" IN (1, 2, 3) AND "comments"."status" = 'approved' GROUP BY post_id;

or

SELECT "posts".* FROM "posts";
SELECT AVG("comments"."rating") AS avg_id FROM "comments" WHERE "comments"."post_id" = 1;
SELECT AVG("comments"."rating") AS avg_id FROM "comments" WHERE "comments"."post_id" = 2;
SELECT AVG("comments"."rating") AS avg_id FROM "comments" WHERE "comments"."post_id" = 3;

=>

SELECT "posts".* FROM "posts";
SELECT AVG("comments"."rating") AS average_comments_rating, post_id AS post_id FROM "comments" WHERE "comments"."post_id" IN (1, 2, 3) GROUP BY post_id;

It supports Rails 4.x, Rails 5.x and Rails 6.x

Installation

Add this line to your application's Gemfile:

gem 'eager_group'

And then execute:

$ bundle

Or install it yourself as:

$ gem install eager_group

Usage

First you need to define what aggregate function you want to eager load.

class Post < ActiveRecord::Base
  has_many :comments

  define_eager_group :comments_average_rating, :comments, :average, :rating
  define_eager_group :approved_comments_count, :comments, :count, :*, -> { approved }
end

class Comment < ActiveRecord::Base
  belongs_to :post

  scope :approved, -> { where(status: 'approved') }
end

The parameters for define_eager_group are as follows

  • definition_name, it's used to be a reference in eager_group query method, it also generates a method with the same name to fetch the result.
  • association, association name you want to aggregate.
  • aggregate_function, aggregate sql function, can be one of average, count, maximum, minimum, sum, I define 2 additional aggregate function first_object and last_object to eager load first and last association objects.
  • column_name, aggregate column name, it can be :* for count
  • scope, scope is optional, it's used to filter data for aggregation.

Then you can use eager_group to fix n+1 aggregate sql functions when querying

posts = Post.all.eager_group(:comments_average_rating, :approved_comments_count)
posts.each do |post|
  post.comments_average_rating
  post.approved_comments_count
end

EagerGroup will execute GROUP BY sqls for you then set the value of attributes.

define_eager_group will define a method in model. You can call the definition_name directly for convenience, but it would not help you to fix n+1 aggregate sql issue.

post = Post.first
post.commets_average_rating
post.approved_comments_count

Advanced

eager_group through association

User.limit(10).includes(:posts).eager_group(posts: [:comments_average_rating, :approved_comments_count])

pass parameter to scope

class Post < ActiveRecord::Base
  has_many :comments

  define_eager_group :comments_average_rating_by_author, :comments, :average, :rating, ->(author, ignore) { by_author(author, ignore) }
end

posts = Post.all.eager_group([:comments_average_rating_by_author, author, true])
posts.each { |post| post.comments_average_rating_by_author }

first_object and last_object aggregation to eager load first and last association objects.

class Post < ActiveRecord::Base
  has_many :comments

  define_eager_group :first_comment, :comments, :first_object, :id
  define_eager_group :last_comment, :comments, :last_object, :id
end

posts = Post.all.eager_group(:first_comment, :last_comment)
posts.each do |post|
  post.first_comment
  post.last_comment
end

Benchmark

I wrote a benchmark script here, it queries approved comments count and comments average rating for 20 posts, with eager group, it gets 10 times faster, WOW!

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/flyerhzm/eager_group.

More Repositories

1

bullet

help to kill N+1 queries and unused eager loading
Ruby
7,081
star
2

rails_best_practices

a code metric tool for rails projects
Ruby
4,163
star
3

switch_user

Easily switch current user
Ruby
732
star
4

chinese_pinyin

translate chinese hanzi to pinyin
Ruby
430
star
5

activemerchant_patch_for_china

A rails plugin to add an active_merchant patch for china online payment platform including alipay (ๆ”ฏไป˜ๅฎ), 99bill (ๅฟซ้’ฑ) and tenpay (่ดขไป˜้€š)
Ruby
305
star
6

css_sprite

automatically css sprite
Ruby
242
star
7

uniform_notifier

uniform notifier for rails logger, customized logger, javascript alert, javascript console, growl and xmpp
Ruby
235
star
8

rails-bestpractices.com

HTML
200
star
9

redis-sentinel

another redis automatic master/slave failover solution for ruby by using built-in redis sentinel (deprecated)
Ruby
188
star
10

seo_checker

check your website if it is seo.
Ruby
117
star
11

simple_cacheable

a simple cache implementation for rails
Ruby
91
star
12

code_analyzer

code analyzer tool which is extracted from rails_best_practices
Ruby
86
star
13

resque-restriction

resque-restriction is an extension to resque queue system that restricts the execution number of certain jobs in a period time.
Ruby
86
star
14

rfetion

rfetion is a ruby gem for China Mobile fetion service that you can send SMS free.
Ruby
61
star
15

chinese_regions

provides all chinese regions, cities and districts
Ruby
60
star
16

mongoid-eager-loading

eager loading for mongoid (DEPRECATED)
Ruby
54
star
17

rails-brakeman.com

online security check for rails projects
Ruby
52
star
18

contactlist

java api to retrieve contact list of email(hotmail, gmail, yahoo, sohu, sina, 163, 126, tom, yeah, 189 and 139) and im(msn)
Java
49
star
19

regexp_crawler

A crawler which uses regular expression to catch data from website.
Ruby
45
star
20

chinese_permalink

This plugin adds a capability for AR model to create a seo permalink with your chinese text. It will translate your chinese text to english url based on google translate.
Ruby
41
star
21

apis-bench

Ruby
34
star
22

sitemap

This plugin will generate a sitemap.xml from sitemap.rb whose format is very similar to routes.rb
Ruby
32
star
23

twitter_connect

facebook connect style twitter oauth
Ruby
30
star
24

taobao

Ruby Client Library for Taobao Open Platform
Ruby
27
star
25

huangzhimin.com

my homepage
HTML
24
star
26

railsbp.com

railsbp.com
JavaScript
23
star
27

multiple_mailers

extend actionmailer to allow one smtp account per mailer class.
Ruby
23
star
28

contactlist-client

The contactlist-client gem is a ruby client to contactlist service which retrieves contact list of email(hotmail, gmail, yahoo, sohu, sina, 163, 126, tom, yeah, 189 and 139) and im(msn)
Ruby
20
star
29

donatecn

demo for activemerchant_patch_for_china
Ruby
17
star
30

monitor

Monitor gem can display ruby methods call stack on browser based on unroller
JavaScript
17
star
31

authlogic_renren_connect

Extension of the Authlogic library to add Renren Connect support built upon the renren plugin
Ruby
5
star
32

rails3-template

rails3 template includes a lot of useful plugins/gems
Ruby
5
star
33

nodeslide

node.js related slideshows [deprecated], move to nodeslide.heroku.com
JavaScript
4
star
34

rubyslide.com

collect ruby rails related presentations [deprecated], moved to rubyslide.heroku.com
Ruby
4
star
35

visual_partial

This plugin provides a way that you can see all the partial pages rendered. So it can prevent you from using partial page too much, which hurts the performance.
Ruby
4
star
36

codelinestatistics

The code line statistics takes files and directories from GUI, counts the total files, total sizes of files, total lines, lines of codes, lines of comments and lines of blanks in the files, displays the results and can also export results to html file.
Ruby
4
star
37

clock_chrome_extension

google chrome extension to display multiple clock analogs for multiple timezones
2
star
38

dotfiles

Vim Script
2
star
39

showoff-understanding-mongoid

My understanding mongoid showoff presentation
Ruby
2
star
40

enough_fields

only select specified fields used
Ruby
2
star
41

skype_archive

company hackathon
Ruby
1
star
42

bullet_test

Ruby
1
star
43

play_skype

JavaScript
1
star
44

test_code_analyzer

test code for code_analyzer gem
Ruby
1
star
45

blog.huangzhimin.com

HTML
1
star
46

test_error

raise an error to test if exception_notification really works.
Ruby
1
star
47

try-ripper

code mirror of try-ripper.heroku.com
CSS
1
star