cassandra相关操作

用法示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# -*- coding: utf-8 -*-

from cassandra.auth import PlainTextProvider
from cassandra.cluster import Cluster
from cassandra.cqlengine import columns, connection
from cassandra.cqlengine.models import Model
from cassandra.query import dict_factory

hosts = ["192.168.10.10", "192.168.10.11"]
username = "username"
password = "password"
port = 9042
keyspace = "mykeyspace"

auth_provider = PlainTextProvider(username=username, password=password)
cluser_conf_dict = dict(port=port, auth_provider=auth_provider)
connection.setup(hosts, keyspace, **cluser_conf_dict)
cluster = connection.get_cluster()
session = connection.get_session()

session.set_keyspace(keyspace)
session.default_fetch_size = 10000
session.default_timeout = 120


class ExapleModel(Models):
partition_1 = columns.Text(partition_key=True, primary_key=True)
partition_2 = columns.Text(partition_key=True, primary_key=True)
primary_1 = columns.Text(primary_key=True)
primary_2 = columns.Text(primary_key=True)
str_type = columns.Text()
boolean_type = columns.Boolean()
int_type = columns.Integer()
bigint_type = columns.BigInt()
float_type = columns.Float()
datatime_type = columns.DataTime()
list_str_type = columns.List(columns.Text)
set_str_type = columns.Set(columns.Text)
set_int_type = columns.Set(columns.Integer)
set_bigint_type = columns.Set(columns.Bigint)
map_type = columns.Map(columns.Text, columns.Float)

# create db statement
CREATE TABLE mykeyspace.examplemodel (
partition_1 text,
partition_2 text,
primary_1 text,
primary_2 text,
str_type text,
boolean_type boolea,
int_type int,
bigint_type bigint,
float_type float,
datatime_type timestamp,
list_str_type list<text>,
set_str_type set<text>,
set_int_type set<int>,
set_bigint_type set<bigint>,
map_type map<text, float>,
PRIMARY KEY((partition_1, partition_2), primary_1, primary_2)
) WITH CLUSTERING ORDER BY (primary_1 ASC, primary_2 ASC)
AND gc_grace_seconds = 0;

def connect_db(hosts, username, password, port, keyspace, timeout=120, default_size=10000):
auth_provider = PlainTextProvider(username=username, password=password)
cluster = Cluster(contact_points=hosts, port=port, auth_provider=auth_provider)
session = cluster.connect(keyspace)

# set session
session.default_fetch_size = default_size
session.default_timeout = timeout
session.row_factory = dict_factory
return cluster, session

def close_db(cluster, session):
session.shutdown()
cluster.shutdown()

def exec_sql(sql, **kwargs):
try:
cluster, session =connect_db(hosts, username, password, port, keyspace)
future = session.execute(sql, kwargs)
close_db(cluster, session)
except Execption as e:
close_db(cluster, session)
future = []
return future
-------------本文结束感谢您的阅读-------------