简体   繁体   中英

How to run batch query against DynamoDB with boto3 given a list of primary keys

Given a variable length list of items in Python containing primary keys (eg itemList = ["item1","item2","item3"] ), how can I use boto3 to translate this list into the proper format for a dynamodb batch query?

I'm able to successfully run a query by manually formatting the request but my problem is how to elegantly translate a python list into this format. I've tried the serializer function in boto3 which seems to be the right direction, but I am missing some piece of the puzzle.

import boto3

dynamodb = boto3.resource('dynamodb', region_name='us-west-2')

response = dynamodb.batch_get_item(
    RequestItems={
        "dynamodb-table-name": {
            "Keys": [
                {
                    'pk': {
                        'S': 'item1'
                    },
                    'sk': {
                        'S': 'ITEM'
                    }
                },
                {
                    'pk': {
                        'S': 'item2'
                    },
                    'sk': {
                        'S': 'ITEM'
                    }
                }
            ]
        }
    }
)

If I create a serializer serializer = boto3.dynamodb.types.TypeSerializer() and use it on my list, I'm returned with {'L': [{'S': 'item1'}, {'S': 'item2'}]}

I think I have figured out my own question. The first issue is that there's a difference between boto3.resource('dynamodb') and boto3.client('dynamodb') , and .client is the one I was able to get working. For the other piece, while serialize might still be a viable option to explore, what I did was this:

itemList = []
for item in items:
    itemList.append({'pk':{'S':item},'sk': {'S':'ITEM'}})

response = client.batch_get_item(
    RequestItems={
        "dynamodb-table-name": {
            "Keys": itemList
        }
    }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM