我尝试查询DynamoDB表以查找未设置email
属性的所有项。包含email
字段的表中存在一个名为EmailPasswordIndex
的全局二级索引。
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));
});
4条答案
按热度按时间3xiyfsfu1#
DynamoDB的全局辅助索引允许索引是稀疏的。这意味着,如果您有一个GSI,它的散列或范围关键字的一个项目没有定义,那么该项目将不会被包括在GSI。这在许多用例中非常有用,因为它允许您直接识别包含某些字段的记录。但是,如果您正在查找缺少字段,则此方法将不起作用。
要获得所有未设置字段的项目,您最好的选择可能是使用过滤器进行扫描。这个操作将非常昂贵,但它将是简单的代码,看起来像下面这样:
ylamdve62#
如果字段不存在,@jaredHatfield是正确的,但如果字段为空,则不起作用。NULL是一个关键字,不能直接使用。但您可以将其与ExpressionAttributeValues一起使用。
kokeuurv3#
由于DynamoDB就是这样,因此需要使用非正统的方法来使用数据库。
我只是引入了一个特殊的值,它可以是在您的域中可以安全识别的任何东西(例如。
"--NULL--"
),并在最低数据层将其从/转换为null
。查询带有该字段null的条目就是查询该特殊值。
从习惯SQL的人的Angular 来看,这并不好,但比扫描好。
对于旧条目,您将需要一次性迁移。
qlvxas9a4#
下面是@Mardok的优秀示例,它针对v3 sdk进行了更新,并使用了typescript。注意
@aws-sdk/util-dynamodb
包中marshall
函数的用法。