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

68

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

你能提供表格和索引属性的定义吗? - mkobit
@mkobit 已添加,谢谢。 - Jordan Mack
4个回答

99

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

68

@jaredHatfield 是正确的,如果字段不存在,但如果字段为null,那么这种方法就不起作用了。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));
})

谢谢您提供的精准信息,我正需要这个 :) - Sébastien

2

这是@Mardok的优秀示例,已更新为v3 sdk并使用typescript。请注意使用@aws-sdk/util-dynamodb包中的marshall函数。

import { ScanCommand, ScanCommandInput } from '@aws-sdk/client-dynamodb';
import { marshall } from '@aws-sdk/util-dynamodb';

const input: ScanCommandInput = {
  TableName: 'Accounts',
  FilterExpression: 'attribute_not_exists(email) or email = :null',
  ExpressionAttributeValues: marshall({
    ':null': null,
  }),
};

const command = new ScanCommand(input);
const response = await dbClient.send(command);

0

由于 DynamoDB 情况特殊,我们需要使用非正统的方法来使用数据库。

我简单地引入了一个特殊值,它在您的域中可以安全地识别为任何内容(例如 "--NULL--"),并将其从/到最低数据层转换为null

查询具有该字段为空的条目只是查询该特殊值。

从习惯于 SQL 的人的角度来看,这不是很好,但比扫描要好得多。

对于旧条目,您将需要进行一次性迁移。


这个答案比Mardok的答案好吗?如果是,为什么? - ptoinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接