数据库设计 – Redis多列范围查询

前端之家收集整理的这篇文章主要介绍了数据库设计 – Redis多列范围查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有Redis Hashes的用户,并希望根据工资和年龄找到类似的用户(给定一个特定的用户).
<user>
  <id>101</id>
  <name>Neo</name>
  <age>30</age>
  <salary>300</salary>
  ....
</user>
@H_301_4@所以,在这种情况下,我需要在一定的限度内找到接近我的年龄和工资的用户接近我的工资.
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
@H_301_4@我们可以这样做,比如说使用ZINTERSTORE,结果集合是按照sql中的用户相似性排序的吗?

@H_404_11@

解决方法

这不像SQL查询那么容易.你需要设置一些键等. @H_301_4@不过,这就是我认为的方法.
您需要创建两个已排序的集合,其中用户ID为成员,年龄/薪水为分数.

ZADD index:user:age 30 101 # 101 is id of user whose name is Neo
ZADD index:user:salary 300 101
@H_301_4@为两个条件创建中间集

# 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
@H_301_4@最后

@H_301_4@>删除临时密钥>使用MULTI / EXEC运行所有这些命令,以便只有一次往返

@H_404_11@ @H_404_11@ 原文链接:https://www.f2er.com/mssql/77487.html

猜你在找的MsSQL相关文章