Original: Https://groups.google.com/forum/#!topic/redis-db/lrYbkbxfQiQ
This article comes from a problem with Redis on Google Group, a classmate posts for help, said to solve one of the following problems: He has an IP range corresponding to the list of addresses, now need to give an IP case, quickly find the IP in which range, That is to judge all the land of this IP. The question drew the answer from Redis author Salvatore Sanfilippo (@antirez). The answers are as follows:
For example, there are two ranges, 10-20 and 30-40
- A_start, A_end 20
- B_start, B_end 40
We will have the starting position of these two ranges in the sorted sets data structure of Redis, the base range starting value as score, the range name plus start and end for its value:
Redis 127.0.0.1:6379> zaddranges 1127.0.0.1:6379> zadd ranges 1 127.0.0.1:6379> zadd ranges1127.0.0.1:6379> zadd ranges 1
This way, after inserting sorted sets, the data corresponds to the order in which the starting positions are sorted.
Now I need to find out where the value of 15 is in the range, only the following zrangbyscore lookups are required:
" A_end "
This command means finding the first value greater than 15 in the sorted sets. (+inf represents positive infinity in Redis, and 15 front brackets denote >15 rather than >=15)
The result of the lookup is a_end, since all values are in order, so it is possible to determine that 15 is on the A_start to A_end interval, that is, 15 is in a range. That's it.
Of course, if you find a start, like we use 25, execute the following command
" B_start "
The return result indicates that the next node is a start node, meaning that the value of 25 is not in any range between start and end.
Of course, this example applies only to cases similar to the IP range lookups above, because there is no overlap between the ranges of values. If there is a coincidence, the problem itself becomes a one-to-many problem. Well, if there is a overlap, how do we solve it? Welcome to the students to challenge you.
Redis application case, finding the range of a value (GO)