Redis is an open-source, in-memory key-value data store. A Redis hash is a data type that represents a mapping between string fields and string values. Hashes are useful for representing objects or documents, like customers, products, etc. This article will explain how to create, retrieve, update and delete hash data in Redis.
To create a new hash, use the HSET command followed by the hash key name, field, and value:
This will create a new hash called "user:1" with a field "name" set to "John Doe".
You can also set multiple field-value pairs at once with HMSET:
HSET will return 1 if the field is new, and 0 if it overwrote an existing field. HMSET returns "OK" on success.
To only set a field if it doesn't exist, use HSETNX. This prevents overwriting existing data.
To get a specific field's value, use HGET:
This will return "John Doe".
To get multiple values at once, use HMGET:
Other useful retrieval commands include:
To update a field value, just HSET it again. This will overwrite the existing value.
To only update if field doesn't exist, use HSETNX instead.
To delete a field, use HDEL. You can delete multiple fields at once:
And DEL will completely delete the hash.
Redis hashes provide a useful data structure for flexibly storing object data. With commands like HSET, HGET, HMSET you can create, retrieve, update and delete hashes. Hashes have great flexibility in Redis and are useful for many cases like user profiles, product information, document metadata and more.