我正在尝试针对Cassandra表运行准备好的选择查询。
该表定义如下:
class EmailAddressLookup(Model, ModelOperations, JSONSerializer):
__table_name__ = 'email_address_lookup'
email_address = columns.Text(primary_key=True)
user_id = columns.Integer(primary_key=True)
我的INSERT很棒。它看起来像这样:
i_email_lookup = session.prepare("""INSERT INTO email_address_lookup (user_id, email_address) VALUES (?, ?)""")
session.execute(i_email_lookup, (user_id, email_address))
但是,我的SELECT无效。它看起来像这样:
s_email_lookup_by_email = session.prepare('SELECT user_id FROM email_address_lookup WHERE "email_address"=?')
session.execute(s_email_lookup_by_email, email_address)
这是email_address是27-char字符串时的追溯:
Traceback (most recent call last):
File "/home/thisguy/Documents/my_proj/api/models/case.py", line 428, in _lookup_usin_email
matches = my_projcluster.select_email_lookup_by_email(self.email)
File "/home/thisguy/Documents/my_proj/api/utils/decorators.py", line 14, in newfunc
result = func(*args, **kwargs)
File "/home/thisguy/Documents/my_proj/api/models/my_projcluster.py", line 203, in select_email_lookup_by_email
session.execute(s_email_lookup_by_email, (email_address))
File "/home/thisguy/.Envs/my_proj/lib/python3.4/site-packages/cassandra/cluster.py", line 1403, in execute
future = self.execute_async(query, parameters, trace)
File "/home/thisguy/.Envs/my_proj/lib/python3.4/site-packages/cassandra/cluster.py", line 1452, in execute_async
future = self._create_response_future(query, parameters, trace)
File "/home/thisguy/.Envs/my_proj/lib/python3.4/site-packages/cassandra/cluster.py", line 1464, in _create_response_future
query = query.bind(parameters)
File "/home/thisguy/.Envs/my_proj/lib/python3.4/site-packages/cassandra/query.py", line 390, in bind
return BoundStatement(self).bind(values)
File "/home/thisguy/.Envs/my_proj/lib/python3.4/site-packages/cassandra/query.py", line 486, in bind
(len(values), len(col_meta)))
ValueError: Too many arguments provided to bind() (got 27, expected 1)
好的,所以Python试图将27个字符串变成27个args?让我们把它包装成一个元组:
session.execute(s_email_lookup_by_email, (email_address, ))
这可以防止回溯,但即使数据库中确实有匹配的电子邮件地址,查询也会返回None。
答案 0 :(得分:8)
此:
session.execute(s_email_lookup_by_email, (email_address))
并没有真正将1元组传递给execute
方法。
在python中,要创建一个1元组,你需要用逗号跟随第一个元素:
session.execute(s_email_lookup_by_email, (email_address,))
否则括号被解释为分组运算符,这使得(email_address)
等同于email_address
而没有括号。