How to implement redis Index
Today, I would like to share with you how to achieve the redis index, I believe many people do not understand, in order to let you know more about the redis index, so give you a summary of the following content, let's look down. I'm sure you'll get something.
Redis does not support indexes directly and needs to be maintained on its own.
For non-scope unique indexes, we can simply save the indexes as KV pairs, v to save the main key, and scope retrieval, or non-unique indexes, to use redis's zset to achieve.
Give an example of a traditional user system.
Uid user idname username credit user credit type type
You can put it directly into a hashset
Hmset usr:1 uid 1 name aaa credit 10 type 0hmset usr:2 uid 2 name bbb credit 20 type 1
Retrieval through uid is fast, but if you want to query users of type=1, you can only scan it all!
In a relational database, we can simply build an index on type
Select * from usr where type=1
In this way, SQL can be executed efficiently. We need to maintain another zset in redis.
Zadd usr.index.type 0 0:1zadd usr.index.type 0 1:2
Notice that the ownership weight is set to 0 so that it can be retrieved directly by value, and then through the
Zrangebylex usr.index.type [1: (1)
On how to achieve the redis index to share here, I hope that the above content can have a certain reference value for everyone, you can learn to apply. If you like this article, you might as well share it for more people to see.