I need to keep track of which user has visited which page how many times.
In MySQL I’d do something like this:
INSERT INTO stats (user_id, url, hits)
VALUES (1234, "/page/1234567890", 1)
ON DUPLICATE KEY UPDATE hits = hits + 1;
In the table stats (user_id, url) is UNIQUE
I’m looking to find the fastest system for this purpose. As this is just for stats keeping durability is not important.
Does Redis or MongoDB or Memcached or any other NoSQL systems support such a feature? How would you implement this to get the highest performance?
In MongoDB the equivalent concept is called an
upsert(detailed info here.)This basically means: “Go look for the document with this key- if it exists, apply this update. If it doesn’t exist, create it and apply this update.”
So for example, in your case you could do something like this in mongo:
db.stats.update({user_id:1234, url:"/page/1234567890"}, {$inc:{hits:1}}, true)The first time this gets called (on an empty db), it would insert this document:
{user_id:1234, url:"/page/1234567890", hits:1}Subsequent calls would simply increment the value of
hits.In Redis, you could accomplish this by just using the Redis
INCRcommand, where your key is based on the values you need to qualify it as unique. The first call toINCRjust sets the value to 1 if it doesn’t exist yet. For example:etc.
As for how to implement this for highest performance, this depends on what you mean by “performance” and what your use case is. For example, using Redis
INCRcommand is likely faster than MongoDB, but you sacrifice capabilities for indexing and querying, as well as flexibility in your data model. These are tradeoffs that you will need to decide based on your particular situation.