Engineering

How to Manage Hashes in Redis

October 1st, 2023
Written by
Paul Krishnamurthy

Introduction

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.

Creating Hashes

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.

Retrieving Hash Information

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:

  • HGETALL - Get all fields and values
  • HKEYS - Get all field names
  • HLEN - Get number of fields
  • HEXISTS - Check if field exists

Updating and Deleting

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.

Additional Tips

  • Use a consistent key naming scheme like objectType:id
  • Hashes are flexible for storing objects like users, products, etc.
  • Redis hashes have space efficiency advantages over other structures

Conclusion

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.