DynamoDB - 通过多个键获取项目

DynamoDB - fetching items by multiple keys

最近开始使用 DynamoDB,但我在通过多个键获取数据时遇到问题。

我正在尝试从 table 中获取多个项目。

我的 table 架构定义如下:

{
  "AttributeDefinitions": [
    {
      "AttributeName": "id",
      "AttributeType": "S"
    },
    {
      "AttributeName": "date",
      "AttributeType": "S"
    }
  ],
  "KeySchema": [
    {
      "AttributeName": "id",
      "KeyType": "HASH"
    },
    {
      "AttributeName": "date",
      "KeyType": "RANGE"
    }
  ],
  ...
}

我有一个 ID 过滤列表和每个 ID 的日期范围:

[
    { "id": "abc", "start_date": "24/03/2020", "end_date": "26/03/2020" },
    { "id": "def", "start_date": "10/04/2020", "end_date": "20/04/2020" },
    { "id": "ghi", "start_date": "11/04/2020", "end_date": "11/04/2020" }
]

我需要获取所有匹配过滤列表的项目。

问题是我不能使用 Query,因为 KeyConditionExpression 只接受一个分区键(我需要将它匹配到整个过滤器列表)

The condition must perform an equality test on a single partition key value.

我不能使用 BatchGetItem,因为它需要确切的键(而且我的排序键需要一个日期范围 Key('date').between(start_date, end_date)

Keys - An array of primary key attribute values that define specific items in the table. For each primary key, you must provide all of the key attributes. For example, with a simple primary key, you only need to provide the partition key value. For a composite key, you must provide both the partition key value and the sort key value.

我有点迷路了... 有没有办法通过范围查询(通过单个请求 - 而不是来自循环的多个请求)通过多个键获取?

您会建议任何 table 更改吗?

您可以使用table.scan获取多条记录。请参阅文档 here

这是一个示例代码:

import boto3

# Get the service resource.
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('tablename')

response = table.scan(
FilterExpression=Attr('first_name').begins_with('J') & Attr('account_type').eq('super_user')
)
items = response['Items']
print(items)

您需要针对每个唯一 id 进行一次查询。这些查询中的每一个都应包含一个键条件表达式,该表达式在 id 分区键上具有相等性,在 date 排序键上具有值范围,如下所示:

#id = :id AND #date BETWEEN :startdate AND :enddate

不要为此使用 scan。随着您的 table 增长,性能会下降。