node.js - DynamoDb如何查询一个Global Secondary Index?

标签 node.js amazon-dynamodb

我创建了一个表,如下所示,其中包含 Em 的全局二级索引(代表电子邮件)。

    TableName : "Users",
    KeySchema: [
        { AttributeName: "Ai", KeyType: "HASH"},  //Partition key
        { AttributeName: "Ui", KeyType: "RANGE" }  //Sort key
    ],
    AttributeDefinitions: [
        { AttributeName: "Ai", AttributeType: "S" },
        { AttributeName: "Ui", AttributeType: "S" },
        { AttributeName: "Em", AttributeType: "S" }
    ],
    GlobalSecondaryIndexes: [
      {
        IndexName: 'EmailIndex',
        KeySchema: [
          { AttributeName: 'Em', KeyType: "HASH" },
        ],
        Projection: {
          ProjectionType: 'ALL'
        },
        ProvisionedThroughput: {
          ReadCapacityUnits: 1,
          WriteCapacityUnits: 1
        }
      }
    ],
    ProvisionedThroughput: {
        ReadCapacityUnits: 1,
        WriteCapacityUnits: 1
    }
}

在我的 node.js SDK 中,我尝试使用 EmailIndex 查询表,如下所示:

const params = {
  TableName: 'Users',
  IndexName: 'EmailIndex',
  Key: {
    Em: email
  }
}
try {
  const data = await docClient.get(params).promise()
  return data
} catch (error) {
  throw error
} 

我收到如下回复:

{
  "message": "The number of conditions on the keys is invalid",
  "code": "ValidationException",
  "time": "2018-07-02T10:33:13.313Z",
  "requestId": "edc5f2e0-3c2b-4354-9342-4a96c74988a6",
  "statusCode": 400,
  "retryable": false,
  "retryDelay": 17.366914444025173
}

我正在尝试从电子邮件地址获取数据。我做错了什么?

最佳答案

您需要在二级索引上运行查询,而不是从表中读取的项目。

var email = "JoeBloggs@hotmail.com";

var docClient = new AWS.DynamoDB.DocumentClient();

var params = {
    TableName : "Users",
    IndexName : "EmailIndex",
    KeyConditionExpression: "#email = :v_email",
    ExpressionAttributeNames:{
        "#email": "Em"
    },
    ExpressionAttributeValues: {
        ":v_email": email
    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
    } else {
        console.log("Query succeeded.");
        data.Items.forEach(function(item) {
            console.log(" -", item.Em + ": " + item.Ai);
        });
    }

查询数据-https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.NodeJs.04.html 索引 - https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html

关于node.js - DynamoDb如何查询一个Global Secondary Index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134296/

相关文章:

javascript - Mongodb 位置运算符不起作用

node.js - 排序时流式传输大数据

javascript - find内部另一个find(...)的回调,如何逃离回调 hell ?

node.js - 使用nodejs从异步函数返回列表

node.js - 应用程序端加入 Node 的 ORM?

python - DynamoDB 更新多个值

excel - 是否可以从 Excel 文件导入 AWS DynamoDB 中的数据?

javascript - 使用来自 node_modules 的 SVG

amazon-web-services - TransactionCanceledException中的神秘TransactionConflict

java - dynamodb 我如何模拟映射器?