cassandra相关操作 发表于 2019-12-15 分类于 database 用法示例123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# -*- coding: utf-8 -*-from cassandra.auth import PlainTextProviderfrom cassandra.cluster import Clusterfrom cassandra.cqlengine import columns, connectionfrom cassandra.cqlengine.models import Modelfrom cassandra.query import dict_factoryhosts = ["192.168.10.10", "192.168.10.11"]username = "username"password = "password"port = 9042keyspace = "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 = 10000session.default_timeout = 120class 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 statementCREATE 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, sessiondef 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 本文作者: Mr Wang 本文链接: https://forgetst.github.io/database/cassandra相关操作.html 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处! -------------本文结束感谢您的阅读-------------