用pythondri在Cassandra中插入元组字段

2024-10-03 00:25:11 发布

您现在位置:Python中文网/ 问答频道 /正文

各位

我在通过DataStax提供的python-driver将数据插入Cassandra表的元组值字段时遇到了一个问题。在

要么我不知道如何正确地将tuple参数传递给Session.execute命令,要么驱动程序在内部以错误的方式转换元组,当将它发送到Cassandra时-因为相同的插入在cqlsh会话中执行时效果良好。在

一个不涉及元组,而是一个列表的等价插入,在代码和cqlsh中都能很好地工作。在

我使用的是python2.7.10和cassandradriver 3.7.1。在Python执行过程中出现的错误是InvalidRequest: Error from server: code=2200 [Invalid query] message="Invalid list literal for tuplefield of type frozen<tuple<int, int, int>>"。在

我粘贴下面一个最小的工作代码,复制我看到的问题。有人能帮我弄清楚我是不是做错了什么事?在

(注意:我已经尝试过将一个普通列表传递给Session.execute来代替元组参数,但也没有成功。)

非常感谢。在

'''
    Run with:
        python 2.7.10
        cassandra-driver==3.7.1 installed
'''

from cassandra.cluster import Cluster

if __name__=='__main__':

    serverAddress='SERVER_ADDRESS'
    keyspacename='tupletests'
    tablecreation='''create table tabletest (
                            rowid int,
                            tuplefield tuple < int, int, int >,
                            listfield list < int >,
                        primary key (rowid)
                    );'''

    # connect and create keyspace
    clu=Cluster([serverAddress])
    session=clu.connect()
    session.execute("create keyspace %s with replication = \
        {'class': 'SimpleStrategy', 'replication_factor': 1};" % keyspacename)

    # use keyspace; create a sample table
    session.set_keyspace(keyspacename)
    session.execute(tablecreation)

    # insert a row with rowid,listfield
    session.execute('insert into tabletest (rowid, listfield) values (%s,%s)', \
        [999, [10,11,12]])
    # succeeds

    # insert a row with rowid,tuplefield
    session.execute('insert into tabletest (rowid, tuplefield) values (%s,%s)', \
        [111, tuple([6,5,4])])
    # raises: *** InvalidRequest: Error from server: code=2200 [Invalid query]
    # message="Invalid list literal for tuplefield of type frozen<tuple<int, int, int>>"

    # Compare with analogous statements in cqlsh, which *both* succeed:
    # List:    insert into tabletest (rowid, listfield) values (999, [21,22,23]);
    # Tuple:   insert into tabletest (rowid, tuplefield) values (765, (121,122,123));

    # delete test keyspace
    session.execute("drop keyspace %s;" % keyspacename)    
    print "Test Finished."

Tags: executesessioncreatewithint元组inserttuple
1条回答
网友
1楼 · 发布于 2024-10-03 00:25:11

好吧,我刚刚解决了这个问题。在这里为大家发布解决方案。 为了让驱动程序知道在将元组传递给Cassandra时应该如何格式化元组,如果坚持使用未准备好的语句进行插入,则必须在调用insert之前指定解析元组时使用的编码器:

session.encoder.mapping[tuple] = session.encoder.cql_encode_tuple

在这个语句之后,Session.executeinsert语句中出现的元组将自动以正确的方式转换为Cassandra,Cassandra不再抱怨。在

(据我所知,最好使用预先准备好的语句,该语句包含足够的信息,使单独指定编码器变得多余)。在

相关问题 更多 >