skip to Main Content

How to write the below in Redis

"Create a sorted set myset1 with the following values ( 1, ‘a’, 2, ‘b’, 3 , ‘c’).Create a sorted set myset 2 with the following values (4, ‘b’, 1, ‘c’, 0, ‘d’).Find the intersection of myset1 and myset2 : – Write a command to find the intersection of myset1 and myset2 and store the intersection in out- Write a command to see the resulting intersection output Sorted set "out" : Find the union of myset1 and myset2 – Write a command to take the union of myset1 and myset2 and store the output in unout – Write a command to see the resulting intersection output Sorted set "unout" "

I wrote the code like below and it says 80% correct.

127.0.0.1:6379> zadd myset1 0 1 0 a 0 2 0 b 0 3 0 c (integer) 6 127.0.0.1:6379> zadd myset2 0 4 0 b 0 1 0 c 0 0 0 d (integer) 6 127.0.0.1:6379> zinterstore out 2 myset1 myset2 (integer) 3 127.0.0.1:6379> zrange out 0 -1 1) "1" 2) "b" 3) "c" 127.0.0.1:6379> zunionstore unout 2 myset1 myset2 (integer) 9 127.0.0.1:6379> zrange unout 0 -1 1) "0" 2) "1" 3) "2" 4) "3" 5) "4" 6) "a" 7) "b" 8) "c" 9) "d" 127.0.0.1:6379>

2

Answers


  1. You can use ZINTERSTORE and ZUNIONSTORE commands to computer intersection and union of intersection of sorted sets.

    ZINTERSTORE

    ZINTERSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]

    Computes the intersection of numkeys sorted sets given by the
    specified keys, and stores the result in destination. It is mandatory
    to provide the number of input keys (numkeys) before passing the input
    keys and the other (optional) arguments.

    By default, the resulting score of an element is the sum of its scores
    in the sorted sets where it exists. Because intersection requires an
    element to be a member of every given sorted set, this results in the
    score of every element in the resulting sorted set to be equal to the
    number of input sorted sets.

    ZUNIONSTORE

    ZUNIONSTORE destination numkeys key [key …] [WEIGHTS weight [weight …]] [AGGREGATE SUM|MIN|MAX]

    Computes the union of numkeys sorted sets given by the specified keys,
    and stores the result in destination. It is mandatory to provide the
    number of input keys (numkeys) before passing the input keys and the
    other (optional) arguments.

    By default, the resulting score of an element is the sum of its scores
    in the sorted sets where it exists.

    Edit:
    It’s not accepting since you’re adding score as key as well

    Yout ZADD commands should be

    ZADD myset1 1, a 2 b 3  c
    zadd myset2  4  b  1  c   0 d
    
    Login or Signup to reply.
  2. Try this

    ZADD myset1 1 a 2 b 3 c
    
    ZADD myset2 4 b 1 c 0 d
    
    ZINTERSTORE out 2 myset1 myset2
    
    ZUNIONSTORE unout 2 myset1 myset2 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search