Redis: Sort and get n Neighbour Keys

2019-04-11 22:12发布

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.

标签: redis
2条回答
淡お忘
2楼-- · 2019-04-11 22:52

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 than score the query looks like this:

zrangebyscore KEY <SCORE> +inf limit 0 <N>

And the n with scores greater than like this:

zrevrangebyscore KEY +inf <SCORE> limit 0 <N>

Say you had sorted set test:key_sort like this:

"a": 10
"b": 20
"c": 30
"d": 40
"e": 50

Then zrevrangebyscore test:key_sort +inf 25 limit 0 2 returns d, c and zrangebyscore test:key_sort -inf 25 limit 0 2 returns a, b

查看更多
我想做一个坏孩纸
3楼-- · 2019-04-11 23:04

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.

ZRANGEBYSCORE theKey 1220 1600

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".

查看更多
登录 后发表回答