我一直在尝试从DynamoDB查询数据2天。让我疯了。
我在办公室里有办公桌。说有两个办公室,科克和都柏林。我有一个名为'deskName'的列,它的名字有'cork1','cork2','dub1','dub2'。我希望能够在表中查询包含'cork'或'dub'的Items,因为它们在同一个表中,但我不想再扫描整个表。CODE:
const params = {
TableName: process.env.DYNAMODB_DESKS_TABLE,
//KeyConditionExpression: '#deskName = :deskName',
KeyConditionExpression: "begins_with(#deskName, :deskName)",
ExpressionAttributeNames: {
"#deskName": "deskName"
},
ExpressionAttributeValues: {
":deskName": "cork"
}
}
dynamodb.query(params, (error, result) => {
if (error) {
console.error(error);
callback(null, {
statusCode: error.statusCode || 501,
headers: {'Content-Type': 'text/plain'},
body: 'Couldn\'t get desks'
});
return;
}
const response = {
statusCode: 200,
body: JSON.stringify(result.Item)
};
callback(null, response);
});
YAML:
HotDeskDesksDBTable:
Type: 'AWS::DynamoDB::Table'
DeletionPolicy: Retain
Properties:
AttributeDefinitions:
-
AttributeName: deskName
AttributeType: S
KeySchema:
-
AttributeName: deskName
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
TableName: ${self:provider.environment.DYNAMODB_DESKS_TABLE}
ERROR:
ValidationException: Query key condition not supported
当我有条件='cork-1'时,我设法让一件物品回来。我希望得到以“软木塞”开头的每件商品。
谢谢
答案 0 :(得分:0)
你得到了这个......
Syntax error in module 'api/desks/get': SyntaxError
KeyConditionExpression: "#deskName = :deskName",
^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
因为这个......
const params = {
TableName: process.env.DYNAMODB_DESKS_TABLE,
IndexName: 'deskName'
KeyConditionExpression: "#deskName = :deskName",
ExpressionAttributeNames:{
"#deskName": "deskName"
},
ExpressionAttributeValues: {
":deskName": "cork"
}
}
JavaScript对象在每个属性后都需要逗号。你在IndexName: 'deskName'
之后错过了一个。
我建议使用DocumentClient,因为它可以轻松地将Javascript数据类型映射到DynamoDB数据类型。
答案 1 :(得分:0)
以下是我可以收集的内容:
const params = {
TableName: process.env.DYNAMODB_DESKS_TABLE, IndexName: 'deskName',
ExpressionAttributeValues: { ":deskName": { "S": "cork" } }