キーと値のデータを保存・取得する

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...