使用 boto3 在 Dynamo 中按分区键查询所有项目

Mat*_*gan 4 python-3.x amazon-dynamodb boto3

我在 DynamoDB 中有一个表,其中包含分区键和排序键。我想检索具有给定分区键的所有项目,而不考虑排序键。

我该怎么做呢?

Mat*_*gan 5

以下方法既适用于仅具有分区键的表,也适用于具有分区和排序键的表:

from boto3 import resource
from boto3.dynamodb.conditions import Key


dynamodb_resource = resource('dynamodb')

def query_table(table_name, key=None, value=None):
    table = dynamodb_resource.Table(table_name)

    if key is not None and value is not None:
        filtering_exp = Key(key).eq(value)
        return table.query(KeyConditionExpression=filtering_exp)

    raise ValueError('Parameters missing or invalid')

if __name__ == '__main__':
    resp = query_table(
        table_name='my-table', 
        key='key-name', 
        value='match-me'
    )
    items = resp.get('Items')
    print(len(items))
Run Code Online (Sandbox Code Playgroud)

注意:我最初在这里找到了一个有用的答案。信用到期的信用!(链接于 8 月 21 日更新)