Reputation: 1938
I have a redis hash store that looks like Item:<id>
, with attribute name
. I want to filter the hash store by a prefix for name
attribute.
What I'm trying to do is store the name (lowercased) in a separate Z-set called Item:::name
while setting the score to 0. By doing this, I'm successfully able to get the desired result using ZRANGEBYLEX
however I'm unable to map the results back to the original Items
. How should I go about implementing something like this?
I've seen multiple autocomplete examples for Redis which require the same functionality but without linking the words back to an actual Item (hash in this case)
Upvotes: 0
Views: 445
Reputation: 9594
In sorted sets
the member
can't be duplicated, it has to be unique. So different users with the same name will cause problem.
My suggestion requires application layer coding to parse response array and executing hash
commands (it will be like secondary indexes);
127.0.0.1:6379> HSET user:1 name jack
(integer) 1
127.0.0.1:6379> HSET user:2 name john
(integer) 1
127.0.0.1:6379> HSET user:3 name keanu
(integer) 1
127.0.0.1:6379> HSET user:4 name jack
(integer) 1
127.0.0.1:6379> ZADD item:names 0 jack::user:1 0 john::user:2 0 keanu::user:3 0 jack::user:4
(integer) 4
127.0.0.1:6379> ZRANGE item:names 0 -1 WITHSCORES
1) "jack::user:1"
2) "0"
3) "jack::user:4"
4) "0"
5) "john::user:2"
6) "0"
7) "keanu::user:3"
8) "0"
127.0.0.1:6379> ZRANGEBYLEX item:names [jack [jo
1) "jack::user:1"
2) "jack::user:4"
At the end you will have name::hash-key
formatted array elements. At application layer if you separate each element to two substrings by using ::
(any other string such as !!!
or ||
etc) you will have user:1
and user:4
.
127.0.0.1:6379> HGETALL user:1
1) "name"
2) "jack"
127.0.0.1:6379> HGETALL user:4
1) "name"
2) "jack"
127.0.0.1:6379>
Upvotes: 2