How to sort, store and POP weighted items using ZADD and ZPOPMIN|MAX in redis?
There is often a need to sort items(strings, integers etc.) on the basis of weight attached along with each one of them. Though a SORT by WEIGHT feature is available in redis, as found at https://redis.io/commands/sort, another way to dynamically sort and store weighted items is explained here. For example consider the following items(elements) along with their weights:-
Set name = ordered_array |
In order to get these elements in the order of their weights, add them to the redis data structure using ZADD and pop each element one by one using ZPOPMIN (or ZPOPMAX if needed in opposite order of weights). A running redis-server is required for this code to work. For installation instructions on redis refer to https://foolsvilla.blogspot.com/2020/03/installing-redis-508-on-linux-ubuntu.html .
The hiredis library is installed along with redis. Following C code is used along with this hiredis library to access redis data structure. The code adds elements with weights to redis and retrieves each element in the sorted order of weights from minimum to maximum. That is, element with weight 1 gets printed first followed by element with weight 2 and so on..
The hiredis library is installed along with redis. Following C code is used along with this hiredis library to access redis data structure. The code adds elements with weights to redis and retrieves each element in the sorted order of weights from minimum to maximum. That is, element with weight 1 gets printed first followed by element with weight 2 and so on..
weighted_sort.c |
Save the above code to a file named weighted_sort.c
Compile the code from terminal with gcc using
$> gcc weighted_sort.c -o weighted_sort -lhiredis
Execute the code to observe result with
$> ./weighted_sort
Following gets printed:- sorted
The characters(actually stored as strings in redis) gets printed in the order of their weights here.
Footnote
Redis 5 or more is requried for this.
Following gets printed:- sorted
The characters(actually stored as strings in redis) gets printed in the order of their weights here.
Footnote
Redis 5 or more is requried for this.
JMT Casino & Resort - Hollywood, FL - JMTH Hub
ReplyDeleteJMT 서귀포 출장마사지 Casino & Resort 평택 출장안마 is located in Hollywood, FL 하남 출장샵 and is part of the Hollywood Group and has a AAA Four 의정부 출장마사지 Diamond status. JMT Hotel 서울특별 출장마사지 is