Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do redis hashes maintain order of insertion [duplicate]

Tags:

redis

Do redis hashes remain the order of key-value pairs they are inserted in? I cannot find anything on this from redis' documentation.

A simple test does say that they remain order but is this ensured? Will this work with cluster or sentinel?

like image 598
Rob Fox Avatar asked Apr 19 '18 16:04

Rob Fox


People also ask

How does Redis hash work?

Redis is an open-source, in-memory key-value data store. A Redis hash is a data type that represents a mapping between a string field and a string value. Hashes can hold many field-value pairs and are designed to not take up much space, making them ideal for representing data objects.

Which of the following does Redis hashes store?

A Redis Hash can store up to 4 billion key value pairs. If the value is Integer, Redis hash allows you to atomically increment or decrement the value. It is a highly performant data structure and supports adding a key, removing a key, and checking membership of key in constant time or O(1).

What does Redis HSET return?

The command returns an integer value indicating the number of fields removed from the hash. If the field does not exist, the command ignores it and only removes the existing ones. To check if a field exists in the hash, use the HEXISTS command. The command returns integer 1 if the key exists and 0 if not.

Can one key have multiple values in Redis?

In Redis you can also have lists as the value, which overcomes the problem of having more than one value for a key, as you can have an ordered list with multiple values (so “they'll none of 'em be missed”).


1 Answers

NO, Redis hash doesn't maintain the order. Since it's a hash, it's unordered. If you need to maintain the insertion order, you have do it yourself.

You can use a LIST to save the order. Each time you insert an item to hash, also push it to the list. You can wrap these two operations into a transaction or a Lua scripting to make it run automatically.

like image 125
for_stack Avatar answered Oct 02 '22 15:10

for_stack