存储与检索键值数据

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 入门

Let's practice!

NoSQL 入门

Preparing Video For Download...