如何在DynamoDB中查询不存在的(空)属性

我试图查询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)); }); 

DynamoDB的全局二级索引允许索引稀less。 这意味着,如果您有一个GSI的项目的散列或范围键未定义,那么该项目将不会被包含在GSI中。 这在许多用例中很有用,因为它允许您直接标识包含特定字段的logging。 但是,如果你正在寻找缺less一个领域,这种方法将无法正常工作。

要获得所有没有设置字段的项目,您最好的办法可能是使用筛选器进行扫描。 这个操作将是非常昂贵的,但它会是直截了当的代码如下所示:

 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)); });