首页 > 解决方案 > 如何排除 DynamoDB GSI 中的项目

问题描述

所以我正在阅读有关稀疏索引的信息,它根据是否存在的属性排除项目。我正在尝试在我的 cloudformation 脚本中执行此操作,其属性为:isTenant. 如果该属性存在,我希望该项目出现在我的 GSI 中,如果该属性不存在,我不希望它出现,这是我的表:

FooBar:
  Type: "AWS::DynamoDB::Table"
  Properties:
    BillingMode: PAY_PER_REQUEST
    TableName: FooBarTable

    AttributeDefinitions:
      -
        AttributeName: "pk"
        AttributeType: "S"
      -
        AttributeName: "sort"
        AttributeType: "S"
      -
        AttributeName: "runningFiles"
        AttributeType: "N"


    KeySchema:
      -
        AttributeName: "pk"
        KeyType: "HASH"
      -
        AttributeName: "sort"
        KeyType: "RANGE"

    LocalSecondaryIndexes:
      -
        IndexName: RunningJobsPerTenant
        Projection:
          ProjectionType:
            INCLUDE
          NonKeyAttributes:
            - "isTenant"
        KeySchema:
          -
            AttributeName: "pk"
            KeyType: "HASH"
          -
            AttributeName: "runningFiles"
            KeyType: "RANGE"


我究竟做错了什么?

标签: amazon-dynamodb

解决方案


对于表中的任何项目,仅当项目中存在索引排序键值时,DynamoDB 才会写入相应的索引条目。如果排序键没有出现在每个表项中,则称该索引是稀疏的。

基于来自 AWS DynamoDB 文档的上述声明:https ://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-indexes-general-sparse-indexes.html

您需要isTenant属性作为排序键,因此仅在存在此属性时才填充索引。

您现在可能面临的问题是如何处理您的runningFiles属性(以防您需要它来查询索引)。我的建议是重载另一个属性,例如:

  • 创建一个新的重载属性,由pk#runningFiles
  • isTenant创建一个新属性,该属性仅在为真时才存在。例如,runningFilesIfTenant因此您使用它作为排序键创建索引并获得相同的结果。

推荐阅读