Skip to main content

What is Hash in Redis?

Hash in Redis is a "key → value" structure inside a single Redis key. Essentially, it's a mini-object or a dictionary, where several field:value pairs can be stored under one Redis key.

Main properties

  • It's an associative array (a map, a dictionary).
  • Every element is a field:value pair.
  • It fits storing objects, user profiles, settings.
  • Values are strings (Redis String).

Example

bash
HSET user:1 name "Anna" age "27" city "Moscow" HGETALL user:1

Result:

javascript
1) "name" 2) "Anna" 3) "age" 4) "27" 5) "city" 6) "Moscow"

The user:1 key holds three fields: name, age, city.

Main commands

CommandDescription
HSET key field value [field value ...]set one or several fields
HGET key fieldget a field's value
HGETALL keyget every field and value
HDEL key field [field ...]remove a field
HEXISTS key fieldcheck whether a field exists
HKEYS keyget the list of every field
HVALS keyget the list of every value
HLEN keythe number of fields
HINCRBY key field incrementincrement a field's numeric value
HSETNX key field valueset a field only if it doesn't already exist

An update-and-count example

bash
HSET user:2 name "Ivan" points "100" HINCRBY user:2 points 50 HGET user:2 points

Result:

javascript
"150"

Internal structure

Redis stores a Hash in two formats:

  1. Ziplist, if there are few fields (up to ~512) and they're short; it saves memory.
  2. Hashtable, if there's a lot of data or the fields are long; it provides fast access.

Redis automatically picks the format based on size.

Uses

  • Storing user data, a profile, a session.
  • Caching objects from a database.
  • Counters and state inside microservices.
  • Fast access to individual fields without loading the whole object.

An example used as a cache

bash
HSET product:42 name "Phone" price "899" stock "24" HGET product:42 price

Result:

javascript
"899"

This is how a hash can represent a row of SQL data inside Redis's memory.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.