Cassandra with the Python driver
Uses cassandra-driver 3.30. The code is an ordinary application for the original database; nothing in it knows about MachNoSQL.
The only change
Section titled “The only change”cass-1.example.com,cass-2.example.commachnosql-1.example.com,machnosql-2.example.comThe address comes from the environment variable CASSANDRA_CONTACT_POINTS, so switching to MachNoSQL changes configuration only.
export CASSANDRA_CONTACT_POINTS='machnosql-1.example.com,machnosql-2.example.com'pip install -r requirements.txtpython app.pyCredentials come from CASSANDRA_USERNAME and CASSANDRA_PASSWORD, the local data center from CASSANDRA_DC (default dc1).
Source
Section titled “Source”The program as it is kept and tested in the Mach Database NoSQL repository; highlighted lines read the connection setting.
"""Sensor readings on Cassandra, unchanged on MachNoSQL."""
import osfrom datetime import datetime, timedelta, timezone
from cassandra.auth import PlainTextAuthProviderfrom cassandra.cluster import Clusterfrom cassandra.policies import DCAwareRoundRobinPolicy, TokenAwarePolicy
cluster = Cluster( contact_points=os.environ["CASSANDRA_CONTACT_POINTS"].split(","), port=9042, auth_provider=PlainTextAuthProvider(os.environ["CASSANDRA_USERNAME"], os.environ["CASSANDRA_PASSWORD"]), load_balancing_policy=TokenAwarePolicy(DCAwareRoundRobinPolicy(local_dc=os.environ.get("CASSANDRA_DC", "dc1"))), protocol_version=5,)session = cluster.connect()
session.execute( "CREATE KEYSPACE IF NOT EXISTS iot WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': 3}")session.execute( "CREATE TABLE IF NOT EXISTS iot.readings (sensor text, at timestamp, value double, " "PRIMARY KEY (sensor, at)) WITH CLUSTERING ORDER BY (at DESC)")session.execute("CREATE TABLE IF NOT EXISTS iot.sensors (sensor text PRIMARY KEY, owner text)")
insert = session.prepare("INSERT INTO iot.readings (sensor, at, value) VALUES (?, ?, ?) USING TTL 86400")now = datetime.now(timezone.utc)for minute in range(10): session.execute(insert, ("s-1", now - timedelta(minutes=minute), 20.0 + minute / 10))
rows = session.execute( "SELECT at, value FROM iot.readings WHERE sensor = %s AND at > %s LIMIT 5", ("s-1", now - timedelta(minutes=5)),)for row in rows: print(row.at, row.value)
applied = session.execute( "INSERT INTO iot.sensors (sensor, owner) VALUES (%s, %s) IF NOT EXISTS", ("s-1", "ada")).was_appliedprint("registered:", applied)
cluster.shutdown()cassandra-driver==3.30.1