爬蟲之DynamoDB初識

AmazonDynamoDB被設計成用來託管的NoSQL數據庫服務、可預期的性能、可實現無縫擴展性和可靠性等核心問題

DynamoDB沒有Cassandra和MongoDB強大
MongoDB是文檔型的數據庫,可以理解爲底層存儲的是JSON,DynamoDB不支持JSON的

開發應用上MongoDB遠勝於DynamoDB
運維的角度來講,DynamoDB省去開發者部署/監控/維護數據庫環節,給開發者節約了大量時間,
強大的擴展能力又減輕了後續運維的壓力,這正是DynamoDB最大的價值所在
亞馬遜網絡服務(AWS)

創建表格:

import boto3

dynamodb = boto3.resource('dynamodb')
# 在 create_table 調用中,您需要指定表名稱、主鍵屬性及其數據類型,ProvisionedThroughput 參數是必填項
table = dynamodb.create_table(
    TableName = 'users',
    KeySchema = [
        {
                'AttributeName': 'username',
                'KeyType': 'HASH'
        },        {
                'AttributeName': 'last_name',
                'KeyType': 'RANGE'
        },

    ],
    AttributeDefinitions = [
        {
            'AttributeName': 'username',
            'AttributeType': 'S'
        },
        {
            'AttributeName': 'last_name',
            'AttributeType': 'S'
        },

    ],
    ProvisionedThroughput={
        'ReadCapacityUnits': 5,
        'WriteCapacityUnits': 5
    }
)
table.meta.client.get_waiter('table_exists').wait( TableName = 'users',)
print(table.item_count)


基本的操作:
import boto3
from boto3.dynamodb.conditions import Key, Attr

使用存在的表Table = users

dynamodb = boto3.resource(‘dynamodb’)
table = dynamodb.Table(‘users’)
print(table.creation_date_time)

創建一個新的Item

table.put_item(
Item={
‘username’: ‘janedoe’,
‘first_name’: ‘Jane’,
‘last_name’: ‘Doe’,
‘age’: 25,
‘account_type’: ‘standard_user’,
}
)

獲取一個Item

response = table.get_item(
Key={
‘username’: ‘janedoe’,
‘last_name’: ‘Doe’
}
)
item = response[‘Item’]
print(item)

更新數據

table.update_item(
Key={
‘username’: ‘janedoe’,
‘last_name’: ‘Doe’
},
UpdateExpression=‘SET age = :val1’,
ExpressionAttributeValues={
‘:val1’: 26
}
)

再獲取更新之後的信息

response = table.get_item(
Key={
‘username’: ‘janedoe’,
‘last_name’: ‘Doe’
}
)
item = response[‘Item’]
print(item)

刪除數據

table.delete_item(
Key={
‘username’: ‘janedoe’,
‘last_name’: ‘Doe’
}
)

查找數據需要導入 from boto3.dynamodb.conditions import Key, Attr

response = table.query(
KeyConditionExpression=Key(‘username’).eq(‘janedoe’)
)
items = response[‘Items’]
print(items)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章