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

How to create a DynamoDB Global Secondary Index with a hash of multiple fields?

对我来说,“散列”这个词传达的意思是 散列 可以由 DynamoDB 中的多个字段组成。但是,我找到的每篇文章都显示仅包含一个值的“哈希”...这对我来说没有任何意义。

我的 table 由以下字段组成:

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

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

  2. 通过对话消息标识符:
    所需哈希值:from + to

  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

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

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

您希望记录中有另一个属性

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

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

请注意,要通过此 GSI 访问数据,您需要知道起点和终点。

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

不是写入单个记录,而是将多个记录写入 table

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>

现在您创建一个 GSI,其中 data 作为散列键,gsi-sk 作为排序键。

扩展我的评论
或者,您可以扩展放入“数据”的内容

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>) 接受table