如何在 Cassandra 中正确配置和执行 BatchStatement?

How do I configure and execute BatchStatement in Cassandra correctly?

在我的 Python (3.8) 应用程序中,我向 Cassandra 数据库通过 DataStax Python Driver 3.24.

根据官方文档,我尝试通过 BatchStatement 通过单个查询执行多个 CQL 操作。不幸的是,我的代码导致了以下内容的错误:

"errorMessage": "retry_policy should implement cassandra.policies.RetryPolicy"
"errorType": "ValueError"

正如您从我的代码中看到的那样,我在 BatchStatement 中设置了 reply_policy 属性的值。无论如何,我的代码引发了您在上面看到的错误。 reply_policy属性里面必须有什么样的值?目前冲突的原因是什么?

代码段:

from cassandra.cluster import Cluster, ExecutionProfile, EXEC_PROFILE_DEFAULT
from cassandra.auth import PlainTextAuthProvider
from cassandra.policies import DCAwareRoundRobinPolicy
from cassandra import ConsistencyLevel
from cassandra.query import dict_factory
from cassandra.query import BatchStatement, SimpleStatement
from cassandra.policies import RetryPolicy


auth_provider = PlainTextAuthProvider(username=db_username, password=db_password)
default_profile = ExecutionProfile(
   load_balancing_policy=DCAwareRoundRobinPolicy(local_dc=db_local_dc),
   consistency_level=ConsistencyLevel.LOCAL_QUORUM,
   request_timeout=60,
   row_factory=dict_factory
)
cluster = Cluster(
   db_host,
   auth_provider=auth_provider,
   port=db_port,
   protocol_version=4,
   connect_timeout=60,
   idle_heartbeat_interval=0,
   execution_profiles={EXEC_PROFILE_DEFAULT: default_profile}
)
session = cluster.connect()

name_1, name_2, name_3  = "Bob", "Jack", "Alex"
age_1, age_2, age_3 = 25, 30, 18

cql_statement = "INSERT INTO users (name, age) VALUES (%s, %s)"

batch = BatchStatement(retry_policy=RetryPolicy)
batch.add(SimpleStatement(cql_statement, (name_1, age_1)))
batch.add(SimpleStatement(cql_statement, (name_2, age_2)))
batch.add(SimpleStatement(cql_statement, (name_3, age_3)))
session.execute(batch)

嗯,终于找到错误了

我从 BatchStatement 中删除了 retry_policy 属性。然后我的错误是我将 CQL 参数放在 SimpleStatement.

这是工作示例代码片段:

...
batch = BatchStatement(batch_type=BatchType.UNLOGGED)
batch.add(SimpleStatement(cql_statement), (name_1, age_1))
batch.add(SimpleStatement(cql_statement), (name_2, age_2))
batch.add(SimpleStatement(cql_statement), (name_3, age_3))
session.execute(batch)

已编辑:

因此,我在post底部留下评论后放弃了BatchStatement。我求求你注意他们! CQL 批次与 RBDMS 批次不同。 CQL 批处理不是优化,而是用于实现跨多个表的非规范化记录的原子更新。