Question

I am working on my blog, a Sinatra application that uses Datamapper as its ORM. I just added a feature for hash-tags. A hash-tag is as such, its a many-to-many relationship with a 'Story'. My need is to get the most popular/used 5 hash-tags to display on the sidebar.

Here is an abstract of my modals that are of interest.

The hash-tag model

class Hashtag

  include DataMapper::Resource

  has n, :stories, through: Resource

  def self.default_repository_name
    :default
  end

  property        :id,                Serial
  property        :created_at,        DateTime
  property        :updated_at,        DateTime

  property        :hashtag,           String
end

The story model:

# File: models/story.rb


class Story

  include DataMapper::Resource

  def self.default_repository_name
    :default
  end

  belongs_to :person
  belongs_to :category

  has 1, :story_content

  has n, :comments
  has n, :hashtags, through: Resource


  property        :id,                Serial
  property        :created_at,        DateTime
  property        :updated_at,        DateTime

  property        :published,         Boolean,    default: false
  property        :privacy_level,     Enum[ :private, :friends, :public ] # SNS access control for Twitter/FB only

end

Need: The most efficient way to get the most used n hash-tags.

  • Tag 1 ~> 1 story
  • Tag 2 ~> 2 stories
  • Tag 3 ~> 3 stories

For n = 2, I need ~> [Tag 2, Tag 3]

I am thinking of maintaining a counter and did it for some thing like 'Likes'. Wonder if there is any other way than cache the count of Stories per HashTag.

Was it helpful?

Solution

Since the top tags are not very likely to change very frequently, you could alternatively compute and cache them for a longer period of time, for example a day. Then, you can recompute the top five from scratch in a nightly job.

Pros:

  • No extra stories_count column
  • No maintenance of the stories_count (not that easy to handle!)
  • Fast queryability

Cons:

  • Top 5 may be out of date (not an option if you expect frequent changes)
  • Need to build and configure a nightly job
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top