Reputation: 3377
If I have a redis hmap that looks like the following:
client.hset('test', 'one', 'aaa');
client.hset('test', 'two', 'bbb');
client.hset('test', 'three', 'ccc');
client.hset('test', 'four', 'ddd');
and I want to find if the map has a value like ccc
whats the best way to do that?
I can call something like
client.hgetall('test', function(err, obj){
for(id in obj){
if(obj[id] == 'ccc'){
return id;
}
}
});
But this seems very inefficient, is there a search or find method in redis that would produce nicer solution?
Upvotes: 0
Views: 67
Reputation: 22886
There's no built-in way to search by value. If you want to do it more efficient, you have to build an inverted index from value to key, e.g. inverted-test. Each time when you update the test hash, also update the inverted index.
HSET test one aaa
HSET inverted-test aaa one
NOTE
If in your original hash, multiple keys might have the same value. You might need to implement the inverted index with a LIST
.
HSET test one aaa
LPUSH inverted-test:aaa one
HSET test two aaa
LPUSH inverted-test:aaa two
Upvotes: 1
Reputation: 161
You could use the filter method like this:
client.hgetall('test', (err, obj) => {
// in here we create an array of the object obj properties
const keys = Object.keys(obj);
// and now we iterate that array with the filter method
const wantedValues = keys.filter(key => obj[key] === 'ccc');
// wantedValues is now a array with the keys of the object obj that have the value ccc
});
Upvotes: 0