Simply: AWS Dynamodb
Tags: aws, beginners, database, serverless
Published: 2020-08-30 13:14:56

![](https://upload.wikimedia.org/wikipedia/commons/f/fd/DynamoDB.png)

# What is DynamoDb? 
DynamoDb is a NoSQL, fully managed, key-value database within AWS

# Why should I use it? 
when it comes to data storage selecting what technology to use is always a big decisions, DynamoDb is like any other technology not a silver bullet but it does offer a lot of positives if you need a document based key-value storage

## Benefits of DynamoDb
* Low latency 
* Scaleable and fully managed
* [Cheap](https://aws.amazon.com/dynamodb/pricing)
* Highly durable
* Easy for beginners
* [And much more](https://aws.amazon.com/dynamodb/features/)

# How do I start?
First you're gonna need an AWS account, [follow this guide](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/). 

## 🛠️ Setting up our first DynamoDb database 
If you feel like it you can set your region on the top right corner of the AWS console, it should default to us-east-1 but you can select something closer to you, read more about [regions here.](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.RegionsAndAvailabilityZones.html)
![](https://dev-to-uploads.s3.amazonaws.com/i/n3pvnqevhfeosm945sbo.png)
From the AWS console head to **Services** and search for **DynamoDb** select the first option.

The first time you open up DynamoDb you should see a blue button with the text **Create Table**, click it. 
![](https://dev-to-uploads.s3.amazonaws.com/i/fv4qgo9324al0fxx7ffr.png)
Now you're presented with some options for creating your table, enter *myFirstTable* (this can be anything) in the *Table name*

### 🔑 Primary Key 
A key in a database is something used to identify items in the table and as such it must always be unique for every item. In DynamoDb the key is built up by a **Partion key** and an option **Sort key** 

* Partition Key: As the tooltip in the AWS console describes the Partion key is used to partion data across hosts because of that for best practice you should use an attribute that has a wide range of values, for now we don't need to worry much about this, the main thing to takeaway is that if the Partion key is used alone it must be unique

* Sort key: if the optional sort key is included the partition key does not have to be unique (but the combination of partition key and sort key does) it allows us to sort within a partition.

Let's continue, for this example I'm gonna say i'm creating something like a library system, so I'll put Author as the Partion key and BookTitle as the sort Key 
![](https://dev-to-uploads.s3.amazonaws.com/i/wdx9z76bvpzie98gzycf.png)
note that this is just one of many ways you could setup this type of table and choosing a good primary key is arguably one of the most important decisions when creating a DynamoDb table, what's good about AWS is that we can create a table, try it out, change our minds and just create a new one with ease. 

Next up are table settings, these are things like [secondary indexes](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SecondaryIndexes.html), [provisioned capacity](https://aws.amazon.com/dynamodb/pricing/provisioned/), [autoscaling](https://aws.amazon.com/blogs/database/amazon-dynamodb-auto-scaling-performance-and-cost-optimization-at-any-scale/), [encryption](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/EncryptionAtRest.html) and such. It's a good idea to eventually get a bit comfortable with these options and I highly recommend looking into [on-demand read/write capacity mode](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html#HowItWorks.OnDemand), but as we just want to get going now the default settings are fine and will not cost you anything for what we are doing today.
![](https://dev-to-uploads.s3.amazonaws.com/i/k1wio7l75z4eeh4zhylf.png)
Hit create and wait for your table to be created! 

Now you should be taken to the **tables** view of DynamoDb and your newly created table should be selected, this can be a bit daunting as there is a lot of options and information, but let's head over to the **Items** tab
![](https://dev-to-uploads.s3.amazonaws.com/i/pngyobjnoj25te22zxgu.png)

From here we could create an Item directly from the console (feel free to try it out if you want) but I think we can do one better and setup a lambda for interacting with the table.

# 📥 Creating our first Item
If you've never created an AWS lambda before I have written a similar guide to this one on the topic, you can find it [here](https://dev.to/tqfipe/simply-aws-lambda-bh1)

Create a lambda called DynamoDbInteracter 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/as6zkof2951gua8ubrin.png)
make sure to select to create a new role from a template and search for the template role **Simple microservice permissions** (this will allow us to perform any actions agains dynamodb)
![](https://dev-to-uploads.s3.amazonaws.com/i/6ts45xm1mrm8zrnydsuj.png)
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/htwtuw0lju016tr80jzy.png)

After creating the lambda we can directly edit it in the AWS console, copy and paste this code 

```javascript
const AWS = require('aws-sdk')
const client = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event) => {
    try {
        console.log(event.action)
        console.log(event.options)
    
        let response;
        switch (event.action) {
            case 'put':
                response = await putItem(event.options);
                break;
            case 'get':
                response = await getItem(event.options);
                break;
        }
        return response;
    } catch (e) {
        console.error(e)
        return e.message || e
    }
};


let putItem = async (options) => {
    var params = {
      TableName : 'myFirstTable',
      Item: {
         Author: options.author,
         BookTitle: options.bookTitle,
         genre: options.genre
      }
    };

    return await client.put(params).promise();
}

let getItem = async (options) => {
    var params = {
      TableName : 'myFirstTable',
      Key: {
        Author: options.author,
        BookTitle: options.bookTitle
      }
    };

    
    return await client.get(params).promise();
}
```

hit Save
then create a new test event like this 
```json
{
    "action": "put",
    "options": {
        "author": "Douglas Adams",
        "bookTitle": "The Hitchhiker's Guide to the Galaxy",
        "genre": "Sci-fi"
    }
}
```
and run that test event. 

Go back to DynamoDb and the Items tab and you should see your newly created Item!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rcv0hiyr3ep59b60aduw.png)

Notice that we did not have to specify the **genre** attribute that is because DynamoDb is NoSQL it follows no schemea and any field + value can be added to any item irregardless of the other items composition as long as the primary key is valid. 

# 📤 Retrieving our Item

Now let's try to get that item, create another test event like this 
```json
{
    "action": "get",
    "options": {
         "author": "Douglas Adams",
        "bookTitle": "The Hitchhiker's Guide to the Galaxy"
    }
}
```
and run it.
You can expand the execution results and you should see your response with the full data of the item
![](https://dev-to-uploads.s3.amazonaws.com/i/lnp65l6o2pm3fkttpu2z.png)

# 🎉 Congratulations!
You've just configured your first DynamoDb table and performed calls against it with a lambda but don't stop here the possibilities with just these two AWS services are endless, my next guide in this series will cover API-Gateway and how we can connect an API to our lambda that then communicates with our database table, stay tuned! 

# What's next? 
As I'm sure you understand we've just begun to scratch the surface of what DynamoDb has to offer, my goal with this series of guides is to get your foot in the door with some AWS services and show that although powerful and vast they are still easy to get started with, to check out more of what calls can be made with the DynamoDb API (such as more complicated queries, updates and scans as well as batch writes and reads) check [this](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html) out, feel free to edit the code and play around. 

I would also like to recommend [this guide](https://medium.com/brainstation23/break-the-ice-with-dynamodb-5302e7456d2a) if you want even more in-depth look into DynamoDb, it covers most of what I have here but more detailed and also goes over some of the API actions mentioned above.  

## 👨‍💻 Contact me
Questions? Thoughts? Feedback?
Twitter: [@tqfipe](https://twitter.com/tqfipe)
Linkedin: [Filip Pettersson](https://www.linkedin.com/in/filip-pettersson-08747bb7/)