儲存與讀取鍵值資料

NoSQL 入門

Jake Roach

Data Engineer

儲存鍵值資料

# 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")

連上 Redis 伺服器後:

  • 將鍵和值傳入 .set() 方法
  • 可傳入原生 intfloat,會以 str 儲存
  • 可覆寫已存在的鍵值對
NoSQL 入門

讀取鍵值資料

讀取鍵值對

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

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

# Print the result
print(username)
JDoe

覆寫鍵值對

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

嘗試存取不存在的鍵

favorite_color = r.get("favorite_color")
print(favorite_color)
None
NoSQL 入門

儲存複雜的鍵值資料

# 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")

可儲存更複雜的型別,如 dict(字典):

  • 使用 .hset(),傳入鍵與 dict
  • 傳入鍵給 .hgetall()

$$

{
    'item_id': '1003',
    'quantity': '2',
    'price': '79.99'
}
NoSQL 入門

一起來練習吧!

NoSQL 入門

Preparing Video For Download...