I need to rank posts in a Rails application using Mongoid and I am looking for input on how to go about doing it efficiently and accurately.
Right now, the way I made it up is highly inefficient.
Right now I am sorting models based on methods like this:
def hotness
return (self.confidence*(self.popularity+0.3))/Math.sqrt((Time.now - Time.at(self.created_at)))
end
So then I am sorting an array based on hotness and printing that to the page. This is the wrong way to go about it and performance is just not happening right now.
I am not really sure what a better way to go about it would be though.
There are other functions that do not require time called and I could imagine different ways to do those, but would still like input. Optimization is important to me.
Thanks a lot in advance. I can clarify anything if needed.
Following on from your comment above - if this is the sort of result that can be cached in a field an updated periodically, or whenever the model is saved - then that is the best way to go (in terms of query performance in MongoDB).
So you'd end up with something along these lines:
class Post
include Mongoid::Document
field :hotness, :type => Float, :default => 0
field :confidence, :type => Float, :default => 0
field :popularity, :type => Float, :default => 0
before_save :refresh_hotness
scope :hottest, desc(:hotness)
protected
def refresh_hotness
self.hotness = (self.confidence*(self.popularity+0.3))/Math.sqrt((Time.now - Time.at(self.created_at)))
end
end
Then you can just grab the ordered, 'hottest' posts with Post.hottest
.
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.