Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 323
Umbrella Avatar asked Aug 24 '18 09:08

Umbrella


People also ask

Can we store JSON as value in Redis?

You can store JSON in redis either as a plain string in dedicated key (or member/value of a set/list) or in a hash structure. If you look at node_redis docs into Friendlier hash commands part you'll see that it gives you some useful methods for manipulating JSON based data.

How do I query a JSON object?

To query JSON data, you can use standard T-SQL. If you must create a query or report on JSON data, you can easily convert JSON data to rows and columns by calling the OPENJSON rowset function. For more information, see Convert JSON Data to Rows and Columns with OPENJSON (SQL Server).

Can you index a JSON object?

You can index JSON data as you would any data of the type that you use to store it. In particular, you can use a B-tree index or a bitmap index for SQL/JSON function json_value , and you can use a bitmap index for SQL/JSON conditions is json , is not json , and json_exists .


1 Answers

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!

like image 85
Urosh T. Avatar answered Sep 21 '22 08:09

Urosh T.