简体   繁体   中英

Redis - Sorted Dictionary

Redis has the data structure sorted sets, which allows you to create a set that is sorted by some score value.

There are several problems that I'm trying to solve

  1. I need to store similar members but with different scores (not possible with sets). One solution is to concatenate the score with the original value and store it as the value, but it's kinda ugly.

  2. I need to have only one member per score and I need a way to enforce it.

  3. I need to be able to update or remove member by score, like in a dictionary.

The best example of what I'm looking for is an order book I need to be able to set amount of a certain price, remove price and retrieve amounts and prices sorted by prices

SET orderBook_buy 1.17 30000
SET orderBook_buy 1.18 40000
SET orderBook_buy 1.19 40000
SET orderBook_buy 1.17 35000 // Override the previous value of 1.17
DEL orderBook_buy 1.18 // 1.18 was sold out

I think it can be done if I combine sorted sets and hash tables

I keep the prices in sorted sets

ZADD orderBook_buy_prices 1.17 1.17
...
ZREM orderBook_buy_prices 1.18

And the amounts in hash tables, by prices

HSET orderBook_buy 1.17 35000
...
HDEL orderBook_buy 1.17

It could work but i have to do 2 reads and 2 writes every time, and also make sure that the writes are inside a transaction.

Is there a data structure in redid that support sorted dictionaries out of the box (Could be a module)?

Thank you.

It could work but i have to do 2 reads and 2 writes every time, and also make sure that the writes are inside a transaction.

You also want to do the reads in a transaction, unless you don't care about possible read consistency problems.

Is there a data structure in redid that support sorted dictionaries out of the box (Could be a module)?

Sorted Sets are just that, but what you're looking for is a single data structure that is a sort of a two way dictionary with ordering (albeit only on one subset of keys/values <- depending the direction you're coming from).

Your approach of "welding" together two existing structures is perfectly valid, with the constraints you've pointed out about two keys and transactionality. You could use a Lua script to wrap the logic and not worry about transactions, but you'd still have it touch 2 keys via two ops.

AFAIK there is no Redis module ATM that implements this data structure (although it should be possible to write one).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM