Cassandra:更新或插入地图值以及其他值
Cassandra: update or insert map value together with other values
我有一个 table 看起来像这样:
(id, a, b, mapValue)
如果存在则更新,如果不存在则插入VALUES(id,a,b,mapValue)
。其中 mapValue 是旧 mapValue 与新 mapValue 的组合,替换了已经存在的每个键的值。
例如,如果旧的 mapValue 是 {1:c, 2:d}
而新的是 {2:e, 3:f}
,则结果将是 {1:c, 2:e, 3:f}
。
我想在 updates/inserts id,a,b
in VALUES(id,a,b,mapValue)
.
的查询中执行此操作
我怎样才能做到这一点?
我找到了 this 关于更新地图的指南,但它没有说明在处理 table 中的其他值时更新它们。我需要同时做这个。
在 Cassandra 中,INSERT 和 UPDATE 之间没有区别 - 一切都是 UPSERT,所以当你 UPDATE
并且数据不存在时,它被插入。或者如果您这样做 INSERT
并且数据已经存在,它将被更新。
关于地图的更新,可以在做UPDATE
的时候对相应的列进行+
和-
操作。例如,我有一个 table:
CREATE TABLE test.m1 (
id int PRIMARY KEY,
i int,
m map<int, text>
);
我可以执行以下操作来更新现有行:
cqlsh:test> insert into test.m1 (id, i, m) values (1, 1, {1:'t1'});
cqlsh:test> select * from test.m1;
id | i | m
----+---+-----------
1 | 1 | {1: 't1'}
(1 rows)
cqlsh:test> update test.m1 set m = m + {2:'t2'}, i = 4 where id = 1;
cqlsh:test> select * from test.m1;
id | i | m
----+---+--------------------
1 | 4 | {1: 't1', 2: 't2'}
(1 rows)
我可以使用类似的 UPDATE
命令来插入全新的数据:
cqlsh:test> update test.m1 set m = m + {6:'t6'}, i = 6 where id = 6;
cqlsh:test> select * from test.m1;
id | i | m
----+---+--------------------
1 | 4 | {1: 't1', 2: 't2'}
6 | 6 | {6: 't6'}
(2 rows)
通常,如果您知道给定主键之前不存在数据,那么 UPDATE
和 +
是将数据插入 set
或 map
的更好方法因为它不会生成当您在集合列上执行 INSERT
或 UPDATE
而没有 +
时生成的墓碑。
P.S。您可以在 following document.
中找到有关使用集合的更多信息
我有一个 table 看起来像这样:
(id, a, b, mapValue)
如果存在则更新,如果不存在则插入VALUES(id,a,b,mapValue)
。其中 mapValue 是旧 mapValue 与新 mapValue 的组合,替换了已经存在的每个键的值。
例如,如果旧的 mapValue 是 {1:c, 2:d}
而新的是 {2:e, 3:f}
,则结果将是 {1:c, 2:e, 3:f}
。
我想在 updates/inserts id,a,b
in VALUES(id,a,b,mapValue)
.
我怎样才能做到这一点? 我找到了 this 关于更新地图的指南,但它没有说明在处理 table 中的其他值时更新它们。我需要同时做这个。
在 Cassandra 中,INSERT 和 UPDATE 之间没有区别 - 一切都是 UPSERT,所以当你 UPDATE
并且数据不存在时,它被插入。或者如果您这样做 INSERT
并且数据已经存在,它将被更新。
关于地图的更新,可以在做UPDATE
的时候对相应的列进行+
和-
操作。例如,我有一个 table:
CREATE TABLE test.m1 (
id int PRIMARY KEY,
i int,
m map<int, text>
);
我可以执行以下操作来更新现有行:
cqlsh:test> insert into test.m1 (id, i, m) values (1, 1, {1:'t1'});
cqlsh:test> select * from test.m1;
id | i | m
----+---+-----------
1 | 1 | {1: 't1'}
(1 rows)
cqlsh:test> update test.m1 set m = m + {2:'t2'}, i = 4 where id = 1;
cqlsh:test> select * from test.m1;
id | i | m
----+---+--------------------
1 | 4 | {1: 't1', 2: 't2'}
(1 rows)
我可以使用类似的 UPDATE
命令来插入全新的数据:
cqlsh:test> update test.m1 set m = m + {6:'t6'}, i = 6 where id = 6;
cqlsh:test> select * from test.m1;
id | i | m
----+---+--------------------
1 | 4 | {1: 't1', 2: 't2'}
6 | 6 | {6: 't6'}
(2 rows)
通常,如果您知道给定主键之前不存在数据,那么 UPDATE
和 +
是将数据插入 set
或 map
的更好方法因为它不会生成当您在集合列上执行 INSERT
或 UPDATE
而没有 +
时生成的墓碑。
P.S。您可以在 following document.
中找到有关使用集合的更多信息