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

Jor*_*ack 23 amazon-web-services node.js amazon-dynamodb

我正在尝试查询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));
});
Run Code Online (Sandbox Code Playgroud)

结果:

{
  "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
}
Run Code Online (Sandbox Code Playgroud)

表定义:

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));
});
Run Code Online (Sandbox Code Playgroud)

Jar*_*eld 38

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));
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*dok 17

如果该字段不存在,则@jaredHatfield是正确的,但如果该字段为空则不起作用.NULL是关键字,不能直接使用.但您可以将它与ExpressionAttributeValues一起使用.

const params = {
    TableName: "Accounts",
    FilterExpression: "attribute_not_exists(email) or email = :null",
    ExpressionAttributeValues: {
        ':null': null
    }
}

dynamodb.scan(params, (err, data) => {
    if (err)
        console.log(JSON.stringify(err, null, 2));
    else
        console.log(JSON.stringify(data, null, 2));
})
Run Code Online (Sandbox Code Playgroud)