# Save data to DynamoDB

Setup a DynamoDB database, taking Mac OSX for instance:

$ brew install dynamodb-local

$ dynamodb-local
1
2
3

Initiate the DynamoDB table:

1). Create table definition file "mqtt_msg.json" for DynamoDB:

{
    "TableName": "mqtt_msg",
    "KeySchema": [
        { "AttributeName": "msgid", "KeyType": "HASH" }
    ],
    "AttributeDefinitions": [
        { "AttributeName": "msgid", "AttributeType": "S" }
    ],
    "ProvisionedThroughput": {
        "ReadCapacityUnits": 5,
        "WriteCapacityUnits": 5
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

2). Create the DynamoDB table:

$aws dynamodb create-table --cli-input-json file://mqtt_msg.json --endpoint-url http://localhost:8000
1

Create a rule:

Go to EMQ X Dashboard (opens new window), select the "rule" tab on the menu to the left.

Select "message.publish", then type in the following SQL:

SELECT
     msgid as id, topic, payload
    FROM
      "message.pubish"
1
2
3
4

image

Bind an action:

Click on the "+ Add" button under "Action Handler", and then select "Data to DynamoDB" in the pop-up dialog window.

image

Fill in the parameters required by the action:

Four parameters is required by action "Data to DynamoDB":

1). DynamoDB Table. Here set it to "mqtt_msg".

2). Hash Key. Here set it to "msgid".

3). DynamoDB Range Key. Leave it empty as we didn't define a range key in the dynamodb definition file.

image

4). Bind a resource to the action. Since the dropdown list "Resource" is empty for now, we create a new resource by clicking on the "New Resource" to the top right, and then select "DynamoDB":

image

Configure the resource:

Fill in the configs as following:

And then click on the "Create" button.

image

Back to the "Actions" dialog, and then click on the "Confirm" button.

image

Back to the creating rule page, then click on "Create" button. The rule we created will be show in the rule list:

image

We have finished, testing the rule by sending an MQTT message to emqx:

> Topic: "t/a"
>
> QoS: 1
>
> Payload: "hello"
1
2
3
4
5

Then inspect the DynamoDB table, verify a new record has been inserted:

image

And from the rule list, verify that the "Matched" column has increased to 1:

image