Jim
Jim

Reputation: 16002

REDIS: Find all keys in an HSET that are missing a particular field

Given some HSET(s).

HSET 'TEST:1' X 10
HSET 'TEST:1' Y 20
HSET 'TEST:1' Z 10 (First Set Keyed on 'TEST:1')

HSET 'TEST:2' X 10
HSET 'TEST:2' Y 20 (Second Set Keyed on 'TEST:2')

The second set above has no value for 'Z'

How would I write an LUA SCAN to find all the KEYS where the 'Z' value has not been set? I am not sure how to get the script to output only the ones where a key field does not exist.

Is it possible to write one where the SCAN does not block? Either way is good.

Upvotes: 1

Views: 210

Answers (1)

Ankit Sahay
Ankit Sahay

Reputation: 2043

One way to do this is, create a set with name of all your hashmaps, like:

SADD ALLSETS TEST:1
SADD ALLSETS TEST:2

Now, when you are adding subkeys (X, Y, Z) in your hashmaps, create a set for each subkeys:

SADD X:SETS TEST:1
SADD X:SETS TEST:2

SADD Y:SETS TEST:1
SADD Y:SETS TEST:2

SADD Z:SETS TEST:1

What this means is, now you have X:SET containing all your hashmaps that had X subkey in it. Similarly, you have Y:SET that contains the name of all hashmaps which has Y subkey in it.

Now, speaking a language of Set Theory, your question is: what are the elements that are present in “ALLSETS” but not in “Z:SETS”, and this operation in Set Theory is called difference operation (which, luckily Redis supports)

SDIFF ALLSETS Z:SETS
1)”TEST:2”

Upvotes: 1

Related Questions