Redis多列范围查询

发布于 2024-11-09 02:18:28 字数 554 浏览 4 评论 0原文

我有 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 中一样?

I have users as Redis Hashes and want to find similar users (given a particular user) based on salary and age.

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

So, in this case I need to find users who are close to my age AND salary close to my salary both within some given limits.
In SQL, I would hypothetically do something like

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

Can we do this, say using ZINTERSTORE, in such a way that the resulting set is ordered by user similarity like in the SQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

莫言歌 2024-11-16 02:18:28

这并不像 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 运行所有这些命令,以便只有一个往返

This is not exactly as easy as a SQL query. You need set some keys etc.

Nevertheless here is what I think is the way to do it.
You would need to create two sorted sets with user id as member and age/salary as score.

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

Create intermediate sets for both conditions

# 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

Finally

  • remove temp keys
  • Run all these commands using MULTI/EXEC so that there is only one round trip
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文