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() 方法int 或 float,将以 str 存储检索键值对
# 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
# 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 入门