Skip to content

Instantly share code, notes, and snippets.

@terenceponce
Created September 5, 2012 07:30
Show Gist options
  • Save terenceponce/3632628 to your computer and use it in GitHub Desktop.
Save terenceponce/3632628 to your computer and use it in GitHub Desktop.
Implementing a decent trending algorithm in Rails

I'm trying to implement a trending feature. The trending feature is based on searches that have become viral in a span of 4 hours. It will get the 6 latest popular searches.

Of course, to pull that off, I created a model called Search that has a keyword field. Every search done on the application will be stored as one row in the Search table.

At the moment, this is what I'm doing to retrieve the keywords to be classified as trending:

@popular_search = Search.where('created_at >= ?', 4.hours.ago).group(:keyword).order('count_keyword DESC').limit(6).count(:keyword)

If I have these keywords now:

  • search8 (1 hour ago)
  • search7 (1 hour, 30 minutes ago)
  • search6 (2 hours ago)
  • search5 (2 hours, 30 minutes ago)
  • search4 (3 hours ago)
  • search3 (3 hours, 30 minutes ago)

cut off --------

  • search2 (4 hours, 30 minutes ago)
  • search1 (5 hours ago)

The list will be filled with the keywords, search8 to search3, which covers part of what I want to achieve.

This should be enough to go on, but if there's few or no searches done within the last 4 hours, the list of trending keywords will be less than 6 or maybe none at all.

  • search10 (30 minutes ago)
  • search9 (1 hour ago)

cut off ------------

  • search8 (6 hours ago)
  • search7 (6 hours, 30 minutes ago)
  • search6 (7 hours ago)
  • search5 (7 hours, 30 minutes ago)
  • search4 (8 hours ago)
  • search3 (8 hours, 30 minutes ago)
  • search2 (9 hours, 30 minutes ago)
  • search1 (10 hours ago)

What's the best way to add the previous trending keywords if the list isn't enough to fill 6?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment