Storing and retrieving key-value data

Introduction to NoSQL

Jake Roach

Data Engineer

Storing key-value data

# Import redis, make a connection
r = redis.Redis(...)

# Store a key-value pair
r.set("username", "JDoe")
# Store another key-value pair
r.set("age", 27)
# Overwrite an existing key
r.set("username", "BSmith")

After making a connection to the Redis server:

  • Pass a key and value to the .set() method
  • Can pass native int or float types, will be stored as strings
  • Can overwrite existing key-value pairs
Introduction to NoSQL

Retrieving key-value data

Retrieve a key-value pair

# Store a key-value pair
r.set("username", "JDoe")

# Retrive the key-value pair
username = r.get("username")

# Print the result
print(username)
JDoe

Overwrite a key-value pair

r.set("username", "BSmith")
username = r.get("username")
print(username)
BSmith

Attempt to access a key that does not exist

favorite_color = r.get("favorite_color")
print(favorite_color)
None
Introduction to NoSQL

Storing complex key-value data

# Store a dictionary using .hset()
r.hset(
    "shopping_cart", 
    mapping={
        "item_id": "1003",
        "quantity": 2,
        "price": 79.99
    }
)
# Retrieve the dictionary
r.hgetall("shopping_cart")

Can store more complex data types, like dictionaries:

  • .hset(), takes key and a dict
  • Pass a key to .hgetall()

$$

{
    'item_id': '1003',
    'quantity': '2',
    'price': '79.99'
}
Introduction to NoSQL

Let's practice!

Introduction to NoSQL

Preparing Video For Download...