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

I need to keep track of which user visited which page how many times.

In MySQL, I would do something like this:

INSERT INTO stats (user_id, url, hits) VALUES (1234, "/page/1234567890", 1) ON DUPLICATE KEY UPDATE hits = hits + 1; 

There is a UNIQUE in the stats table (user_id, url)

I am looking for the fastest system for this purpose. Since this is just for statistics, maintaining durability does not matter.

Does Redis or MongoDB or Memcached or any other NoSQL systems support this feature? How would you implement this to get maximum performance?

+4
source share
1 answer

In MongoDB, the equivalent concept is called upsert (more info here .)

This basically means: "Look for a document with this key, if it exists, apply this update. If it does not exist, create it and apply this update."

So, for example, in your case, you can do something like this in mongo:

db.stats.update({user_id:1234, url:"/page/1234567890"}, {$inc:{hits:1}}, true)

At the first call of the call (on empty db), it inserts this document:

{user_id:1234, url:"/page/1234567890", hits:1}

Subsequent calls simply increase the value of hits .

In Redis, you can accomplish this simply by using the Redis INCR command, where your key is based on values ​​that you need to qualify as unique. The first INCR call simply sets the value to 1 if it does not already exist. For instance:

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

and etc.

As for how to implement this for maximum performance, it depends on what you mean by “performance” and what is your use case. For example, using the Redis INCR command is likely faster than MongoDB, but you sacrifice indexing and query capabilities, as well as flexibility in your data model. These are trade-offs that you will need to resolve based on your specific situation.

+9
source

Source: https://habr.com/ru/post/1391585/


All Articles