GridDB时间序列容器能否存储同时间戳不同传感器数据?报错求助
GridDB单时间序列容器存储同时间戳多传感器数据问题解答
可以在单个时间序列容器中存储时间戳相同但读数不同的数据,你之前遇到报错,核心原因是主键设计不合理。
GridDB的时间序列容器如果仅将timestamp设为主键,系统会判定同时间戳的记录为重复数据,插入时触发冲突报错。但它支持复合主键,只要把**传感器唯一ID(sensor_id)+ 时间戳(timestamp)**组合作为主键,就能区分同时间戳下不同传感器的记录,实现正常存储。
具体实现示例
用SQL创建容器
CREATE TIMESERIES CONTAINER sensor_data ( sensor_id STRING, timestamp TIMESTAMP, value DOUBLE, PRIMARY KEY(sensor_id, timestamp) )
用Java API创建容器(简化版)
// 定义字段结构 List<ColumnInfo> columnInfoList = new ArrayList<>(); columnInfoList.add(new ColumnInfo("sensor_id", Type.STRING)); columnInfoList.add(new ColumnInfo("timestamp", Type.TIMESTAMP)); columnInfoList.add(new ColumnInfo("value", Type.DOUBLE)); // 设置复合主键 ContainerInfo containerInfo = new ContainerInfo("sensor_data", ContainerType.TIME_SERIES, columnInfoList); containerInfo.setPrimaryKey(Arrays.asList("sensor_id", "timestamp")); // 写入GridDB GridStore gridStore = GridStoreFactory.getGridStore(properties); gridStore.putContainer(containerInfo); gridStore.close();
注意事项
- 复合主键的两个字段缺一不可,插入数据时必须同时提供
sensor_id和timestamp,确保每条记录的主键唯一 - 主键顺序不影响唯一性,但建议把查询频率更高的字段(比如
sensor_id)放在前面,优化后续查询性能
内容的提问来源于stack exchange,提问作者Barshi
相关产品推荐
相关产品推荐

