Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you query for a non-existent (null) attribute in DynamoDB

People also ask

IS NOT NULL DynamoDB?

There is no NotNull constraint explicitly available on DynamoDB. However there is a feature to provide default value for the attribute if you are using DynamoDBMapper. Also, DynamoDB API doesn't allow to add an attribute with empty value (i.e. Null or empty string '').

Can DynamoDB have NULL values?

Dynamodb can't accept a key with an explicitly NULL value.

Can DynamoDB sort null keys?

Can the DynamoDB sort key be null? DynamoDB does not support null for sort key.

Can you Query in DynamoDB?

In Amazon DynamoDB, you can use either the DynamoDB API, or PartiQL, a SQL-compatible query language, to query an item from a table. With Amazon DynamoDB the Query action lets you retrieve data in a similar fashion. The Query action provides quick, efficient access to the physical locations where the data is stored.


DynamoDB's Global Secondary Indexes allow for the indexes to be sparse. That means that if you have a GSI whose hash or range key for an item is not defined then that item will simply not be included in the GSI. This is useful in a number of use cases as it allows you to directly identify records that contain certain fields. However, this approach will not work if you are looking for the lack of a field.

To get all of the items that have a field not set your best bet may be resorting to a scan with a filter. This operation will be very expensive but it would be straightforward code looking something like the following:

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

@jaredHatfield is correct if the field does not exist but that will not work if the filed is null. NULL is a keyword and can't used directly. But you can use it with 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));
})