gpt4 book ai didi

node.js - 如何在 DynamoDB 中查询不存在的(空)属性

转载 作者:IT老高 更新时间:2023-10-28 22:07:42 24 4
gpt4 key购买 nike

我正在尝试查询 DynamoDB 表以查找未设置 email 属性的所有项目。一个名为 EmailPasswordIndex 的全局二级索引存在于包含 email 字段的表上。

var params = {
"TableName": "Accounts",
"IndexName": "EmailPasswordIndex",
"KeyConditionExpression": "email = NULL",
};

dynamodb.query(params, function(err, data) {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});

结果:

{
"message": "Invalid KeyConditionExpression: Attribute name is a reserved keyword; reserved keyword: NULL",
"code": "ValidationException",
"time": "2015-12-18T05:33:00.356Z",
"statusCode": 400,
"retryable": false
}

表定义:

var params = {
"TableName": "Accounts",
"KeySchema": [
{ "AttributeName": "id", KeyType: "HASH" }, // Randomly generated UUID
],
"AttributeDefinitions": [
{ "AttributeName": "id", AttributeType: "S" },
{ "AttributeName": "email", AttributeType: "S" }, // User e-mail.
{ "AttributeName": "password", AttributeType: "S" }, // Hashed password.
],
"GlobalSecondaryIndexes": [
{
"IndexName": "EmailPasswordIndex",
"ProvisionedThroughput": {
"ReadCapacityUnits": 1,
"WriteCapacityUnits": 1
},
"KeySchema": [
{ "AttributeName": "email", KeyType: "HASH" },
{ "AttributeName": "password", KeyType: "RANGE" },
],
"Projection": { "ProjectionType": "ALL" }
},
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};

dynamodb.createTable(params, function(err, data) {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});

最佳答案

DynamoDB 的全局二级索引允许索引稀疏。这意味着,如果您有一个 GSI,其项目的哈希或范围键未定义,则该项目将不会包含在 GSI 中。这在许多用例中很有用,因为它允许您直接识别包含某些字段的记录。但是,如果您正在寻找缺少的字段,这种方法将不起作用。

要获取所有未设置字段的项目,最好的选择可能是使用过滤器进行扫描。此操作将非常昂贵,但它会是如下所示的简单代码:

var params = {
TableName: "Accounts",
FilterExpression: "attribute_not_exists(email)"
};

dynamodb.scan(params, {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});

关于node.js - 如何在 DynamoDB 中查询不存在的(空)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349135/

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