Redis hashes

Introduction to Redis hashes

Redis hashes are record types structured as collections of field-value pairs. You can use hashes to represent basic objects and to store groupings of counters, among other things.

While hashes are handy to represent objects, actually the number of fields you can put inside a hash has no practical limits (other than available memory), so you can use hashes in many different ways inside your application.

The command HSET sets multiple fields of the hash, while HGET retrieves a single field. HMGET is similar to HGET but returns an array of values:

There are commands that are able to perform operations on individual fields as well, like HINCRBY:

You can find the full list of hash commands in the documentation.

It is worth noting that small hashes (i.e., a few elements with small values) are encoded in special way in memory that make them very memory efficient.

Basic commands

  • HSET: sets the value of one or more fields on a hash.
  • HGET: returns the value at a given field.
  • HMGET: returns the values at one or more given fields.
  • HINCRBY: increments the value at a given field by the integer provided.

See the complete list of hash commands.

Field expiration

The following commands can be used to add, delete, and report on a key's individual field TTL or expiration time:

  • HEXPIRE: set the remaining time to live in seconds for a key's fields.
  • HPEXPIRE: set the remaining time to live in milliseconds for key's fields.
  • HEXPIREAT: set the expiration time to a UNIX timestamp specified in seconds since the Unix epoch.
  • HPEXPIREAT: set the expiration time to a UNIX timestamp specified in milliseconds since the Unix epoch.
  • HEXPIRETIME: get the expiration time as a Unix timestamp in seconds since the Unix epoch.
  • HPEXPIRETIME: get the expiration time as a Unix timestamp in milliseconds since the Unix epoch.
  • HPERSIST: remove the expiration time from a key's fields.
  • HTTL: get the remaining time to live in seconds for a key's fields.
  • HPTTL: get the remaining time to live in milliseconds for a key's fields.

Examples

  • Store counters for the number of times bike:1 has been ridden, has crashed, or has changed owners:

Performance

Most Redis hash commands are O(1).

A few commands - such as HKEYS, HVALS, HGETALL, and most of the expiration-related commands - are O(n), where n is the number of field-value pairs.

Limits

Every hash can store up to 4,294,967,295 (2^32 - 1) field-value pairs. In practice, your hashes are limited only by the overall memory on the VMs hosting your Redis deployment.

Learn more

RATE THIS PAGE
Back to top ↑