【问题标题】:Redis multi column range queryRedis 多列范围查询
【发布时间】:2011-08-30 08:54:41
【问题描述】:

我有用户作为 Redis 哈希,并希望根据薪水和年龄找到相似的用户(给定特定用户)。

<user>
  <id>101</id>
  <name>Neo</name>
  <age>30</age>
  <salary>300</salary>
  ....
</user>

因此,在这种情况下,我需要在给定的限制范围内找到与我的年龄和工资接近的用户。 在 SQL 中,我假设会做类似

的事情
SELECT id, abs(age - 30) as agediff, abs(salary - 300) as saldiff FROM
 USERS WHERE 
(age BETWEEN 25 35) AND (salary BETWEEN 250 350) ORDER BY agediff ASC, saldiff ASC

我们能否做到这一点,比如使用 ZINTERSTORE,使得结果集按照用户相似度排序,就像在 SQL 中一样?

【问题讨论】:

    标签: database-design data-modeling redis


    【解决方案1】:

    这并不像 SQL 查询那么简单。您需要设置一些键等。

    尽管如此,这就是我认为的方法。 您需要创建两个排序集,其中用户 ID 作为成员,年龄/薪水作为分数。

    ZADD index:user:age 30 101 # 101 is id of user whose name is Neo
    ZADD index:user:salary 300 101 
    

    为这两个条件创建中间集

    # Condition 1: age 25-30
    ZUNIONSTORE temp:age 1 index:user:age WEIGHTS 1
    ZREMRANGEBYSCORE temp:age 0 24
    ZREMRANGEBYSCORE temp:age 36 INF
    # Condition 2: Repeat above for salary
    # Now create result set which is intersection of both above sets
    ZINTERSTORE temp:result 2 temp:salary temp:age # 2 is no. of sets to intersect
    # Verify result
    ZRANGE temp:result 0 -1
    

    终于

    • 删除临时键
    • 使用 MULTI/EXEC 运行所有这些命令,以便只有一次往返

    【讨论】:

    • 我已经实施了解决方案 - 它与您的方案太接近了。我猜你的意思是在 ZRANGE 之前取两个 Zset 的 ZINTERSTORE 而不是 UNION
    • 是的,那是错字。更新了我的答案。
    猜你喜欢
    • 2020-05-10
    • 2021-04-25
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    相关资源
    最近更新 更多