4
votes

I have a DynamoDB table which is described (users should be selectable by a unique user_id or a combination of username + 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"
            }
        ]
    }
],
... 

When I run the following code with the primary key, I get a list of records, as expected:

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); 
});

...but if I attempt to use the global secondary index, replacing key with:

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

then I get a ValidationException: The provided key element does not match the schema.

1

1 Answers

6
votes

...never mind - RTFM:

The GetItem operation returns a set of attributes for the item with the given primary key

To use the secondary index you need to do a query and provide the index name.