向 AWS DynamoDB 添加 where 子句

Adding a where clause to AWS DynamoDB

我正在尝试在 AWS Lambda 中创建一个 getItem 请求以像这样访问 DynamoDB:

dynamodb.getItem({
    TableName: "DataTable",
    Key: {
        user: {
            S: user
        },
        deleted: {
            BOOL: false
        }
    }
}, function(err, data) {
    if (err) return fn(err);
    else {
        if ('Item' in data) {
            fn(null, user);
        } else {
            fn(null, null); // User not found
        }
    }
});

当我传递用户时它工作正常,因为那是 table 上的主键。我添加了一个已删除的布尔值来创建对用户的软删除。但是我补充说,在模式中开始发生错误,因为删除不是主键的一部分。我想要一种方法将其添加为来自关系数据库世界的 where 子句。这是怎么做到的?谢谢。 :o)

如果必须按任何非键属性过滤数据,则不能使用 getItem

我认为在上面的例子中,'deleted'属性是一个非键属性。因此,查询 API 应该与键属性一起用于过滤数据。

请参考下面例子中的FilterExpression

过滤表达式:'deleted = :createdate'

(AWS.Request) query(params = {}, callback)

示例代码:-

var params = {
    TableName : table,
    KeyConditionExpression : 'yearkey = :hkey and title = :rkey',
    FilterExpression : 'deleted = :deleted',
    ExpressionAttributeValues : {
        ':hkey' : year_val,
        ':rkey' : title,
        ':deleted' : {BOOL : false}
    }
};

docClient.query(params, function(err, data) {
    if (err) {
        console.error("Unable to read item. Error JSON:", JSON.stringify(err,
                null, 2));
    } else {
        console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
    }
});

对于您的用例,键、过滤条件和表达式属性值应如下所述:-

KeyConditionExpression : 'user = :user',
FilterExpression : 'deleted = :deleted',
ExpressionAttributeValues : {
     ':user' : 'John',
     ':deleted' : {BOOL : false}
}