Cassandra Python 使用 python 驱动器从字符串执行多条语句?

问题描述

我想使用 python driver 执行多个 cql 语句(2 个或更多)。

我尝试了这样简单的代码,但如果查询包含多个语句,则会导致错误。我不想拆分语句或格式化它(到单个语句)。我只想执行整个 CQL。

如何使用 Cassandra 的 python 驱动程序来实现 - 有可能吗?

我使用 ; 作为语句拆分。

from cassandra.cluster import Cluster


def main():
    cluster = Cluster(contact_points=['cassandra-1.','cassandra-2.','cassandra-3.','cassandra-4.'])
    session = cluster.connect()
    session.execute('drop keyspace if exists test')
    session.execute('''
        create keyspace test
        with durable_writes = true
        and replication = {
            'class' : 'SimpleStrategy','replication_factor' : 3
        };    
    ''')
    session.set_keyspace('test')

    # two statements or more and there is error
    # how to execute all in one call?
    query = '''\
    create table x1 (
        name text,primary key ((name))
    );

    create table x2 (
        name text,primary key ((name))
    );
    '''

    result_set = session.execute(query)
    print(result_set)


if __name__ == '__main__':
    main()

它产生这样的错误

Traceback (most recent call last):
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandBox\cassandra_scheme\04_execute_multiple_statements.py",line 39,in <module>
    main()
  File "C:\Users\Cezary Wagner\PycharmProjects\medptr-v2\sandBox\cassandra_scheme\04_execute_multiple_statements.py",line 34,in main
    result_set = session.execute(query)
  File "cassandra\cluster.py",line 2618,in cassandra.cluster.Session.execute
  File "cassandra\cluster.py",line 4894,in cassandra.cluster.ResponseFuture.result
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 7:4 mismatched input 'create' expecting EOF (... ((name))    );    [create]...)">

解决方法

每个语句都应该是单独的。只需使用您的 Python 代码在 ; 上拆分文本,然后单独执行它们。此外,请考虑到像您这样的程序化架构修改具有潜在危险 - 您可能会遇到所谓的架构分歧,需要通过滚动重启集群来修复它。