首页 > 解决方案 > DynamoDB 查找日期之后的所有项目

问题描述

我有一个 DynamoDB 表,其中存储了链接数据(urldatecategorytags)。

我需要能够——

基于上述,我将架构设置url为主哈希键和二级索引date,如下所示 -

AWSTemplateFormatVersion: '2010-09-09'
Parameters:
  TableName:
    Type: String
    Default: "my_links"
  HashAttr:
    Type: String
    Default: url
  IndexAttr:
    Type: String
    Default: date
  ReadCapacity:
    Type: Number
    Default: 5
  WriteCapacity:
    Type: Number
    Default: 5
Resources:
  Table:
    Properties:
      KeySchema:
        - AttributeName: !Ref HashAttr
          KeyType: HASH
      AttributeDefinitions:
        - AttributeName: !Ref HashAttr
          AttributeType: S
        - AttributeName: !Ref IndexAttr
          AttributeType: S
      GlobalSecondaryIndexes:
        - IndexName: !Ref IndexAttr
          KeySchema:
            - AttributeName: !Ref IndexAttr
              KeyType: HASH
          Projection:
            ProjectionType: ALL
          ProvisionedThroughput:
            ReadCapacityUnits: !Ref ReadCapacity
            WriteCapacityUnits: !Ref WriteCapacity
      ProvisionedThroughput:
        ReadCapacityUnits: !Ref ReadCapacity
        WriteCapacityUnits: !Ref WriteCapacity
      TableName: !Ref TableName
    Type: AWS::DynamoDB::Table

date我可以按如下方式查询表格,但只能使用eq条件 -

ddb=boto3.resource("dynamodb")
table=ddb.Table("my_links")
from boto3.dynamodb.conditions import Key
queryexp=Key('date').eq("2020-02-19")
for item in table.query(IndexName="date",
                        KeyConditionExpression=queryexp)["Items"]:
    print (item)    

如果我使用 agte代替eq条件,我会得到以下结果 -

botocore.exceptions.ClientError: An error occurred (ValidationException) when calling the Query operation: Query key condition not supported

但是,我可以使用扫描和gte条件查询表 -

filterexp=Key('date').gte("2020-02-19")
for item in table.scan(FilterExpression=filterexp)["Items"]:
    print (item)

但是我猜我不再需要二级索引,而且随着表变大,这将变得非常昂贵:-/

因此,如果可能的话,我宁愿坚持使用二级索引和查询(我在想这个吗?),但是我需要对架构做些什么才能在日期之后获取所有项目?

标签: amazon-dynamodb

解决方案


您不能使用 GTE。查询支持 EQ | 乐 | LT | 通用电气 | 燃气轮机 | BEGINS_WITH | 之间

检查这篇文章https://medium.com/cloud-native-the-gathering/querying-dynamodb-by-date-range-899b751a6ef2


推荐阅读