Sim*_*leJ 2 javascript node.js amazon-dynamodb
我正在尝试使用定义为RANGE键的列从 DynamoDB 表中获取单个记录,但是当我这样做时,我收到此错误:
The provided key element does not match the schema
Run Code Online (Sandbox Code Playgroud)
这是我创建和播种表的方式:
// Create words table
if(!tableExists('words')) {
console.log('Creating words table');
await createTable({
TableName: 'words',
KeySchema: [
{ AttributeName: 'id', KeyType: 'HASH' },
{ AttributeName: 'index', KeyType: 'RANGE' },
],
AttributeDefinitions: [
{ AttributeName: 'id', AttributeType: 'S' },
{ AttributeName: 'index', AttributeType: 'N' },
],
ProvisionedThroughput: { ReadCapacityUnits: 5, WriteCapacityUnits: 5 },
});
await wait(5000);
console.log('done');
} else {
console.log('words table found. Skipping.')
}
// Seed words
let index = 0;
for(let word of words) {
console.log(`Adding word ${word}`);
const params = {
TableName: tableName('words'),
Item: {
id: word,
index: index,
},
};
await db.put(params).promise();
console.log('added');
index++;
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试获取记录的方式:
const db = require('../db');
const getResponseItem = response => response.Item;
module.exports = function loadWordByIndex(index) {
return db.get({
TableName: 'talk_stem.words',
Key: {
index,
},
})
.promise()
.then(getResponseItem);
};
Run Code Online (Sandbox Code Playgroud)
RANGE如果我什至不能在查询中引用它,那么定义一个键有什么意义?
当你做一个时,get你只能要求一个项目。Get 返回(或不返回)与完整键对应的单个项目,否则“提供的键元素与架构不匹配”。例子:
const id = 'marmelade';
const index = 5;
db.get({
TableName: 'talk_stem.words',
Key: {
id,
index,
},
}).promise()
Run Code Online (Sandbox Code Playgroud)
与get您一起寻找一件商品!
您需要的是一个query(请参阅此处的文档)。你可以想象这样的事情:
db.query({
TableName: 'talk_stem.words',
KeyConditionExpression: '#id = :id AND #index BETWEEN :indexLow AND :indexHigh',
ExpressionAttributeNames: {
'#id': 'id',
'#index': 'index',
},
ExpressionAttributeValues: {
':id': id, # a fixed id
':indexLow': 3,
':indexHigh': 9,
},
}).promise()
Run Code Online (Sandbox Code Playgroud)
请记住,使用 DynamoDBget并query需要提及分区键。总是。当你想获取你不知道的分区键的项目时,你只能做一个“昂贵”的scan。