首页 > 解决方案 > 如何使用排序键中的任何值查询 DynamoDB?

问题描述

我有一个包含 userId、pictureURL 和其他一些字段的简单表。我想返回具有某个 userId 的所有字段,但是当我这样做时

dynamodb.get({
  TableName: tableName,
  Key: {
    'userid': '39e1f6cb-22af-4f8c-adf5-xxxxxxxxxx'
  }
}, ...

我明白The provided key element does not match the schema了,因为它似乎也需要排序键。当我做

dynamodb.get({
  TableName: tableName,
  Key: {
    'userid': '39e1f6cb-22af-4f8c-adf5-xxxxxxxxxx',
    'pictureurl': '' // Or null
  }
}, ...

我收到一个错误One or more parameter values were invalid: An AttributeValue may not contain an empty string

那么如何查询排序键中的任何值呢?

标签: javascriptnode.jsamazon-web-servicesamazon-dynamodb

解决方案


使用 DynamoDB DocumentClient

  • 要查询多个项目,请使用query
  • 要获取单个项目,请使用get

因此,使用查询并使用KeyConditionExpression参数为分区键提供特定值。查询操作将返回具有该分区键值的表(或索引)中的所有项目。

这是一个例子:

const AWS = require("aws-sdk");
AWS.config.update({region: 'us-east-1'});

const params = {
  TableName: tableName,
  KeyConditionExpression: '#userid = :userid',
  ExpressionAttributeNames: {
    '#userid': 'userid',
  },
  ExpressionAttributeValues: {
    ':userid': '39e1f6cb-22af-4f8c-adf5-xxxxxxxxxx',
  },
};

const dc = new AWS.DynamoDB.DocumentClient();

dc.query(params, (err, data) => {
  if (err) {
    console.log('Error', err);
  } else {
    for (const item of data.Items) {
      console.log('item:', item);
    };
  }
});

推荐阅读