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

2024-06-02 15:32:31 发布

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

在我的Python3.8)应用程序中,我通过DataStax Python Driver 3.24Cassandra数据库发出请求

我有几个CQL操作,根据官方文档,我正试图通过BatchStatement通过单个查询执行这些操作。不幸的是,我的代码导致以下内容出现错误:

"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)

Tags: 代码namefromimportauthdbagebatch
1条回答
网友
1楼 · 发布于 2024-06-02 15:32:31

嗯,我终于找到了错误

我从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)

编辑:

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

相关问题 更多 >