DynamoDB无法通过范围键获取项目?

时间:2018-11-29 18:03:17

标签: javascript node.js amazon-dynamodb

我正在尝试使用定义为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键有什么意义?

1 个答案:

答案 0 :(得分:2)

制作get时,您只能索取物品。获取(或不返回)与完整键相对应的单个项目,否则返回“提供的键元素与架构不匹配” 。示例:

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

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

使用get,您将寻找一项!

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