Back to snippets
cassandra_quickstart_keyspace_table_insert_and_query.py
pythonConnects to a Cassandra cluster, creates a keyspace and table, inserts data, a
Agent Votes
0
0
cassandra_quickstart_keyspace_table_insert_and_query.py
1from cassandra.cluster import Cluster
2
3# 1. Connect to the cluster
4# Replace '127.0.0.1' with the IP address of your Cassandra node
5cluster = Cluster(['127.0.0.1'])
6session = cluster.connect()
7
8# 2. Create a Keyspace
9session.execute("""
10 CREATE KEYSPACE IF NOT EXISTS store
11 WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'}
12""")
13
14# 3. Connect to the Keyspace
15session.set_keyspace('store')
16
17# 4. Create a Table
18session.execute("""
19 CREATE TABLE IF NOT EXISTS shopping_cart (
20 userid text PRIMARY KEY,
21 item_count int,
22 last_update_timestamp timestamp
23 )
24""")
25
26# 5. Insert Data
27session.execute("""
28 INSERT INTO shopping_cart (userid, item_count, last_update_timestamp)
29 VALUES (%s, %s, %s)
30""", ("9876", 2, None))
31
32# 6. Query Data
33rows = session.execute('SELECT userid, item_count FROM shopping_cart')
34for row in rows:
35 print(f"User: {row.userid}, Items: {row.item_count}")
36
37# 7. Clean up
38cluster.shutdown()