Query multiple Redis columns

I have users like Redis Hashes and you want to find similar users (based on a specific 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, as within certain 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, so that the result set is ordered in the likeness of a user, as in SQL?

+6
source share
1 answer

It is not as simple as an SQL query. You need to install some keys, etc.

However, here is what I think is a way to do this. You will need to create two sorted sets with the user ID as a member and age / salary as an estimate.

 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

  • delete temporary keys
  • Run all of these commands with MULTI / EXEC so that there is only one round trip.
+11
source

Source: https://habr.com/ru/post/888721/


All Articles