Darshan Soni
Darshan Soni

Reputation: 1809

Amazon DynamoDB with 'OR' condition

I'm just starting with the amazon dynamoDB and I have to create a no-sql db structure like this,

-posts
    -postId1
        -tags
            1:A
            2:B
            3:C
        -text:Hello

    -postId2
        -tags
            1:B
            2:D
        -text:How are you?

    -postId3
        -tags   
            1:A
            2:C
        -text:Hello World

Now, I want to retrieve the text of those post IDs which are having the tag B or D what will be the easiest way to achieve this ?

Upvotes: 0

Views: 718

Answers (1)

notionquest
notionquest

Reputation: 39186

As discussed on comments, if you maintain the tags attribute as DynamoDB list data type, you can use CONTAINS with OR operator to check to filter the posts which has tags B or D.

Sample params for Scan API:-

var params = {
    TableName: "post",
    FilterExpression: "contains (tags, :tag1) OR  contains (tags, :tag2)",
    ExpressionAttributeValues: {
        ":tag1": 'B',
        ":tag2": 'D'
    }
};

Full code:-

The below code uses local DynamoDB.

var AWS = require("aws-sdk");
var creds = new AWS.Credentials('akid', 'secret', 'session');

AWS.config.update({
    region: "us-west-2",
    endpoint: "http://localhost:8000",
    credentials: creds
});

var docClient = new AWS.DynamoDB.DocumentClient();

var params = {
    TableName: "post",
    FilterExpression: "contains (tags, :tag1) OR  contains (tags, :tag2)",
    ExpressionAttributeValues: {
        ":tag1": 'B',
        ":tag2": 'D'
    }
};

console.log("Scanning Post table.");
docClient.scan(params, onScan);

function onScan(err, data) {
    if (err) {
        console.error("Unable to scan the table. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("Scan succeeded.");
        data.Items.forEach(function (printItem) {
            console.log("Item :", JSON.stringify(printItem));
        });

        if (typeof data.LastEvaluatedKey != "undefined") {
            console.log("Scanning for more...");
            params.ExclusiveStartKey = data.LastEvaluatedKey;
            docClient.scan(params, onScan);
        }
    }
}

Upvotes: 2

Related Questions