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

时间:2018-12-26 17:33:17

标签: python-3.x amazon-dynamodb boto3

我在DynamoDB中有一个带有分区键和排序键的表。我想检索具有给定分区键的所有项目,而与排序键无关。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

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

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))

注意:我最初为这个here找到了一个有用的答案。信用归功!

相关问题