Cassandra Demo--Python操作cassandra
================================================================
创建keyspace和table
CREATE KEYSPACE exps WITH REPLICATION = { 'class' : 'NetworkTopologyStrategy', 'DC1' : 2 }; create table exps_user(user_id int primary key,user_name varchar,user_info text); create index idx_user_name on exps_user(user_name);
注意在创建keyspace时,数据中心的名称需要区分大小写,如果数据中心名称写错,创建keyspace和table能成功,但INSERT数据时会报错。
在cqlsh上报NoHostAvailable错误,如果使用python访问,会报下面错误:
Error from server: code=1000 [Unavailable exception] message="Cannot achieve consistency level LOCAL_ONE" info={'consistency': 'LOCAL_ONE', 'required_replicas': 1, 'alive_replicas': 0}
================================================================
需要安装python依赖包cassandra-driver:
from cassandra.cluster import Cluster from cassandra.policies import DCAwareRoundRobinPolicy from cassandra import ConsistencyLevel cluster_instances = ['192.168.199.171', '192.168.199.172', '192.168.199.173'] cluster = Cluster( cluster_instances, load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='DC1'), port=9042 ) session = cluster.connect("exps") for user_id in range(1, 50000): try: sql_script = ("insert into exps_user(user_id,user_name,user_info)" "VALUES({0},'U{0}','THIS IS TEST');").format(user_id) user_lookup_stmt = session.prepare(sql_script) user_lookup_stmt.consistency_level = ConsistencyLevel.LOCAL_ONE user1 = session.execute(user_lookup_stmt, []) except Exception as ex: print(str(ex))