首页 > 解决方案 > Cassandra - 更新集类型列

问题描述

我们在 cassandra 中有一个表,其结构如下:

cities_in_state(state TEXT, zip TEXT, cities SET<TEXT>, PRIMARY KEY ((zip, 
state)))

我需要使用 java 驱动程序为该州更新城市的值,有以下代码:

BoundStatement bound = session().prepare("UPDATE cities_in_state SET cities 
= cities + ? WHERE zip = ? and state = ?").bind();
bound.setSet(1, cities);
bound.setString(2, "ZIP1");
bound.setString(3, "state1");

这会出现“HashSet 无法转换为字符串”之类的错误,而且我应该始终需要向现有城市添加更多城市。那么我将如何在 cassandra 中使用绑定参数附加 set 列。

标签: collectionscassandradatastax

解决方案


以下代码工作得很好:

PreparedStatement prepared = session.prepare("UPDATE test.st SET cities = cities + ? WHERE zip = ? and state = ?");
BoundStatement bound = prepared.bind(Collections.singleton("t2"), "2", "1");
session.execute(bound);

您的问题是您从 1 开始计数,而 Java 驱动程序使用基于 0 的索引。以下代码可以找到我是否将每个索引都减 1:

BoundStatement bound2 = prepared.bind();
bound2.setSet(0, Collections.singleton("t3"));
bound2.setString(1, "2");
bound2.setString(2, "1");
session.execute(bound2);

推荐阅读