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 server แล้ว:
.set()int หรือ float โดยจะเก็บเป็น stringดึงข้อมูล key-value
# Store a key-value pair
r.set("username", "JDoe")
# Retrive the key-value pair
username = r.get("username")
# Print the result
print(username)
JDoe
เขียนทับคู่ key-value
r.set("username", "BSmith")
username = r.get("username")
print(username)
BSmith
เข้าถึง key ที่ไม่มีอยู่
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")
รองรับข้อมูลที่ซับซ้อนขึ้น เช่น dictionary:
.hset() รับ key และ dict.hgetall()$$
{
'item_id': '1003',
'quantity': '2',
'price': '79.99'
}
NoSQL เบื้องต้น