Note:- As you have not provided the full code, it is difficult to simulate and identify the issue. However, I have created the similar tables and indexes. It works fine for me. You can refer the below code for more details.
Here is the table create script and query the index.
You can change the table name and index name if required. I have followed the same key attributes structure that you have mentioned on post.
This has been tested and working fine.
1) Create table 'city' with index 'city_index':-
var params = {
TableName: 'city',
KeySchema: [
{
AttributeName: 'id',
KeyType: 'HASH',
},
{
AttributeName: 'name',
KeyType: 'RANGE',
}
],
AttributeDefinitions: [
{
AttributeName: 'id',
AttributeType: 'S',
},
{
AttributeName: 'name',
AttributeType: 'S',
},
{
AttributeName: 'city',
AttributeType: 'S',
},
],
ProvisionedThroughput: {
ReadCapacityUnits: 400,
WriteCapacityUnits: 400,
},
GlobalSecondaryIndexes: [
{
IndexName: 'city_index',
KeySchema: [
{
AttributeName: 'city',
KeyType: 'HASH',
}
],
Projection: {
ProjectionType: 'ALL'
},
ProvisionedThroughput: {
ReadCapacityUnits: 400,
WriteCapacityUnits: 400,
},
},
],
};
dynamodb.createTable(params, function(err, data) {
if (err){ console.log("error :" +JSON.stringify(err));}
else console.log("success :" +JSON.stringify(data));
});
2) Insert some data to city table
3) Query using index:-
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "city";
var params = {
TableName : table,
IndexName : 'city_index',
KeyConditionExpression : 'city = :cityVal',
ExpressionAttributeValues : {
':cityVal' : 'london'
}
};
docClient.query(params, function(err, data) {
if (err) {
console.error("Unable to read item. Error JSON:", JSON.stringify(err,
null, 2));
} else {
console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
}
});