Reputation: 1160
How do you search for keys with a value in Ruby? For example get all KEYS where the value is "somevalue".
My keys are
"xyz" => {:status=> "connected", :topic=> "ABC"}
"PQR" => {:status=> "connected", :topic=> "ABC"}
Now I need to find all the KEYS where topic is "ABC"
Upvotes: 1
Views: 5016
Reputation: 2965
Depends on which version of redis you can use getkeys on redis >= 2.8.13 or you could use keys command taking care some performance issues (if you have few keys should not be a problem but if you have a large amount of keys take care with that, because keys command will block redis for a few moment in order to get all keys)
If you are running redis 2.8 you'll be able to use scan command instead keys.
EDIT: A recently added page in Redis' documentation provides more information about Secondary indexing with Redis and covers this case under the Non range indexes section. Additional topics in it include:
Upvotes: 1
Reputation: 49932
Regardless the programming language, to do this efficiently you'll need to maintain an "index" key that maps somevalue to the key names. Using a Set or a Sorted Set for this is what you should usually do - i.e. add new key names to it and remove them according to their values - and get that key's contents when you want to "search".
There are some libraries (i.e. gems) that may provide this sort of functionality ready to use - look into the most excellent Ohm in your case.
EDIT
My keys are xyz => {:status=> "connected", :topic=> "ABC"} PQR => {:status=> "connected", :topic=> "ABC"} Now I need to find all the KEYS where topic is "ABC"
I would store xyz's value as a String or a Hash (depending on whether I need to update/read just parts of it or not). Then I would SADD topic:ABC xyz
and do SMEMBERS
or SSCAN
on it to get the names of all keys with that topic. I'd also try to remember to SREM
the relevant member from topic:ABC when I DEL
its key...
Upvotes: 6