Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis, partial match keys with end of line

This is a 2 part question.

I have a redis db storing items with the following keys:

record type 1: "site_id:1_item_id:3"

record type 2: "site_id:1_item_id:3_user_id:6"

I've been using KEYS site_id:1_item_id:* to grab record type 1 items (in this case for site 1)

Unfortunately, it returns all type 1 and type 2 items.

Whats the best way to grab all "site_id:1_item_id:3" type records? While avoiding the ones including user_id? Is there an EOL match I can use?

Secondly, I've read using KEYS is a bad choice, can anyone recommend a different approach here? I'm open to editing the key names if I must.

like image 776
Elliot Avatar asked Nov 21 '25 13:11

Elliot


1 Answers

First thing first: unless your are the only redis user on your local developpment machine, you are right using KEYS is wrong. It blocks the redis instance until completed, so anyone querying it while you are using keys will have to wait for you keys query to be finished. Use SCAN instead.

SCAN will iterate over the entries in a non blocking way, and you are guaranteed to get all of them. I don't know which language you use to query it, but in python it is quite easy to query the keys with scan and filter them on the fly.

But let's say you would like to use keys anyway. Looks to me like either doing KEYS site_id:1_item_id:? or KEYS site_id:1_item_id:3 does the trick. wether you want the keys finishing with "3" or not (I am not sure I completely understood your question here).

Here is an example that I tried on my local machine:

redis 127.0.0.1:6379> flushall
OK
redis 127.0.0.1:6379> set site_id:1_item_id:3 a
OK
redis 127.0.0.1:6379> set site_id:1_item_id:3_user_id:6 b
OK
redis 127.0.0.1:6379> set site_id:1_item_id:4 c
OK

// ok so we have got the database cleaned and set up
redis 127.0.0.1:6379> keys *
1) "site_id:1_item_id:3"
2) "site_id:1_item_id:4"
3) "site_id:1_item_id:3_user_id:6"

// gets all the keys like site_id:1_item_id:X
redis 127.0.0.1:6379> keys site_id:1_item_id:?
1) "site_id:1_item_id:3"
2) "site_id:1_item_id:4"

// gets all the keys like site_id:1_item_id:3
redis 127.0.0.1:6379> keys site_id:1_item_id:3
1) "site_id:1_item_id:3"

Don't forget that Redis KEYS uses GLOB style pattern, which is not exactly like a regex. You can check out the keys documentation examples to make sure you understand

like image 120
Arnaud Potier Avatar answered Nov 23 '25 19:11

Arnaud Potier