Search JSON values in redis
Asked Answered
C

1

6

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?

Cracked answered 24/8, 2018 at 9:38 Comment(0)
S
5

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!

Scarper answered 24/8, 2018 at 10:20 Comment(2)
Yeah, this might be a good work around if you want to search redis only using the service_id.Hogan
You can query by any field by just creating an appropriate structure. Just like you would create an index in a MySQL, you can create a hash with the key you want to query by. It may require two trips, yes, but with an in-memory database, you can definitely afford it. You can even use Pseudo Multi Key Queries but that is a bit advance for this purposeScarper

© 2022 - 2024 — McMap. All rights reserved.