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

Aru*_*ven 6 database-design primary-key amazon-dynamodb

我使用了带有以下字段的 DynamoDB 表:

主分区键=>user_id

主要排序键=>conversation_id

示例表数据

+---------+--------------------+ | user_id | conversation_id | +---------+--------------------+ | 10 | aaaa | | 10 | bbbb | | 10 | cccc |
| 11 | aaaa | | 11 | bbbb | | 11 | cccc | +---------+--------------------+

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

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

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

使用主排序键( conversation_id) 或

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

注意:我使用的是 PHP(Codeigniter 框架)

not*_*est 1

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

查询接口

查询示例代码

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

本地 DynamoDB:-

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

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
Run Code Online (Sandbox Code Playgroud)

create_gsi_attributes.json:-

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

[{
    "AttributeName": "title",
    "AttributeType": "S"
},
{
    "AttributeName": "yearkey",
    "AttributeType": "N"
}]
Run Code Online (Sandbox Code Playgroud)

创建_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
        }
    }
}]
Run Code Online (Sandbox Code Playgroud)

编辑:-

命令:-

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
Run Code Online (Sandbox Code Playgroud)

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
        }
    }
}]
Run Code Online (Sandbox Code Playgroud)

create_gsi_attributes_conversation.json:-

[{
    "AttributeName": "user_id",
    "AttributeType": "S"
},
{
    "AttributeName": "conversation_id",
    "AttributeType": "S"
}]
Run Code Online (Sandbox Code Playgroud)