I have dynamoDB table,
Table name xx
Primary partition key id
(Number)
Primary sort key name
(String)
And I want to query it by name
.
'use strict';
const AWS = require("aws-sdk");
const dynamodb = new AWS.DynamoDB();
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, ctx, callback) {
var params = {
TableName: 'xx',
KeyConditionExpression: "#name = :name",
ExpressionAttributeNames:{
"#name": "name"
},
ExpressionAttributeValues: {
":name":event.name
}
};
docClient.query(params, function(err, data){
if(err){
callback(err, null);
}else{
callback(null, data);
}
});
}
but I got an error called :"Query condition missed key schema element:id:" how to deal with that?
DynamoDB is a NoSQL Database so you can only query the primary key by default. You have a couple of options:
Create a Global Secondary Index and query against that (Link):
"A global secondary index contains a selection of attributes from the base table, but they are organized by a primary key that is different from that of the table. The index key does not need to have any of the key attributes from the table; it doesn't even need to have the same key schema as a table."
Scan rather than Query:
var params= {
TableName:'xx',
ProjectionExpression:'name', // remove this string if you want to get not only 'name'
FilterExpression:'name = :name',
ExpressionAttributeValues:{ ":name" : event.name }
};
docClient.scan(params, function(err, data){
if(err){
callback(err, null);
}else{
callback(null, data);
}
});
If your tables isn't going to be huge Scan is the easier and cheaper way to do it (I believe Global Secondary Indicies have associated costs) but the 'correct' way to do it is with a Global Secondary Index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With