redissecondary-indexes

Redis Secondary Indexes and Performance Question


I know that Redis doesn't really have the concept of secondary indexes, but that you can use the Z* commands to simulate one. I have a question about the best way to handle the following scenario.

We are using Redis to keep track of orders. But we also want to be able to find those orders by phone number or email ID. So here is our data:

> set 123 7245551212:dlw@email.com
> set 456 7245551212:dlw@email.com
> set 789 7245559999:kdw@email.com
> zadd phone-index 0 7245551212:123:dlw@email.com
> zadd phone-index 0 7245551212:456:dlw@email.com
> zadd phone-index 0 7245559999:789:kdw@email.com

I can see all the orders for a phone number via the following (is there a better way to get the range other than adding a 'Z' to the end?):

> zrangebylex phone-index [7245551212 (7245551212Z
1) "7245551212:123:dlw@dcsg.com"
2) "7245551212:456:dlw@dcsg.com"

My question is, is this going to perform well? Or should we just create a list that is keyed by phone number, and add an order ID to that list instead?

> rpush phone:7245551212 123
> rpush phone:7245551212 456
> rpush phone:7245559999 789
> lrange phone:7245551212 0 -1
1) "123"
2) "456"

Which would be the preferred method, especially related to performance?


Solution

  • RE: is there a better way to get the range other than adding a 'Z' to the end? Yes, use the next immediate character instead of adding Z:

    zrangebylex phone-index [7245551212 (7245551213
    

    But certainly the second approach offers better performance.

    Using a sorted set for lexicographical indexing, you need to consider that:

    In contrast, using lists:

    You can also use sets (SADD and SMEMBERS), the difference is lists allows duplicates and preserves order, sets ensure uniqueness and doesn't respect insertion order.