如何在 DynamoDB 中将排序键设置为全局二级索引(另一个分区键)..?

How to set Sort key as Global secondary index (Another Partition key) in DynamoDB..?

我将 DynamoDB table 与以下字段一起使用:

主分区键 => user_id

主排序键 => conversation_id

样本table数据

+--------+------------------+ | user_id | conversation_id | +--------+--------------------+ | 10 |啊啊| | 10 | bbbb | | 10 | cccc |<br> | 11 |啊啊| | 11 | bbbb | | 11 | CCCC | +--------+--------------------+

我在 dynamodb 中有两个单独的查询:

  1. 通过特定 user_id 获取所有 conversation_id
    如果输入 10 => 输出 => aaaa, bbbb, cccc
  2. 如何从特定的 conversation_id 中获取所有 user_id如果输入 aaaa => 输出 => 10,11

我可以得到第一个查询的结果,但是如何获取第二个查询结果。?

使用主排序键(conversation_id)或

获取数据是一个好习惯吗

如何分配或创建 conversation_id 作为 全局二级索引(另一个分区键)..?

注意:我正在使用PHP(Codeigniter 框架)

1) 您需要使用query来获取分区键的所有排序键。请参考以下link.

Query API

Query sample code

2) 使用 AWS CLI 命令创建 GSI。

本地 DynamoDB:-

您可能需要删除端点 url 并包括适当的区域 --region us-east-1。另外,请相应地更改 table 名称。

aws dynamodb update-table --table-name Movies --attribute-definitions file://create_gsi_attributes.json --global-secondary-index-updates file://create_gsi.json --endpoint-url http://localhost:8000

create_gsi_attributes.json:-

请将属性名称(和类型)更改为 conversation_iduser_id

[{
    "AttributeName": "title",
    "AttributeType": "S"
},
{
    "AttributeName": "yearkey",
    "AttributeType": "N"
}]

create_gsi.json:-

请将关键架构属性名称更改为 conversation_iduser_id

[{
    "Create": {
        "IndexName": "Movies_Gsi",
        "KeySchema": [{
            "AttributeName": "title",
            "KeyType": "HASH"
        },
        {
            "AttributeName": "yearkey",
            "KeyType": "RANGE"
        }],
        "Projection": {
            "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 100,
            "WriteCapacityUnits": 100
        }
    }
}]

编辑:-

命令:-

aws dynamodb update-table --table-name message_participants_tbl --attribute-definitions file://create_gsi_attributes_conversation.json --global-secondary-index-updates file://create_gsi_conversation.json --endpoint-url http://localhost:8000

create_gsi_conversation.json:-

[{
    "Create": {
        "IndexName": "message_participants_tbl_gsi",
        "KeySchema": [{
            "AttributeName": "conversation_id",
            "KeyType": "HASH"
        },
        {
            "AttributeName": "user_id",
            "KeyType": "RANGE"
        }],
        "Projection": {
            "ProjectionType": "ALL"
        },
        "ProvisionedThroughput": {
            "ReadCapacityUnits": 100,
            "WriteCapacityUnits": 100
        }
    }
}]

create_gsi_attributes_conversation.json:-

[{
    "AttributeName": "user_id",
    "AttributeType": "S"
},
{
    "AttributeName": "conversation_id",
    "AttributeType": "S"
}]