zoukankan      html  css  js  c++  java
  • 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))
  • 相关阅读:
    __x__(10)0906第三天__字符实体(转义字符)
    __x__(9)0906第三天__常见的标签
    __x__(8)0906第三天__乱码问题
    广工校赛——小明在工作
    广工校赛——01串也疯狂之光棍也有伴
    POJ2488——DFS——A Knight's Journey
    josephus问题
    链表(排序和删除)
    Buy Tickets
    敌兵布阵
  • 原文地址:https://www.cnblogs.com/gaogao67/p/10428498.html
Copyright © 2011-2022 走看看