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.

Examples

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

Field expiration

New in Redis Community Edition 7.4 is the ability to specify an expiration time or a time-to-live (TTL) value for individual hash fields. This capability is comparable to key expiration and includes a number of similar commands.

Use the following commands to set either an exact expiration time or a TTL value for specific fields:

  • HEXPIRE: set the remaining TTL in seconds.
  • HPEXPIRE: set the remaining TTL in milliseconds.
  • HEXPIREAT: set the expiration time to a timestamp1 specified in seconds.
  • HPEXPIREAT: set the expiration time to a timestamp specified in milliseconds.

Use the following commands to retrieve either the exact time when or the remaining TTL until specific fields will expire:

  • HEXPIRETIME: get the expiration time as a timestamp in seconds.
  • HPEXPIRETIME: get the expiration time as a timestamp in milliseconds.
  • HTTL: get the remaining TTL in seconds.
  • HPTTL: get the remaining TTL in milliseconds.

Use the following command to remove the expiration of specific fields:

Common field expiration use cases

  1. Event Tracking: Use a hash key to store events from the last hour. Set each event's TTL to one hour. Use HLEN to count events from the past hour.

  2. Fraud Detection: Create a hash with hourly counters for events. Set each field's TTL to 48 hours. Query the hash to get the number of events per hour for the last 48 hours.

  3. Customer Session Management: Store customer data in hash keys. Create a new hash key for each session and add a session field to the customer’s hash key. Expire both the session key and the session field in the customer’s hash key automatically when the session expires.

  4. Active Session Tracking: Store all active sessions in a hash key. Set each session's TTL to expire automatically after inactivity. Use HLEN to count active sessions.

Field expiration examples

Support for hash field expiration in the official client libraries is not yet available, but you can test hash field expiration now with beta versions of the Python (redis-py) and Java (Jedis) client libraries.

Following are some Python examples that demonstrate how to use field expiration.

Consider a hash data set for storing sensor data that has the following structure:

event = {
    'air_quality': 256,
    'Battery_level':89
}

client.hset('sensor:sensor1', mapping=event)

Set and retrieve the TTL for multiple fields in a hash:

# set the TTL for two hash fields to 60 seconds
client.hexpire('sensor:sensor1', 60, 'air_quality', 'battery_level')
ttl = client.httl('sensor:sensor1', 'air_quality', 'battery_level')
print(ttl)
# prints [60]

Set and retrieve a hash field's TTL in milliseconds:

# set the TTL of the 'air_quality' field in milliseconds
client.hpexpire('sensor:sensor1', 60000, 'air_quality')
# and retrieve it
pttl = client.hpttl('sensor:sensor1', 'air_quality')
print(pttl)
# prints [60000]

Set and retrieve a hash field’s expiration timestamp:

# set the expiration of 'air_quality' to now + 24 hours
# (similar to setting the TTL to 24 hours)
client.hexpireat('sensor:sensor1', 
    datetime.now() + timedelta(hours=24), 
    'air_quality')
# and retrieve it
expire_time = client.hexpiretime('sensor:sensor1', 'air_quality')
print(expire_time)
# prints [1717668041]

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


  1. all timestamps are specified in seconds or milliseconds since the Unix epoch↩︎

RATE THIS PAGE
Back to top ↑