我有一个描述的DynamoDB表(用户应通过唯一的user_id或用户名+ system_id的组合来选择):

"TableName": "auth-users",
"KeySchema": [ {
        "KeyType": "HASH",
        "AttributeName": "user_id"
    }
],
"AttributeDefinitions": [ {
    {
        "AttributeName": "user_id",
        "AttributeType": "S"
    },
        "AttributeName": "system_id",
        "AttributeType": "S"
    },  {
        "AttributeName": "username",
        "AttributeType": "S"
    }
],
"GlobalSecondaryIndexes": [
    {
        "IndexName": "username-system_id-index",
        "Projection": {
            "ProjectionType": "ALL"
        },
        "IndexStatus": "ACTIVE",
        "KeySchema": [ {
               "KeyType": "HASH",
               "AttributeName": "username"
            }, {
               "KeyType": "RANGE",
               "AttributeName": "system_id"
            }
        ]
    }
],
...


当我使用主键运行以下代码时,将按预期获得记录列表:

var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB({region: 'ap-southeast-2');
var userTable = 'auth-users';
var key = { user_id: '123412341234' };

dynamodb.getItem({
   TableName: tableName,
   Key: key
}, function(err,data) {
   console.error('err:',err);
   console.info('data:', data);
});


...但是如果我尝试使用全局二级索引,则将key替换为:

var key = {
    username:  {S: 'testuser'},
    system_id: {S: 'test-system'}
};


然后我收到ValidationException:提供的key元素与架构不匹配。

最佳答案

...没关系-RTFM:


GetItem操作使用以下命令返回该项目的一组属性
给定的主键


要使用二级索引,您需要执行query并提供索引名称。

08-05 18:56