我使用了带有以下字段的 DynamoDB 表:
主分区键 => user_id
主排序键 => conversation_id
示例表数据+---------+--------------------+
| user_id | conversation_id |
+---------+--------------------+
| 10 | aaaa |
| 10 | bbbb |
| 10 | cccc |
| 11 | aaaa |
| 11 | bbbb |
| 11 | cccc |
+---------+--------------------+
我在 dynamodb 中有两个单独的查询:
conversation_id
由特别 user_id
.如果输入 10 => 输出 => aaaa, bbbb, cccc
user_id
来自特定 conversation_id
?如果输入 aaaa => 输出 => 10,11
我可以获得第一个查询的结果,但是如何获取第二个查询结果。?
使用 获取数据是一个好习惯吗?主排序键 (
conversation_id
) 或如何分配或创建
conversation_id
如 全局二级索引(另一个分区键) ..?备注 :我正在使用 PHP(Codeigniter 框架)
最佳答案
1) 您需要使用 query
获取分区键的所有排序键。请引用以下链接。
Query API
Query sample code
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
create_gsi_attributes.json:-
请将属性名称(和类型)更改为
conversation_id
和 user_id
[{
"AttributeName": "title",
"AttributeType": "S"
},
{
"AttributeName": "yearkey",
"AttributeType": "N"
}]
create_gsi.json:-
请将关键架构属性名称更改为
conversation_id
和 user_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"
}]
关于database-design - 如何在 DynamoDB 中将排序键设置为全局二级索引(另一个分区键)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41393672/