Lưu và truy xuất dữ liệu key-value

Giới thiệu về NoSQL

Jake Roach

Data Engineer

Lưu dữ liệu key-value

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

Sau khi kết nối tới máy chủ Redis:

  • Truyền key và value vào .set()
  • Có thể truyền int hoặc float gốc, sẽ lưu thành str
  • Có thể ghi đè cặp key-value hiện có
Giới thiệu về NoSQL

Truy xuất dữ liệu key-value

Truy xuất một cặp 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

Ghi đè một cặp key-value

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

Thử truy cập một key không tồn tại

favorite_color = r.get("favorite_color")
print(favorite_color)
None
Giới thiệu về NoSQL

Lưu dữ liệu key-value phức tạp

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

Có thể lưu kiểu dữ liệu phức tạp hơn, như dict:

  • .hset(): truyền key và một dict
  • Truyền key vào .hgetall()

$$

{
    'item_id': '1003',
    'quantity': '2',
    'price': '79.99'
}
Giới thiệu về NoSQL

Ayo berlatih!

Giới thiệu về NoSQL

Preparing Video For Download...