DynamoDB and its Data Pane Operations - 1
Tags: dynamodb, aws, cli, crud
Published: 2022-12-14 00:56:53

In this article, I am going to show you some of the Data Pane (read-write) operations, such us Create, Read, Update and Delete (CRUD) on DynamoDB **`items`**, using **`expressions`** and **`conditional expressions`**.

In this article, I am **`not`** explaining the terminology and the concepts used in DynamoDB Tables. Please visit my previous articles for this - [DynamoDB and its Control Pane Operations - 1](https://dev.to/aws-builders/dynamodb-and-its-control-pane-operations-1-36bk) and [DynamoDB and its Control Pane Operations - 2](https://dev.to/aws-builders/dynamodb-and-its-control-pane-operations-2-327b).



_**Let’s get started!**_


# Objectives:

**1.** Create an item

**2.** Read an item

**3.** Update an item

**4.** Delete an item


Please visit my **[GitHub Repository for DynamoDB articles](https://github.com/awsmine/DynamoDB_projects)** on various topics being updated on constant basis.


# Pre-requisites:
- AWS user account with admin access, not a root account.
- Cloud9 IDE with AWS CLI.
- Create the DynamoDB table - **`Movies`** from the previous article [DynamoDB and its Control Pane Operations - 1](https://dev.to/aws-builders/dynamodb-and-its-control-pane-operations-1-36bk)


# Resources Used:

[Amazon DynamoDB Developer Guide](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html)

[Put item cli](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/put-item.html)

[Get item cli](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/get-item.html)

[Update item cli](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/update-item.html)

[Delete item cli](https://docs.aws.amazon.com/cli/latest/reference/dynamodb/delete-item.html)








# Steps for implementation to this project:

## 1. Create an item

**PutItem** – Writes a single item to a table. 

- You must specify the entire primary key attributes, but you don't have to specify other attributes.

- if a table has a composite primary key (partition key and sort key), you must provide a value for the partition key and a value for the sort key.

- It creates a new item or replaces an existing item completely with a new item. 

- Copy the and paste below in your AWS Cloud9 command prompt. 

- It puts 3 items into the **`Movies`** table

```
aws dynamodb put-item \
    --table-name Movies \
    --item '{
           "Title": {"S": "Abhimaan"},
           "Review": {"S": "Excellent"},
           "Actor": {"S": "Big B"},
           "PostedBy": {"S": "User A"},
           "Songs": {"L": [ {"S": "Song1"},
                            {"S": "Song2"}
                          ]
                    }
            }'
aws dynamodb put-item \
    --table-name Movies \
    --item '{
           "Title": {"S": "Abhimaan"},
           "Review": {"S": "Terrific"},
           "Actor": {"S": "Jaya"},
           "PostedBy": {"S": "User B"},
           "Songs": {"L": [ {"S": "Song1"},
                            {"S": "Song2"}
                          ]
                    }
            }'
aws dynamodb put-item \
    --table-name Movies \
    --item '{
           "Title": {"S": "Abhimaan"},
           "Review": {"S": "Too Good"},
           "Actor": {"S": "Bindu"},
           "PostedBy": {"S": "User A"},
           "Songs": {"L": [ {"S": "Song1"},
                            {"S": "Song2"}
                          ]
                    }
            }'  
```



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/09utgw4eqaxkz31bb1ih.png)



## 2. Read an item

**GetItem** – Retrieves a single item from a table. 

- You must specify the primary key for the item that you want.

- You can retrieve the entire item, or just a subset of its attributes.

- Copy the and paste below in your AWS Cloud9 command prompt. 

- By default a read from DynamoDB uses eventual consistency because eventually consistent reads in DynamoDB are half the price of a strongly consistent read. 

- There are many useful options to the get-item command but a few of them which are used regularly are:

    **`--consistent-read`** : Specifying that you want a strongly consistent read
    **`--projection-expression`** : Specifying that you only want certain attributes returned in the request
    **`--return-consume-capacity`** : Tell us how much capacity was consumed by the request
     
    - Possible values:

        **`INDEXES`** - The response includes the aggregate ConsumedCapacity for the operation, together with ConsumedCapacity for each table and secondary index
        **`TOTAL`** - The response includes only the aggregate ConsumedCapacity for the operation.
        **`NONE`** - No ConsumedCapacity details are included in the response.

```
aws dynamodb get-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}' \
    --consistent-read \
    --projection-expression "Actor, PostedBy" \
    --return-consumed-capacity TOTAL
```

- This request consume 1.0 RCU, because this item is less than 4KB and it is a strong consistent read.
- It projects the attribute names along with their attribute values


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qyjltbl3l1xee0s6do36.png)


- If we run the command again but remove the **`--consistent-read`** option, we will see that eventually consistent reads consume half as much capacity
- - It projects the attribute names along with their attribute values

```
aws dynamodb get-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}' \
    --projection-expression "Actor, PostedBy" \
    --return-consumed-capacity TOTAL
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9vj5hgp6mw8r4yvyli5.png)



## 3. Update an item

**UpdateItem** - Creates a new item or to replace existing items completely with a new item. 

- You have to specify the full Primary Key that you want to update.

- Also have to provide an update expression, indicating the attributes that you want to modify and the values that you want to assign to them. 

- and can selectively modify specific attributes without changing others.

- It consists of one or more clauses. 



      - Each clause begins with a word



          **`SET`** - Adds one or more attributes to an item. If any of these attributes already exists, they are overwritten by the new values. 

          **`REMOVE`** - Removes one or more attributes from an item.

          **`ADD`** - Adds a new attribute and its values to an item.

          **`DELETE`** - Removes one or more elements from a set. 


- I am going to show you 2 actions - **`SET`** and **`REMOVE`**


**First** get the item you want to update

```
aws dynamodb get-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}'
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aa5i3tccu05tlg6uw1d0.png)


- We see that there is a **`List attribute called Songs`**
- It has two songs already, **`Song 1`** and **`Song 2`**. 
- I am going to use the **`list_append()`** function in the **`UpdateExpression`** to add the Songs - **`Song 3`** and **`Song 4`** to the same list.



```
aws dynamodb update-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}' \
    --update-expression "SET #Songs = list_append(#Songs, :values)" \
    --expression-attribute-names '{"#Songs": "Songs"}' \
    --expression-attribute-values '{
        ":values" : {"L": [{"S" : "Song 3"}, {"S" : "Song 4"}]}
    }' \
    --return-consumed-capacity TOTAL
```

- get the same item that you have updated just now

- Song 3 and Song 4 are added to the item



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hb3xmouucixq1swgixwx.png)


**Now** - We will **REMOVE** those two songs entries

- Because it is a list item, we have to reference the index number in the list. 

- DynamoDB lists are 0-based, which means the 3rd and 4th elements we just added are list indexes 2 and 3. 

- To remove them, we can use this command:


```
aws dynamodb update-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}' \
    --update-expression "REMOVE #Songs[2], #Songs[3]" \
    --expression-attribute-names '{"#Songs": "Songs"}' \
    --return-consumed-capacity TOTAL
```

- get the same item that you have updated just now

- Song 3 and Song 4 have been removed from the item


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cr6xn5gzihp9dxxnxu0.png)





## 4. Delete an item

**Deleteitem** is always single operation.

-  There is no single command you can run that would delete all the rows in the table for example.

- You have to reference the full Primary Key and Sort key if the table has a composite Primary key.

- It’s safe to delete the same item more than once. 

- You can run the same command above as many times as you want and it won’t report an error; if the key doesn’t exist then the DeleteItem still returns success.


- We will delete the same item you got for the previous operations

```
aws dynamodb get-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}'
```

```
aws dynamodb delete-item \
    --table-name Movies \
    --key '{"Title":{"S":"Abhimaan"},
            "Review": {"S": "Too Good"}}'
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uut06ustveigekcj13vc.png)


- The Table **`Movies`** now has 2 items


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdr6rbddh4qqj4n410zx.png)



# Cleanup

```
aws dynamodb delete-table --table-name Movies
```


# What we have done so far

We have successfully demonstrated the Data Pane (read-write) operations, such us Create, Read, Update and Delete (CRUD) on DynamoDB items, using expressions and conditional expressions.