Home Articles

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

Asked
Viewed 1329 times
15

我正在尝试查询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));
});

2 Answers

  • 26

    如果该字段不存在,则@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));
    })
    
  • 4

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

Related