Redis Data Types

Redis Data Types – Notes

1. Strings

  • Description: The simplest type; stores text or binary data (up to 512 MB).
  • Usage:

    • Store text
    • Store serialized JSON/XML
    • Store counters and numeric values
  • Common Commands:

    SET key value
    GET key
    INCR key
    DECR key
    APPEND key "extra"
    

2. Lists

  • Description: Ordered collection of strings, implemented as linked lists.
  • Usage:

    • Queues (FIFO)
    • Stacks (LIFO)
    • Message lists
  • Common Commands:

    LPUSH list value   # Add to head
    RPUSH list value   # Add to tail
    LPOP list          # Remove from head
    RPOP list          # Remove from tail
    LRANGE list 0 -1   # Get all elements
    

3. Sets

  • Description: Unordered collection of unique strings.
  • Usage:

    • Tags
    • Unique items
    • Membership checks
  • Common Commands:

    SADD set member
    SREM set member
    SMEMBERS set
    SISMEMBER set member
    SUNION set1 set2
    

4. Sorted Sets (ZSets)

  • Description: Like Sets, but each member has an associated score for sorting.
  • Usage:

    • Leaderboards
    • Rankings
    • Time-based events
  • Common Commands:

    ZADD zset score member
    ZRANGE zset 0 -1 WITHSCORES
    ZRANK zset member
    ZREM zset member
    

5. Hashes

  • Description: Key-value pairs inside a single Redis key (like a small document or object).
  • Usage:

    • Store user profiles
    • Store settings
    • Store structured objects
  • Common Commands:

    HSET hash field value
    HGET hash field
    HGETALL hash
    HDEL hash field
    

6. Bitmaps

  • Description: Strings interpreted as bit arrays for bit-level operations.
  • Usage:

    • Tracking daily user activity
    • Flags & binary states
  • Common Commands:

    SETBIT key offset value
    GETBIT key offset
    BITCOUNT key
    

7. HyperLogLogs

  • Description: Probabilistic data structure to estimate the count of unique items with low memory usage.
  • Usage:

    • Count unique visitors
    • Count distinct items
  • Common Commands:

    PFADD key element
    PFCOUNT key
    PFMERGE destkey key1 key2
    

8. Streams

  • Description: Append-only log of messages with IDs and fields (similar to Kafka).
  • Usage:

    • Event sourcing
    • Message queues
  • Common Commands:

    XADD mystream * field value
    XRANGE mystream - +
    XREAD COUNT 2 STREAMS mystream 0
    

Key Notes

  • Redis is schema-less → you can mix different data types in different keys.
  • Choose the right type based on access pattern and performance needs.
  • Many commands operate in O(1) or O(log n) time → very fast.


Previous Post Next Post