Skip to content

Instantly share code, notes, and snippets.

@rococtz
Last active October 4, 2017 00:55
Show Gist options
  • Save rococtz/8addd38752d80a6e5e02b4fa10f24522 to your computer and use it in GitHub Desktop.
Save rococtz/8addd38752d80a6e5e02b4fa10f24522 to your computer and use it in GitHub Desktop.
DynamoDB cheatsheet

Start local instance of DynamoDB

java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb

Connect to database

var AWS = require("aws-sdk");

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

var dynamodb = new AWS.DynamoDB();

Create a table

var params = {
    TableName : "Movies",
    KeySchema: [       
        { AttributeName: "year", KeyType: "HASH"},  //Partition key
        { AttributeName: "title", KeyType: "RANGE" }  //Sort key
    ],
    AttributeDefinitions: [       
        { AttributeName: "year", AttributeType: "N" },
        { AttributeName: "title", AttributeType: "S" }
    ],
    ProvisionedThroughput: {       
        ReadCapacityUnits: 10, 
        WriteCapacityUnits: 10
    }
};

dynamodb.createTable(params, (err, data) => {});

Load data into table

// Sample data to be inserter
const movie = {
    "year" : 2013,
    "title" : "Turn It Down, Or Else!",
    "info" : {
        "release_date" : "2013-01-18T00:00:00Z",
        "rating" : 6.2,
        "actors" : [
            "David Matthewman",
            "Ann Thomas",
            "Jonathan G. Neff"
       ]
    }
}

var params = {
    TableName: "Movies",
    Item: {
        "year":  movie.year,
        "title": movie.title,
        "info":  movie.info
    }
};

docClient.put(params, (err, data) => {})

Read an item (by primary key)

var params = {
    TableName: "Movies",
    Key:{
        "year": 2000,
        "title": "Gladiator"
    }
};

docClient.get(params, (err, data) => {});

Update an item

var params = {
    TableName:table,
    Key:{
        "year": 2000,
        "title": "Gladiator"
    },
    UpdateExpression: "set info.rating = :r, info.plot=:p, info.actors=:a",
    ExpressionAttributeValues:{
        ":r":5.5,
        ":p":"Everything happens all at once.",
        ":a":["Larry", "Moe", "Curly"]
    },
    ReturnValues:"UPDATED_NEW"
};

docClient.update(params, (err, data) => {});

Increment an atomic counter

var params = {
    TableName:table,
    Key:{
        "year": 2000,
        "title": "Gladiator"
    },
    UpdateExpression: "set info.rating = info.rating + :val",
    ExpressionAttributeValues:{
        ":val":2
    },
    ReturnValues:"UPDATED_NEW"
};

docClient.update(params, (err, data) => {});

Update an item conditionally

var params = {
    TableName:table,
    Key:{
        "year": 2000,
        "title": "Gladiator"
    },
    UpdateExpression: "remove info.actors[0]",
    ConditionExpression: "size(info.actors) > :num",
    ExpressionAttributeValues:{
        ":num":3
    },
    ReturnValues:"UPDATED_NEW"
};

docClient.update(params, (err, data) => {});

Delete an item

var params = {
    TableName:"Movies",
    Key:{
        "year":2000,
        "title":"Gladiator"
    },
    ConditionExpression:"info.rating <= :val",
    ExpressionAttributeValues: {
        ":val": 5.0
    }
};

docClient.delete(params, (err, data) => {});

Query (by year)

var params = {
    TableName : "Movies",
    KeyConditionExpression: "#yr = :yyyy",
    ExpressionAttributeNames:{
        "#yr": "year"
    },
    ExpressionAttributeValues: {
        ":yyyy":1999
    }
};

docClient.query(params, (err, data) => {});

Query (by year with a certain title)

// title beginning with the letter "A" through the letter "L"
var params = {
    TableName : "Movies",
    ProjectionExpression:"#yr, title, info.genres, info.actors[0]",
    KeyConditionExpression: "#yr = :yyyy and title between :letter1 and :letter2",
    ExpressionAttributeNames:{
        "#yr": "year"
    },
    ExpressionAttributeValues: {
        ":yyyy":1992,
        ":letter1": "A",
        ":letter2": "L"
    }
};

docClient.query(params, function(err, data) {});

Scan

var params = {
    TableName: "Movies",
    ProjectionExpression: "#yr, title, info.rating",
    FilterExpression: "#yr between :start_yr and :end_yr",
    ExpressionAttributeNames: {
        "#yr": "year",
    },
    ExpressionAttributeValues: {
         ":start_yr": 1950,
         ":end_yr": 1959 
    }
};

console.log("Scanning Movies 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 {
        // print all the movies
        console.log("Scan succeeded.");
        // continue scanning if we have more movies, because
        // scan can retrieve a maximum of 1MB of data
        if (typeof data.LastEvaluatedKey != "undefined") {
            console.log("Scanning for more...");
            params.ExclusiveStartKey = data.LastEvaluatedKey;
            docClient.scan(params, onScan);
        }
    }
}

Delete table

var params = {
    TableName : "Movies"
};
dynamodb.deleteTable(params, function(err, data) {});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment