Let's say I have these pairs in Redis:
1237.56 "John"
1224.59 "Robert"
1213.34 "Mahmoud"
1242.90 "George"
1020.11 "Mary"
1723.09 "Jay"
1589.77 "Khan"
1106.62 "Albert"
The keys are always a decimal number. When provided a number, I would like to get two keys in both directions with closest number.
For example, if I search for the neighbours of 1242
, the resultset should have:
1224.59 "Robert"
1237.56 "John"
1242.90 "George"
1589.77 "Khan"
Is this possible? I'm still new to Redis and thanks for any help.
This is possible using
zrangebyscore
with the limit parameter. You will need to make two queries - one to get the neighbours on each side.For example if you want to get the
n
with a score less thanscore
the query looks like this:And the
n
with scores greater than like this:Say you had sorted set
test:key_sort
like this:Then
zrevrangebyscore test:key_sort +inf 25 limit 0 2
returnsd, c
andzrangebyscore test:key_sort -inf 25 limit 0 2
returnsa, b
Yes and no the same time.
Why yes? The only one redis data type - SORTED SET allow you to get range of values based on decimal. So with ZRANGEBYSCORE you can get values by score range.
Gives you sought-for data set.
Why No? In your question your ask about neighbours of score. ZRANGEBYSCORE can get values from min score to max score but not the "get X values less then given" or "X values great then given".