首页 > 解决方案 > 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如果我什至不能在查询中引用它,那么定义一个键有什么意义?

标签: javascriptnode.jsamazon-dynamodb

解决方案


当你做一个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


推荐阅读