Search code examples
amazon-web-servicesamazon-dynamodbdynamodb-queries

How to make QUERY using "NOT_CONTAINS" in nodejs with DynamoDB


Querying Dynamodb for a list of posts from a table, here I need to do some filters on query. I need to check a user-id in a list in my table if the user-id matches the record should be ignored. I need this condition I tried using some examples for CONTAINS and it works and I don't know how to write code for NOT_CONTAINS.

code sample follows.

var params = {
  TableName: config.aws_table_name,
  IndexName: "active",
  ExclusiveStartKey: key_value,
  ExpressionAttributeNames: {
    "#timestamp": "timestamp",
    "#tu1": "taggedUsers",
  },
  KeyConditionExpression: "active = :ac and #timestamp BETWEEN :from AND :to",
  FilterExpression: "#tu1 NOT_CONTAINS :tu2",
  ProjectionExpression: "title, description",
  ExpressionAttributeValues: {
    ":ac": "true",
    ":from": 1632919324385,
    ":to": Date.now(),
    ":tu2": userId,
  },
  Limit: req.query.limit,
};

const result = docClient.query(params, function (err, data) {
  if (err) {
    console.log(err);
    res.send({
      success: false,
      message: err,
    });
  } else {
    const { LastEvaluatedKey } = data;
    const { Items } = data;
    res.send({
      success: true,
      posts: Items,
      lastEvaluatedKey: LastEvaluatedKey,
    });
  }
});

As you can see I'm using BETWEEN but I don't know how to use NOT_CONTAINS, LE, and NE. please give some sample params for query in node.js. Thanks

https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Condition.html


Solution

  • I have discovered a solution for this issue. Just give a between not_contains. like this not contains(#tu1, :tu2).

    var params = {
        TableName: config.aws_table_name,
        IndexName: "active",
        ExclusiveStartKey: key_value,
        KeyConditionExpression: "active = :ac and #timestamp BETWEEN :from AND :to",
        ProjectionExpression: "title, description",
        FilterExpression : "not contains(#tu1, :tu2)",
        ExpressionAttributeNames: {
            "#timestamp": "timestamp",
            "#tu1": "taggedUsers"
        },
        ExpressionAttributeValues: {
            ":ac": "true",
            ":from": 1632919324385,
            ":to": Date.now(),
            ":tu2": userId
        },
        Limit: req.query.limit
    }
    

    Thanks.