如何使用多个字段的哈希值创建DynamoDB全局二级索引?

时间:2020-10-22 15:13:51

标签: amazon-dynamodb amazon-dynamodb-index

在我看来,“散列”一词表示,有可能对DynamoDB中由多个字段组成的散列。但是,我发现的每篇文章都显示仅由单个值组成的“哈希”……这对我来说没有任何意义。

我的表包含以下字段:

  • uid(PK)
  • 提供者
  • 标识符
  • 来自
  • 已收到日期
  • date_processed

目标是根据我的应用检索数据的方式来拥有多个索引(当然不是通过PK)。组合是:

  1. 通过提供者的消息标识符:
    所需的哈希:提供者+标识符

  2. 通过对话消息标识符:
    所需的哈希值:从+到

  3. 到收到日期为止,是否得到处理
    所需的哈希:_ac

  4. 到收到日期为止,是否得到处理
    所需的哈希:帐户

这是我尝试过但未成功的示例之一 ...

  MessagesTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: messages
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        - AttributeName: uid
          AttributeType: S
        - AttributeName: account
          AttributeType: S
        - AttributeName: provider
          AttributeType: S
        - AttributeName: identifier
          AttributeType: S
        - AttributeName: from
          AttributeType: N
        - AttributeName: to
          AttributeType: N
        - AttributeName: _ac
          AttributeType: N
        - AttributeName: _ap
          AttributeType: N
      KeySchema:
        - AttributeName: uid
          KeyType: HASH
      GlobalSecondaryIndexes:
        - IndexName: idxConversation
          KeySchema:
            - AttributeName: from:to
              KeyType: HASH
            - AttributeName: _ac
              KeyType: RANGE
          Projection:
            ProjectionType: KEYS_ONLY
        - IndexName: idxProviderMessage
            KeySchema:
              - AttributeName: provider:identifier
                KeyType: HASH
              - AttributeName: _ac
                KeyType: RANGE
            Projection:
              ProjectionType: KEYS_ONLY

1 个答案:

答案 0 :(得分:2)

那不是DDB的工作方式...

使用

from: "sender@myco.com"
to: "recevier@otherco.com"

您想要在记录中包含另一个属性

gsiHash: "sender@my.com#recevier@otherco.com"

这是您指定为GSI哈希键的属性。

请注意,要通过此GSI访问数据,您需要既了解又了解。

根据您的情况,您可能想从DDB文档的Overloading Global Secondary Indexes页中获取提示

您无需将多个记录写入表中

s: id, keytype: hash  
s: data, keytype: sort  
s: gsi-sk  

记录看起来像

id:"<uid>",data:"PRIMARY", gsi-sk:"<?>" //"primary" record  
id:"<uid>",data:"FROM", gsi-sk:"sender@myco.com"
id:"<uid>",data:"TO", gsi-sk:"receiever@otherco.com"
id:"<uid>",data:"FROMTO", gsi-sk:"sender@myco.com#receiever@otherco.com"
id:"<uid>",data:"PROVIDER", gsi-sk:"whateverid"
<ect>

现在,您以data作为哈希键,以gsi-sk作为排序键来创建GSI。

扩展我的评论
或者,您可以扩展您在“数据”中添加的内容

id:"<uid>",data:"PRIMARY", gsi-sk:"<?>" //"primary" record  
id:"<uid>",data:"FROM#sender@myco.com", gsi-sk:"TO#receiever@otherco.com"
id:"<uid>",data:"TO#receiever@otherco.com", gsi-sk:"FROM#sender@myco.com"
id:"<uid>",data:"PROVIDER#<whateverid>", gsi-sk:"IDENTIFIER#<someid>"
<ect>

您保留在主记录中的数据量取决于您的访问要求。您是否希望能够使用GetItem(hk=<uid>, sk="PRIMIARY")来获取所有内容,还是可以接受Query(hk=<uid>)

相关问题