【问题标题】:Insert to cassandra from python using cql使用 cql 从 python 插入到 cassandra
【发布时间】:2012-10-24 10:08:41
【问题描述】:

我打算将数据插入到具有复合键的波纹管 CF 中。

CREATE TABLE event_attend (
    event_id int,
    event_type varchar,
    event_user_id int,
    PRIMARY KEY (event_id, event_type)    #compound keys...
);

但是我不能使用 cql 从 python 向这个 CF 插入数据。 (http://code.google.com/a/apache-extras.org/p/cassandra-dbapi2/)

import cql
connection = cql.connect(host, port, keyspace)
cursor = connection.cursor()
cursor.execute("INSERT INTO event_attend (event_id, event_type, event_user_id) VALUES (1, 'test', 2)", dict({}) )

我得到以下回溯:

Traceback (most recent call last):
File "./v2_initial.py", line 153, in <module>
  db2cass.execute()
File "./v2_initial.py", line 134, in execute
  cscursor.execute("insert into event_attend (event_id, event_type, event_user_id ) values (1, 'test', 2)", dict({}))
File "/usr/local/pythonbrew/pythons/Python-2.7.2/lib/python2.7/site-packages/cql-1.4.0-py2.7.egg/cql/cursor.py", line 80, in execute
  response = self.get_response(prepared_q, cl)
File "/usr/local/pythonbrew/pythons/Python-2.7.2/lib/python2.7/site-packages/cql-1.4.0-py2.7.egg/cql/thrifteries.py", line 80, in get_response
  return self.handle_cql_execution_errors(doquery, compressed_q, compress)
File "/usr/local/pythonbrew/pythons/Python-2.7.2/lib/python2.7/site-packages/cql-1.4.0-py2.7.egg/cql/thrifteries.py", line 98, in handle_cql_execution_errors
  raise cql.ProgrammingError("Bad Request: %s" % ire.why)
cql.apivalues.ProgrammingError: Bad Request: unable to make int from 'event_user_id'

我做错了什么?

【问题讨论】:

    标签: python cassandra cql


    【解决方案1】:

    您似乎正在尝试遵循以下示例: http://pypi.python.org/pypi/cql/1.4.0

    import cql
    con = cql.connect(host, port, keyspace)
    cursor = con.cursor()
    cursor.execute("CQL QUERY", dict(kw='Foo', kw2='Bar', kwn='etc...'))
    

    但是,如果您只需要插入一行(如在您的问题中),只需删除空的 dict() 参数。

    另外,由于您使用的是复合键,请确保您使用 CQL3 http://www.datastax.com/dev/blog/whats-new-in-cql-3-0

    connection = cql.connect('localhost:9160', cql_version='3.0.0')
    

    以下代码应该可以工作(如果需要,只需将其调整为 localhost):

    import cql
    con = cql.connect('172.24.24.24', 9160,  keyspace, cql_version='3.0.0')
    print ("Connected!")
    cursor = con.cursor()
    CQLString = "INSERT INTO event_attend (event_id, event_type, event_user_id) VALUES (131, 'Party', 3156);"
    cursor.execute(CQLString)
    

    【讨论】:

    • 谢谢奥伦。我试图编辑我的代码并执行,所以它成功了!
    • 有没有办法使用相同的方式批量上传数据?
    【解决方案2】:

    对于python 2.7、3.3、3.4、3.5和3.6的安装,你可以使用

         $ pip install cassandra-driver
    

    在python中:

         import cassandra
    

    文档可以在https://datastax.github.io/python-driver/getting_started.html#passing-parameters-to-cql-queries下找到

    【讨论】:

    • 很抱歉,您的回答没有回答问题
    猜你喜欢
    • 1970-01-01
    • 2012-02-26
    • 2014-05-10
    • 2019-01-27
    • 2013-05-22
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多