是否有 Python API 用于向 AWS DynamoDB 提交批量获取请求?

Is there a Python API for submitting batch get requests to AWS DynamoDB?

boto3 - Amazon 的官方 AWS API 包装器 python - 非常支持将项目批量上传到 DynamoDB。它看起来像这样:

db = boto3.resource("dynamodb", region_name = "my_region").Table("my_table")

with db.batch_writer() as batch:
    for item in my_items:
        batch.put_item(Item = item)

这里 my_items 是 Python 字典的列表,每个字典都必须有 table 的主键。这种情况并不完美——例如,没有安全机制来防止你超过吞吐量限制——但它仍然很好。

但是,似乎没有任何对应的数据库读取。我能找到的最接近的是 DynamoDB.Client.batch_get_item(),但这里的 API 非常复杂。下面是请求两个项目的样子:

db_client = boto3.client("dynamodb", "my_region")

db_client.batch_get_item(
    RequestItems = {
        "my_table": {
            "Keys": [
                {"my_primary_key": {"S": "my_key1"}},
                {"my_primary_key": {"S": "my_key2"}}
            ]
        }
    }
)

这可能是可以容忍的,但是响应有同样的问题:所有值都是字典,其键是数据类型("S" for string,"N" for number,"M" for映射等)而且必须解析所有内容有点烦人。所以我的问题是:

Is there any native boto3 support for batch reading from DynamoDb, similar to the batch_writer function above?

否则,

Does boto3 provide any built-in way to automatically deserialize the responses to the DynamoDB.Client.batch_get_item() function?

我还要补充一点,函数 boto3.resource("dynamodb").Table().get_item() 具有我认为的 "correct" API,因为输入或输出不需要类型解析。所以这似乎是开发人员的某种疏忽,我想我正在寻找解决方法。

所以值得庆幸的是,有些东西你可能会觉得有用 - 就像 json 模块有 json.dumpsjson.loads,boto3 有一个类型模块,包括序列化器和反序列化器.参见 TypeSerializer/TypeDeserializer。如果您查看源代码,serialization/deserialization 是递归的,应该非常适合您的用例。

注意:建议您使用 Binary/Decimal 而不是仅使用常规的旧 python float/int 进行往返转换。

serializer = TypeSerializer()
serializer.serialize('awesome') # returns {'S' : 'awesome' }

deser = TypeDeserializer()
deser.deserialize({'S' : 'awesome'}) # returns u'awesome'

希望这对您有所帮助!

有服务资源等级batch_get_item。也许你可以做类似的事情:

def batch_query_wrapper(table, key, values):

    results = []

    response = dynamo.batch_get_item(RequestItems={table: {'Keys': [{key: val} for val in values]}})
    results.extend(response['Responses'][table])

    while response['UnprocessedKeys']:

        # Implement some kind of exponential back off here
        response = dynamo.batch_get_item(RequestItems={table: {'Keys': [{key: val} for val in values]}})
        results.extend(response['Response'][table])

    return results

它将 return 您的结果作为 python 个对象。

我发现这是将 Boto 3 DynamoDB 项目转换为 Python 字典的有效方法。

https://github.com/Alonreznik/dynamodb-json

有点相关的答案,文档做广告the query method;他们的例子:

from boto3.dynamodb.conditions import Key, Attr

response = table.query(
    KeyConditionExpression=Key('username').eq('johndoe')
)
items = response['Items']
print(items)