javascript - DynamoDB 无法按范围键获取项目?
问题描述
我正在尝试使用定义为键的列从 DynamoDB 表中获取一条记录RANGE
,但是当我这样做时出现此错误:
The provided key element does not match the schema
这是我创建和播种表的方式:
// 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++;
}
这就是我试图获取记录的方式:
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);
};
RANGE
如果我什至不能在查询中引用它,那么定义一个键有什么意义?
解决方案
当你做一个get
你只能要求一个项目。Get 返回(或不返回)与完整键对应的单个项目,否则"The provided key element does not match the schema"。例子:
const id = 'marmelade';
const index = 5;
db.get({
TableName: 'talk_stem.words',
Key: {
id,
index,
},
}).promise()
与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()
请记住,使用 DynamoDB 时get
需要query
提及分区键。总是。当你想获取不知道的分区键的项目时,你只能做一个“昂贵的” scan
。
推荐阅读
- javascript - 将替换方法的组合转换为一个
- ruby-on-rails - 如何使用 Proc.new
- python - 尝试使用 join/split 删除我自己的停用词
- python - 从包含索引的另一个子列表的子列表中获取项目
- javascript - 使用 Sequelize 破坏模型的麻烦
- batch-file - SVN 和 JIRA 集成以使用 API 检查 JIRA 中是否存在问题
- sql - SQL 全外连接 + group by + count 列
- android - 当在 Tabs 中再次打开 Fragment 时,Recycler View 变为空视图
- c# - 调试 ASP.NET (.NET Framework 4.8) Web 应用程序时,没有为新 csproj 格式的 (.NET Framework 4.8) 库加载符号
- php - PHP Null 合并混乱