我创建了一个像这样的 cassandra 数据库:
cqlsh:timeseries> describe keyspace timeseries;
CREATE KEYSPACE timeseries WITH replication = {
'class': 'SimpleStrategy',
'replication_factor': '1'
};
USE timeseries;
CREATE TABLE option_data (
ts timestamp,
ask decimal,
bid decimal,
expiry timestamp,
id text,
strike decimal,
symbol text,
PRIMARY KEY ((ts))
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.100000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='99.0PERCENTILE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
CREATE TABLE underlying_data (
symbol text,
ask decimal,
bid decimal,
ts bigint,
PRIMARY KEY ((symbol))
) WITH
bloom_filter_fp_chance=0.010000 AND
caching='KEYS_ONLY' AND
comment='' AND
dclocal_read_repair_chance=0.100000 AND
gc_grace_seconds=864000 AND
index_interval=128 AND
read_repair_chance=0.000000 AND
replicate_on_write='true' AND
populate_io_cache_on_flush='false' AND
default_time_to_live=0 AND
speculative_retry='99.0PERCENTILE' AND
memtable_flush_period_in_ms=0 AND
compaction={'class': 'SizeTieredCompactionStrategy'} AND
compression={'sstable_compression': 'LZ4Compressor'};
CREATE INDEX underlying_data_ts_idx ON underlying_data (ts);
cqlsh:timeseries>
我有一个 C# 函数:
public void InsertUnderlying(long timestamp, string symbol, decimal bid, decimal ask)
{
var batchStmt = new BatchStatement();
var v2Insert = new SimpleStatement("insert into underlying_data " +
"(ts, symbol, bid, ask) values(?, ?, ?, ?);");
batchStmt.Add(v2Insert.Bind(timestamp, symbol, bid, ask));
session.Execute(batchStmt);
}
我实时调用这个函数来添加数据。但是,当我从 CQL 执行查询时,
cqlsh:timeseries> select * from underlying_data;
尽管我多次调用此函数,但我只看到一行。不确定如何附加数据而不是覆盖它?
最佳答案
在 Cassandra 中,主键是唯一的。您的表 underlying_data
仅在 symbol
列上键入:
PRIMARY KEY ((symbol))
这意味着特定符号的所有插入都将相互覆盖:
INSERT INTO underlying_data (symbol, ts, ask, bid) VALUES ('SPX',1412102636,3.1,4.0);
INSERT INTO underlying_data (symbol, ts, ask, bid) VALUES ('SPX',1412102708,3.0,4.4);
INSERT INTO underlying_data (symbol, ts, ask, bid) VALUES ('SPX',1412102731,2.1,5.0);
SELECT * FROM underlying_data;
symbol | ts | ask | bid
--------+------------+-----+-----
SPX | 1412102731 | 2.1 | 5.0
要存储每个 INSERT
,请将 ts
添加到主键定义中:
PRIMARY KEY (symbol, ts)
此外,Cassandra 不区分 INSERT
和 UPDATE
(本质上是“UPSERT”)。虽然语法不同,但它们都完成相同的任务:存储特定键的列值。这意味着您可以使用 UPDATE
插入新记录,也可以使用 INSERT
更新现有记录。 Ike Walker 有一篇很好的博客文章描述了这一点:How to do an Upsert in Cassandra .
关于c# - Cassandra C# insert 似乎正在删除先前的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26126268/