簡體   English   中英

python如何查詢AWS DynamoDB?

[英]How do I query AWS DynamoDB in python?

我對 NoSQL 和使用 AWS DynamoDB 還很陌生。 我正在使用 python 從 AWS Lambda 調用它 2.7 我正在嘗試從order_number字段中檢索一個值。
這是我的表的樣子(只有一條記錄。):
在此處輸入圖像描述

主分區鍵:subscription_id 在此處輸入圖像描述


和我的二級全球索引:order_number
在此處輸入圖像描述

我的設置正確嗎? 如果給出 order_number,我如何使用 python 檢索記錄?
我無法弄清楚執行此操作的語法。

我試過了

response = table.get_item( Key = {'order_number': myordernumber} )

但我得到:
An error occurred (ValidationException) when calling the GetItem operation: The provided key element does not match the schema: ClientError

DynamoDB 不會自動索引對象的所有字段。 默認情況下,您可以定義一個散列鍵(在您的情況下為subscription_id ),並且可以選擇定義一個范圍鍵,這些鍵將被編入索引。 所以,你可以這樣做:

response = table.get_item(Key={'subscription_id': mysubid})

它會按預期工作。 但是,如果您想根據order_number檢索項目,則必須使用scan操作來查看表中的所有項目以找到具有正確值的項目。 這是一項非常昂貴的操作。 或者您可以在您的表中創建一個使用order_number作為主鍵的全局二級索引。 如果你這樣做並調用了新的索引order_number-index你就可以查詢匹配特定訂單號的對象,如下所示:

from boto3.dynamodb.conditions import Key, Attr

response = table.query(
    IndexName='order_number-index',
    KeyConditionExpression=Key('order_number').eq(myordernumber))

DynamoDB 是一個非常快速、可擴展且高效的數據庫,但它確實需要仔細考慮您可能想要搜索哪些字段以及如何有效地進行搜索。

好消息是現在您可以將 GSI 添加到現有表中。 以前,您必須刪除表並重新開始。

確保你已經導入了這個:

from boto3.dynamodb.conditions import Key, Attr

如果你沒有它,你肯定會得到錯誤。 它在文檔示例中

感謝@altoids 的上述評論,因為這對我來說是正確的答案。 我想用一個“正式”的答案來引起人們的注意。

要使用帶過濾器的索引查詢 dynamodb:

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb', region_name=region)
table = dynamodb.Table('<TableName>')

response = table.query(
    IndexName='<Index>',
    KeyConditionExpression=Key('<key1>').eq('<value>') & Key('<key2>').eq('<value>'),
    FilterExpression=Attr('<attr>').eq('<value>')
)

print(response['Items'])

如果不需要過濾器,則不要在查詢中使用FilterExpression

import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource('dynamodb', region_name=region_name)
table = dynamodb.Table(tableName)

def queryDynamo(pk, sk):
    response = table.query(
        ProjectionExpression="#pk, #sk, keyA, keyB",
        ExpressionAttributeNames={"#pk": "pk", "#sk": "sk"},
        KeyConditionExpression=
            Key('pk').eq(pk) & Key('sk').eq(sk)
    )
    return response['Items']

如果您使用 boto3 dynamodb客戶端,您可以執行以下操作(同樣您需要使用 subscription_id,因為它是主鍵):

dynamodb = boto3.client('dynamodb')
response = dynamodb.query(
    TableName='recurring_charges', 
    KeyConditionExpression="subscription_id = :subscription_id",
    ExpressionAttributeValues={":subscription_id": {"S": "id"}}
)

到目前為止,這是我發現的最干凈的方法; query格式為JSON

dynamodb_client = boto3.client('dynamodb')

def query_items():
    arguments = {
        "TableName": "your_dynamodb_table",
        "KeyConditions": {
            "att_1": {"ComparisonOperator": "EQ", "AttributeValueList": [{"S": "value"}]},
        },
        "QueryFilter": {
            "att_2": {"ComparisonOperator": "NULL"},
        },
    }
    return dynamodb_client.query(**arguments)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM