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?
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.
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).
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 .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With