简体   繁体   中英

Wilson Score in Rails + Add Random Number to Upvote in Postgres Select Statement

I am trying to add a randomized number to my Wilson Score select statement.

My Post model has columns 'upvotes_count' and 'downvotes_count' that get incremented and decremented according to how many upvotes and downvotes they have (duh..).

Post.select("((upvotes_count + 1 + 1.9208) / (upvotes_count + downvotes_count + 2) - " +
            "1.96 * SQRT(((upvotes_count + 1) * (downvotes_count + 1)) / (upvotes_count + downvotes_count + 2) + 0.9604) / " +
            "(upvotes_count + downvotes_count + 2)) / (1 + 3.8416 / (upvotes_count + downvotes_count + 2)) " +
            "AS ci_lower_bound, posts.*")
    .order("ci_lower_bound DESC")

Note: In theory, Wilson Score doesn't allow for cases where both upvotes_count and downvotes_count equal 0, so I cheat and add upvote and downvote to each post record. I know this is mathematical "blasphemy" so please don't hurt me math gods. Otherwise, I wouldn't get post records with zero upvotes and zero downvotes...and that sucks.

What would be ideal is to have a select statement that would add a different random number (Poisson preferably) to upvotes_count of each post to give an artificial bump to it's Wilson score so it would occasionally appear higher on the list.

Question: How do I add a different random number to upvotes_count for each post selected in my select statement?

Something like this...but obviously it doesn't work...

Post.select("((upvotes_count + 1 + random + 1.9208) / (upvotes_count + downvotes_count + 2) - " +
            "1.96 * SQRT(((upvotes_count + 1 + random) * (downvotes_count + 1)) / (upvotes_count + downvotes_count + 2) + 0.9604) / " +
            "(upvotes_count + random + downvotes_count + 2)) / (1 + 3.8416 / (upvotes_count + random + downvotes_count + 2)) " +
            "AS ci_lower_bound, posts.*")

This answer may be blasphemy too and I'm not sure I would ever do this, but here's how you could probably do what you're asking

# app/models/post.rb
class Post < ActiveRecord::Base
  def self.custom_select_query
    select("((upvotes_count + 1 + #{random(100)} + 1.9208) / (upvotes_count + downvotes_count + 2) - " +
      "1.96 * SQRT(((upvotes_count + 1 + #{random(99)}) * (downvotes_count + 1)) / (upvotes_count + downvotes_count + 2) + 0.9604) / " +
      "(upvotes_count + #{random(98)} + downvotes_count + 2)) / (1 + 3.8416 / (upvotes_count + #{random(97)} + downvotes_count + 2)) " +
      "AS ci_lower_bound, posts.*")
  end

  private

  def self.random(max)
    SecureRandom.random_number(max)
  end
end

Then call it Post.custom_select_query

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.

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