gpt4 book ai didi

javascript - DynamoDB 无法按范围键获取项目?

转载 作者:行者123 更新时间:2023-11-30 11:11:14 24 4
gpt4 key购买 nike

我尝试使用定义为 RANGE 键的列从 DynamoDB 表中获取单个记录,但是当我这样做时,我收到此错误:

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 返回(或不返回)与完整键相对应的单个项目,否则“提供的键元素与架构不匹配”。示例:

const id = 'marmelade';
const index = 5;

db.get({
TableName: 'talk_stem.words',
Key: {
id,
index,
},
}).promise()

使用 get 您可以查找一项!

您需要的是查询 ( see doc here )。你可以想象这样的事情:

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,getquery 需要提及分区键。总是。当您想要获取您不知道的分区键的项目时,您只能进行“昂贵的”扫描

关于javascript - DynamoDB 无法按范围键获取项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53545048/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com