Which is faster "count" or "length"? - ruby-on-rails

Assuming there are 2 models called User and Post
Which will be better performance(fast) either "Plan A" or "Plan B"?
"Plan A"
controller
#users = User.find_all_by_country(params[:country])
#posts = Post.find_all_by_category(params[:category])
view
<%= #users.count.to_s %>
<%= #posts.count.to_s %>
"Plan B"
controller
#users = User.find_all_by_country(params[:country])
#posts = Post.find_all_by_category(params[:category])
view
<%= #users.length.to_s %>
<%= #posts.length.to_s %>

In ruby, count, length and size all do pretty much the same thing regarding arrays. See here for more info.
When using ActiveRecord objects, however, count is better than length, and size is even better.
find_all_by_country returns a dumb array so you shouldn't use that method (because it always returns an array). Instead, use where(country: params[:country]).
I'll let Code School's Rails Best Practices slide nº 93 speak for itself (and hope they don't get mad at me for reproducing it here).
Just in case the image gets taken down, basically:
length always pulls all the records and then calls .length on the array - bad
count always does a count query - good
size looks at the cache if you have a cache counter, otherwise does a count query - best

Both will be the same, count with no arguments and length are identical as you are invoking them on a Ruby array (returned by the magic find_* method), and not an ActiveRecord object.
That said, both methods are the worst way to do this, if you're simply interested in the number of matching records.
Instead of instantiating the entire result set just to find its length, use .count on an actual ActiveRecord relation:
#num_users = User.where(country: params[:country]).count
#num_posts = Post.where(category: params[:category]).count
This will actually execute as select count(*) from instead of a full select * from, which will be much faster depending on the number of results.

Related

I need advice in speeding up this rails method that involves many queries

I'm trying to display a table that counts webhooks and arranges the various counts into cells by date_sent, sending_ip, and esp (email service provider). Within each cell, the controller needs to count the webhooks that are labelled with the "opened" event, and the "sent" event. Our database currently includes several million webhooks, and adds at least 100k per day. Already this process takes so long that running this index method is practically useless.
I was hoping that Rails could break down the enormous model into smaller lists using a line like this:
#today_hooks = #m_webhooks.where(:date_sent => this_date)
I thought that the queries after this line would only look at the partial list, instead of the full model. Unfortunately, running this index method generates hundreds of SQL statements, and they all look like this:
SELECT COUNT(*) FROM "m_webhooks" WHERE "m_webhooks"."date_sent" = $1 AND "m_webhooks"."sending_ip" = $2 AND (m_webhooks.esp LIKE 'hotmail') AND (m_webhooks.event LIKE 'sent')
This appears that the "date_sent" attribute is included in all of the queries, which implies that the SQL is searching through all 1M records with every single query.
I've read over a dozen articles about increasing performance in Rails queries, but none of the tips that I've found there have reduced the time it takes to complete this method. Thank you in advance for any insight.
m_webhooks.controller.rb
def index
def set_sub_count_hash(thip) {
gmail_hooks: {opened: a = thip.gmail.send(#event).size, total_sent: b = thip.gmail.sent.size, perc_opened: find_perc(a, b)},
hotmail_hooks: {opened: a = thip.hotmail.send(#event).size, total_sent: b = thip.hotmail.sent.size, perc_opened: find_perc(a, b)},
yahoo_hooks: {opened: a = thip.yahoo.send(#event).size, total_sent: b = thip.yahoo.sent.size, perc_opened: find_perc(a, b)},
other_hooks: {opened: a = thip.other.send(#event).size, total_sent: b = thip.other.sent.size, perc_opened: find_perc(a, b)},
}
end
#m_webhooks = MWebhook.select("date_sent", "sending_ip", "esp", "event", "email").all
#event = params[:event] || "unique_opened"
#m_list_of_ips = [#List of three ip addresses]
end_date = Date.today
start_date = Date.today - 10.days
date_range = (end_date - start_date).to_i
#count_array = []
date_range.times do |n|
this_date = end_date - n.days
#today_hooks = #m_webhooks.where(:date_sent => this_date)
#count_array[n] = {:this_date => this_date}
#m_list_of_ips.each_with_index do |ip, index|
thip = #today_hooks.where(:sending_ip => ip) #Stands for "Today Hooks ip"
#count_array[n][index] = set_sub_count_hash(thip)
end
end
Well, your problem is very simple, actually. You gotta remember that when you use where(condition), the query is not straight executed in the DB.
Rails is smart enough to detect when you need a concrete result (a list, an object, or a count or #size like in your case) and chain your queries while you don't need one. In your code, you keep chaining conditions to the main query inside a loop (date_range). And it gets worse, you start another loop inside this one adding conditions to each query created in the first loop.
Then you pass the query (not concrete yet, it was not yet executed and does not have results!) to the method set_sub_count_hash which goes on to call the same query many times.
Therefore you have something like:
10(date_range) * 3(ip list) * 8 # (times the query is materialized in the #set_sub_count method)
and then you have a problem.
What you want to do is to do the whole query at once and group it by date, ip and email. You should have a hash structure after that, which you would pass to the #set_sub_count method and do some ruby gymnastics to get the counts you're looking for.
I imagine the query something like:
main_query = #m_webhooks.where('date_sent > ?', 10.days.ago.to_date)
.where(sending_ip:#m_list_of_ips)
Ok, now you have one query, which is nice, but I think you should separate the query in 4 (gmail, hotmail, yahoo and other), which gives you 4 queries (the first one, the main_query, will not be executed until you call for materialized results, don forget it). Still, like 100 times faster.
I think this is the result that should be grouped, mapped and passed to #set_sub_count instead of passing the raw query and calling methods on it every time and many times. It will be a little work to do the grouping, mapping and counting for sure, but hey, it's faster. =)
In case this helps anybody else, I learned how to fill a hash with counts in a much simpler way. More importantly, this approach runs a single query (as opposed to the 240 queries that I was running before).
#count_array[esp_index][j] = MWebhook.where('date_sent > ?', start_date.to_date)
.group('date_sent', 'sending_ip', 'event', 'esp').count

rails each loop with from to

In my controller i fetch 9 row's for object organizations.
#organizations = Organization.where(parent_id: 1).order(city_id: :asc, is_vip: :desc, title: :asc).limit(25).sample(9)
and then in view i must separate this 9 value's to 3 view loops, like first .each do if for row's 1-3, second for 4-6, third 6-9
and i try so:
- #organizations[0..2].each do |org|
...
- #organizations[3..5].each do |org|
...
- #organizations[6..8].each do |org|
...
but it seems that i do something wrong, but what exactly? and how to do it right?
Not sure why your data is duplicated. But you can use the following method for splitting the array into slices
you can use each_slice
#organization.each_slice(3) do |sliced_orgs|
end
Some documentation here
First I don't really get why you use .limit(25).sample(9), you could limit your results to 9 already. But maybe you have some use of the random factor introduced by sample? Strange.
Other than that,
#organizations[0..2].each do |org|
puts org
end
...
should work perfectly fine. If the data is repeated it is because you have multiple times the same entry in your model. sample(9) is taking random unique entries and #organizations[0..2] is a fixed range returning an array or nil. (Rubydoc : ary[range] → new_ary or nil)
In short, nothing wrong with the code but probably somewhere in your data/logic.

Block or method to calculate float elements in column of data in Rails app

I am trying to show a sum of the floats of all records entered, and I can't seem to figure out how to do it. Here's the situation. My app (purely for learning purposes) has a user who can register a swimmer profile and upon doing so, can record swims for the swimmer. Swim belongs to Swimmer and Swimmer has many swims.
// swims_controller.rb
// SwimsController#index
#swims = #swimmer.swims.all
#distances = #swimmer.swims.all(:select => "distance")
In the view for this action, I iterate through swims to get swim.date and swim.distance. Then I add this line which doesn't work
<p>Total distance: <%= #distances.each { | x | x.distance.inject(:+).to_f } %></p>
The error I am getting is "undefined method `inject' for 5500.0:Float" (5500.0 is the distance of the first swim recorded for this swimmer). I used inject based on other threads (e.g., How to sum array of numbers in Ruby?) but clearly, I'm missing something. Actually, I'm probably missing quite a lot because I'd like to put this a #total_distance method in the Swim model (swim.rb) but when I try to do that, I can't get the controller to recognize the method and I read elsewhere that a view should not try to access a method defined in a model due to "caching" issues.
Anyone's useful guidance on this would greatly help. Seems like a pretty basic thing to want to do but for some reason, I find scant guidance on a question like this after numerous search queries. Thanks!
I am not that experience but try to do <%= #swims.inject(0) {|num,n| num + n[:distance] } %>
OR
<%= #distances.inject {|sum, n| sum + n } %>
I hope this would work.
Thanks.
You should take a look at active record calculation. It already supports sum:
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

Rails 3.2 Query - .exists?

I have about 500 outlets. Each outlet will be monitored a minimum of one time per day. I am trying to get a list of outlets that have been monitored each day.
I am having a problem with the query at the moment, any help is appreciated:
<% for outlet in #outlets %>
<% if Monitoring.exists?( :outlet_id => outlet.id, 'DATE(created_at) = ?', Date.today ) %>
The #outlets is an instance variable containing Outlet.all.
This query leaves me with a syntax error. What would be the correct way to do this? I'm trying to check that the Monitoring belongs to the Outlet, and that the Monitoring record was created today.
Also, I'm not entirely sure of the speed implications of this query. There will be a max of 2000 outlets on a page at one time (it's a dashboard, so they appear as either red or green dots).
Any help greatly appreciated.
You're getting a syntax error because you're trying to mix implicit-Hash and implicit-Array arguments:
Monitoring.exists?(:outlet_id => outlet.id, 'DATE(created_at) = ?', Date.today)
The exists? methods wants a Hash as its single argument. You want to use an SQL function in the query though, that means that you have to use the Model.where(...).exists? form:
Monitoring.where(:outlet_id => outlet.id).where('date(created_at) = ?', Date.today).exists?
That still leaves you hitting the database over and over again to light up your lights. You could precompute the whole mess with something like this:
counts = Monitoring.where('date(created_at) = ?', Date.today).count(:group => :outlet_id)
And then look use counts.has_key? outlet.id in your loop. Adding a where(:outlet_id => outlet_ids) (where outlet_ids are the IDs you're interested in) might make sense as well. You might be able to combine the count query with the query that is generating the #outlets too.

Getting the last document of limited Mongoid query result and .count()

I'm using Mongoid to work with MongoDB. Everything is fine, I like it very much and so on. In my blog application (posts controller, index action) I have this code:
#posts = Post.without(:comments)
#posts = #posts.my_search(params[:s]) if params[:s]
#posts = #posts.order_by([:created_at, :desc])
#posts = #posts.where(:pid.lt => params[:p].to_i+1) if params[:p]
#posts = #posts.limit(items_per_page+1)
The part with "where" is implementation of my own pagination method (allows to page results in one direction only, but without skip(), what I consider a plus). Now, there are few small problems that make me feel uncomfortable:
For my pagination to work I need to get the last post within that limit. But when I do #posts.last I'm getting last document of the whole query without limit. Ok, this is strange, but not a big problem. Other than that, query results act like almost-ordinary-array, so at this moment I'm getting the last element with #posts.pop (funny, but it doesn't remove any documents) or #posts.fetch(-1)
I have a feeling that this isn't "right way" and there mush be something more elegant. Also
#posts.count generates second query exactly the same as first one (without limit) but with "count" only and I don't like it.
If I make the last line look like
#posts = #posts.limit(items_per_page+1).to_ary
to convert query results into array, everything generates only one query (good), but now #posts.count stops reporting what I need (total amount of documents without limit applied) and behaves exactly like #posts.size - it returns items_per_page+1 or less (bad).
So, here are my questions:
1) What is a "correct" way to get the last document of query results within given limit?
2) How to get total amount of documents with given conditions applied without generating additional query?
UPD:
3) #posts.first generates additional query, how to prevent it and just get first document before I iterate all documents?
Getting the last document:
Post.last
Getting last document with some other queries:
Post.order_by([:created_at, :desc]).last
Getting total number documents:
Post.order_by([:created_at, :desc]).count
Recommendation: Just use the built in pagination
#posts = Post.limit(10).paginate(:page=>pararms[:page])
later:
<%= will_paginate #posts %>
Regarding the additional queries -- mongoid lazy loads everything:
#posts = Post.all #no query has been run yet
#posts.first #Ok, a query has finally been run because you are accessing the objects

Resources