Umbrella
Umbrella

Reputation: 1145

Search JSON values in redis

I'm developing a nodeJS server that uses redis as a database and I need to retrieve all the redis keys that have a certain service_id value. For example, if service id is 4, I need to retrieve all the keys where service_id = 4. I've got the following structure in redis where value is JSON:

key: "{service_id: number}"

Is it possible to filter the keys that have a certain service id? Maybe there is some workaround to make it possible?

Upvotes: 6

Views: 6628

Answers (1)

Urosh T.
Urosh T.

Reputation: 3824

Even though redis is a key:value store, there are soooo many ways that you can tweak it to your benefit. For example, you can use hashes and store your values like this:

HSET services service:1 foo
HSET services service:2 bar
HSET services service:3 buz

So the syntax is HSET hashname fieldname value where as a field you are separating the ids with a colon.

If you have more than 1 value per key, you can do the following:

HSET services service:1:name foo
HSET services service:1:id 1
HSET services service:2:name bar
HSET services service:2:id 2

So, by separating your key with another colon, you can store more values. Then if you want to retrieve all from service 1, you can do a SCAN with a wildcard, like so:

HSCAN services 0 match service:1:*

Heck, you can even store each service as a separate hash:

HSET services:1 id 1
HSET services:1 name foo
HSET services:2 id 2
HSET services:2 name buz

Or make it even shorter with HMSET

HMSET services:1 id 1 name foo
HMSET services:2 id 2 name buz

In conclusion - Redis is awesome!

Upvotes: 5

Related Questions