This article comes from a question from Redis on Google Group, a classmate to ask for help, said to solve a problem: He has an IP range corresponding address list, now need to give an IP case, quickly find the IP in which range, that is, to determine the IP of all the land. The question drew an answer from Redis author Salvatore Sanfilippo (@antirez). The answers are as follows:
For example there are two ranges below, 10-20 and 30-40
Copy Code code as follows:
A_start, A_end 20
B_start, B_end 40
We present the starting position of these two ranges in the Redis sorted sets data structure, the base range starting value as the score, and the range name plus start and end as their value values:
Copy Code code as follows:
Redis 127.0.0.1:6379> zadd Ranges A_start
(integer) 1
Redis 127.0.0.1:6379> zadd Ranges a_end
(integer) 1
Redis 127.0.0.1:6379> zadd Ranges B_start
(integer) 1
Redis 127.0.0.1:6379> zadd Ranges b_end
(integer) 1
After inserting the sorted sets, the data is equivalent to arranging the starting positions in order.
Now I need to look for 15 in which range, only the following Zrangbyscore lookup is required:
Copy Code code as follows:
Redis 127.0.0.1:6379> zrangebyscore ranges (+inf LIMIT 0 1
1) "A_end"
The meaning of this command is to look for the first value greater than 15 in sorted sets. (+inf represents positive infinity in Redis, and parentheses in front of 15 represent >15 rather than >=15)
The result of the lookup is a_end, because all values are in order, so you can determine that 15 is on the A_start to the A_end interval, which means that 15 is in the range of a. It's done.
Of course, if you're looking for a start, like we use 25, execute the following command
Copy Code code as follows:
Redis 127.0.0.1:6379> zrangebyscore Ranges (+inf 0 1
1) "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 lookup 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 can we solve it? Welcome readers to challenge you.