如何在给定主分区键值列表的情况下一次批量调用多个项目

问题描述 投票:4回答:1

所以,我有一个带有主分区键列的dynamodb表,foo_id,没有主要的排序键。我有一个foo_id值列表,并希望获得与此ID列表相关的观察结果。

我认为最好的方法(?)是使用batch_get_item(),但它不适合我。

    # python code
    import boto3
    client = boto3.client('dynamodb')

    # ppk_values = list of `foo_id` values (strings) (< 100 in this example)
    x = client.batch_get_item(
        RequestItems={
            'my_table_name':
                {'Keys': [{'foo_id': {'SS': [id for id in ppk_values]}}]}
        })

我正在使用SS,因为我传递了一个字符串列表(foo_id值的列表),但我得到了:

ClientError: An error occurred (ValidationException) when calling the
BatchGetItem operation: The provided key element does not match the
schema

所以我认为这意味着它认为foo_id包含列表值而不是字符串值,这是错误的。

- >那个解释对吗?批量查询一堆主分区键值的最佳方法是什么?

python amazon-dynamodb boto boto3
1个回答
6
投票

密钥应如下所述给出。它不能被称为'SS'。

基本上,您可以将DynamoDB String数据类型与String(即不与SS)进行比较。每个项目都单独处理。它与查询中的SQL不相似。

'Keys': [
            {
                'foo_id': key1
            },
            {
                'foo_id': key2
            }
], 

示例代码: -

您可能需要更改表名称和键值。

from __future__ import print_function # Python 2/3 compatibility
import boto3
import json
import decimal
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource("dynamodb", region_name='us-west-2', endpoint_url="http://localhost:8000")

email1 = "[email protected]"
email2 = "[email protected]"

try:
    response = dynamodb.batch_get_item(
        RequestItems={
            'users': {
                'Keys': [
                    {
                        'email': email1
                    },
                    {
                        'email': email2
                    },
                ],            
                'ConsistentRead': True            
            }
        },
        ReturnConsumedCapacity='TOTAL'
    )
except ClientError as e:
    print(e.response['Error']['Message'])
else:
    item = response['Responses']
    print("BatchGetItem succeeded:")
    print(json.dumps(item, indent=4, cls=DecimalEncoder))
© www.soinside.com 2019 - 2024. All rights reserved.