Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Redis / Memcached / MongoDB (or any NoSQL systems) support MySQL's ON DUPLICATE KEY UPDATE?

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?

like image 221
Continuation Avatar asked Jan 17 '23 18:01

Continuation


1 Answers

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 INCR command, where your key is based on the values you need to qualify it as unique. The first call to INCR just sets the value to 1 if it doesn't exist yet. For example:

INCR "uid:1234:url:/page/1234567890"
> 1
INCR "uid:1234:url:/page/1234567890"
> 2

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 INCR command 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.

like image 60
mpobrien Avatar answered Jan 30 '23 22:01

mpobrien