无法使用Begins_with查询DynamoDB的项目列表 [英] Can't Query DynamoDB with Begins_with for list of Items
问题描述
我已经尝试查询DynamoDB数据了2天了.让我发疯.
I've been trying to query data from the DynamoDB for 2 days now. Driving me insane.
我在办公室有一张桌子.假设有两个办公室,科克和都柏林.我有一个名为"deskName"的列,其名称类似于"cork1","cork2","dub1","dub2".我希望能够在表中查询包含在同一表中的软木"或"dub"项,但我不想将整个表扫描回去.
I have a table for desks in an office. Say there is two offices, Cork and Dublin. I have a column called 'deskName' which would have names like 'cork1', 'cork2', 'dub1', 'dub2'. I want to be able to query the table for Items which contain 'cork' or 'dub' as they are in the same table but I don't want to SCAN the whole table back.
代码:
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}
错误:
ValidationException: Query key condition not supported
当我的条件='cork-1'时,我设法退回了一件商品.我想获取所有以软木"开头的项目.
I managed to get one item coming back when I had the condition = 'cork-1'. I want to get every item that begins with 'cork'.
谢谢
推荐答案
您正在得到这个...
You're getting this...
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'
之后缺少一个.
JavaScript objects require a comma after each property. You're missing one after IndexName: 'deskName'
.
我建议使用 DocumentClient 因为它可以轻松地将Javascript数据类型映射到DynamoDB数据类型.
I would recommend the use of DocumentClient as it easily maps Javascript data types to DynamoDB data types.
这篇关于无法使用Begins_with查询DynamoDB的项目列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!