Reputation: 8635
How can I query using secondary index using dynamo db and node js
Heres my code so far, but it doesn't work
getObjectByAlternateKey: function (keyName, keyObj, indexName, callback, consistentRead) {
var params = {
TableName: this.tableName,
KeyConditionExpression: keyName + ' = :v_key',
ExpressionAttributeValues: converters.jsObjectToDynamoMap({ ':v_key': keyObj }),
IndexName: indexName,
ConsistentRead: !!consistentRead
};
this.dynamo.query(params, function (error, data) {
console.dir(data);
if (error) {
return callback(error);
}
if (data.Items && data.Items.length > 0) {
if (data.Items.length !== 1) {
console.warn("Got more than one item returned for query!", { query: params, data: data });
}
return callback(null, converters.dynamoMapToJsObject(data.Items[0]));
}
return callback(null, null);
});
},
Here's the cloudformation template I used to create the table:
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
"TableName": {
"Description": "Table name to use",
"Type": "String",
"Default": "test-user-unique-ids-prod-ue1"
},
"ReadCapacityUnits": {
"Description": "Provisioned read throughput",
"Type": "Number",
"Default": "100",
"MinValue": "1",
"MaxValue": "10000",
"ConstraintDescription": "must be between 1 and 10000"
},
"WriteCapacityUnits": {
"Description": "Provisioned write throughput",
"Type": "Number",
"Default": "100",
"MinValue": "1",
"MaxValue": "10000",
"ConstraintDescription": "must be between 1 and 10000"
}
},
"Resources": {
"sparkUserUniqueIds": {
"Type": "AWS::DynamoDB::Table",
"Properties": {
"TableName": {
"Ref": "TableName"
},
"AttributeDefinitions": [
{
"AttributeName": "guid",
"AttributeType": "S"
},
{
"AttributeName": "unique_id",
"AttributeType": "S"
}
],
"KeySchema": [
{
"AttributeName": "guid",
"KeyType": "HASH"
}
],
"GlobalSecondaryIndexes": [
{
"IndexName": "test-user-by-unique-id",
"KeySchema": [
{
"AttributeName": "unique_id",
"KeyType": "HASH"
}
],
"Projection": {
"ProjectionType": "ALL"
},
"ProvisionedThroughput": {
"ReadCapacityUnits": {
"Ref": "ReadCapacityUnits"
},
"WriteCapacityUnits": {
"Ref": "WriteCapacityUnits"
}
}
}
],
"ProvisionedThroughput": {
"ReadCapacityUnits": {
"Ref": "ReadCapacityUnits"
},
"WriteCapacityUnits": {
"Ref": "WriteCapacityUnits"
}
}
}
}
}
}
Upvotes: 1
Views: 1454
Reputation: 911
Log your params
value , it should be like this
{ TableName: 'test-user-unique-ids-prod-ue1',
IndexName: 'test-user-by-unique-id',
KeyConditions:
{ unique_id:
{ ComparisonOperator: 'EQ',
AttributeValueList: [ { S: 'test' } ] } } }
Upvotes: 2