EBOOK – REDIS IN ACTION

This book covers the use of Redis, an in-memory database/data structure server.

  • Foreword
  • Preface
  • Acknowledgments
  • About this Book
  • About the Cover Illustration
  • Part 1: Getting Started
  • Part 2: Core concepts
  • Part 3: Next steps
  • Appendix A
  • Appendix B
  • Buy the paperback

    1.2.4 Hashes in Redis

    Figure 1.4 An example of a HASH with two keys/values under the key hash-key

    Whereas LISTs and SETs in Redis hold sequences of items, Redis HASHes store a mapping of keys to values. The values that can be stored in HASHes are the same as what can be stored as normal STRINGs: strings themselves, or if a value can be interpreted as a number, that value can be incremented or decremented. Figure 1.4 shows a diagram of a hash with two values.

    In a lot of ways, we can think of HASHes in Redis as miniature versions of Redis itself. Some of the same commands that we can perform on STRINGs, we can perform on the values inside HASHes with slightly different commands. Try to follow listing 1.4 to see some commands that we can use to insert, fetch, and remove items from HASHes. Table 1.6 describes the commands.

    Table 1.6Commands used on HASH values

    Command

    What it does

    HSET

    Stores the value at the key in the hash

    HGET

    Fetches the value at the given hash key

    HGETALL

    Fetches the entire hash

    HDEL

    Removes a key from the hash, if it exists

    Listing 1.4
    The HSET, HGET, HGETALL, and HDEL commands in Redis
    redis 127.0.0.1:6379> hset hash-key sub-key1 value1
    (integer) 1
    redis 127.0.0.1:6379> hset hash-key sub-key2 value2
    (integer) 1
    redis 127.0.0.1:6379> hset hash-key sub-key1 value1
    (integer) 0
    

    When we add items to a hash, again we get a return value that tells whether the item is new in the hash.

    redis 127.0.0.1:6379> hgetall hash-key
    1) "sub-key1"
    2) "value1"
    3) "sub-key2"
    4) "value2"
    

    We can fetch all of the items in the HASH, which gets translated into a dictionary on the Python side of things.

    redis 127.0.0.1:6379> hdel hash-key sub-key2
    (integer) 1
    redis 127.0.0.1:6379> hdel hash-key sub-key2
    (integer) 0
    

    When we delete items from the hash, the command returns whether the item was there before we tried to remove it.

    redis 127.0.0.1:6379> hget hash-key sub-key1
    "value1"
    

    We can also fetch individual fields from hashes.

    redis 127.0.0.1:6379> hgetall hash-key
    1) "sub-key1"
    2) "value1"
    


    For those who are familiar with document stores or relational databases, we can consider a Redis HASH as being similar to a document in a document store, or a row in a relational database, in that we can access or change individual or multiple fields at a time. We’re now one structure from having seen all of the structures available in Redis. Keep reading to learn what ZSETs are and a few things that we can do with them.