Save data to Cassandra

Setup a Cassandra database, and changes the root/password to root/public, taking Mac OSX for instance:

  1. $ brew install cassandra
  2. ## change the config file to enable authentication
  3. $ vim /usr/local/etc/cassandra/cassandra.yaml
  4. authenticator: PasswordAuthenticator
  5. authorizer: CassandraAuthorizer
  6. $ brew services start cassandra
  7. ## login to cql shell and then create the root user
  8. $ cqlsh -ucassandra -pcassandra
  9. cassandra@cqlsh> create user root with password 'public' superuser;

Initiate Cassandra Table:

  1. $ cqlsh -uroot -ppublic

Create Keyspace “test”:

  1. CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;

Create “t_mqtt_msg” table:

  1. USE test;
  2. CREATE TABLE t_mqtt_msg (
  3. msgid text,
  4. topic text,
  5. qos int,
  6. payload blob,
  7. retain int,
  8. arrived timestamp,
  9. PRIMARY KEY (msgid, topic)
  10. );

Create a rule:

Go to EMQX DashboardSave data to Cassandra - 图1 (opens new window), select the “rule” tab on the menu to the left.

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

  1. SELECT
  2. *
  3. FROM
  4. "message.publish"

image

Bind an action:

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

image

Fill in the parameters required by the action:

Two parameters is required by action “Data to Cassandra”:

1). SQL template. SQL template is the sql command you’d like to run when the action is triggered. In this example we’ll insert a message into Cassandra, so type in the following sql template:

  1. insert into t_mqtt_msg(msgid, topic, qos, payload, retain, arrived) values (${id}, ${topic}, ${qos}, ${payload}, ${retain}, ${timestamp})

Before data is inserted into the table, placeholders like ${key} will be replaced by the corresponding values.

image

2). 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 “Cassandra”:

image

Configure the resource:

Set “Cassandra Keyspace” to “test”, “Cassandra Username” to “root”, “Cassandra Password” to “public”, and keep all other configs as default, and click on the “Testing Connection” button to make sure the connection can be created successfully.

image

Then click on the “Create” button.

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:

  1. > Topic: "t/cass"
  2. > QoS: 1
  3. > Retained: true
  4. > Payload: "hello"

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

image

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

image