amazon-web-servicesredisstackexchange.rediselastic-cache

Sort redis hash maps based on string field


I'm trying to implement query functionality for my AWS redis cluster. I have stored all my data as hash maps and also created SortedSet for each of the indexed fields.

Whenever a query is received we query SortedSet to find ids. The querying may involve multiple indexes as well which gets merged based on AND/OR conditions. Once we have the final set of ids we need to sort the data based on some fields. So basically im fetching list of hashmaps which matches the ids. The hashmap looks like below

HSET employees::1 name Arivu salary 100000 age 30
HSET employees::2 name Uma salary 300000 age 31
HSET employees::3 name Jane salary 100000 age 25
HSET employees::4 name Zakir salary 150000 age 28

Now I'm adding all the hashes to a set so that I can use a sort function

SADD collection employees::1 employees::2 employees::3 employees::4

Now when i try to sort based on string field the sort doesn't seems to work

127.0.0.1:6379> SORT collection by name
1) "employees::2"
2) "employees::4"
3) "employees::3"
4) "employees::1"
127.0.0.1:6379> SORT collection by name desc
1) "employees::2"
2) "employees::4"
3) "employees::3"
4) "employees::1"

I assume this is because the hasmaps are stored as byte data but is there anyway i can sort these alphabetically?

I have also tried using alpha param which sort function provides but it doesnt seems to work

SORT collection by name desc ALPHA

Solution

  • Your usage seems to be incorrect. Set your hash like this (like you are doing)

    HSET employees::1 name Arivu salary 100000 age 30
    HSET employees::2 name Uma salary 300000 age 31
    HSET employees::3 name Jane salary 100000 age 25
    HSET employees::4 name Zakir salary 150000 age 28
    

    Store your ids in the set like this:

    SADD collection 1 2 3 4
    

    Please note in the set I just store the ids of the employee (1,2,3,4).

    Now time to sort

    SORT collection by employees::*->name ALPHA
    

    It will sort like this as you expected

    1) "1"
    2) "3"
    3) "2"
    4) "4"
    

    In case you need fields do like this:

    SORT collection by employees::*->name ALPHA GET employees::*->name
    
    1) "Arivu"
    2) "Jane"
    3) "Uma"
    4) "Zakir"  
    

    In case you need age also along with name:

    SORT collection by employees::*->name ALPHA GET employees::*->name GET employees::*->age
    1) "Arivu"
    2) "30"
    3) "Jane"
    4) "25"
    5) "Uma"
    6) "31"
    7) "Zakir"
    8) "28"