Files
promote/ATTENTION.md
2025-03-12 23:53:36 +08:00

82 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# ClickHouse使用注意事项
## 数据插入最佳实践
### 1. 利用ClickHouse的默认值机制
在向ClickHouse插入数据时对于有默认值的字段`event_id``timestamp``date``hour`可以不用显式提供这些值让ClickHouse自动生成。这样可以
- 简化代码
- 避免格式错误
- 确保数据一致性
示例:
```typescript
// 推荐做法:不指定有默认值的字段
await clickhouse.insert({
table: 'events',
values: [{
// event_id, timestamp, date, hour 自动由ClickHouse生成
user_id: 'test-user-123',
influencer_id: 'influencer-456',
// 其他必要字段...
}],
format: 'JSONEachRow'
});
```
### 2. 避免JSON格式问题
使用`JSONEachRow`格式时,可能会遇到时间戳等特殊格式字段的解析错误:
```
Cannot parse input: expected '"' before: '.749Z","date":"2025-03-12",...
```
解决方法:
- 让ClickHouse使用默认值自动生成时间相关字段
- 如必须手动指定确保格式严格符合ClickHouse要求
### 3. 使用正确的方法
ClickHouse客户端库(@clickhouse/client)提供了多种插入数据的方法:
- **insert方法**:最适合结构化数据
```typescript
await clickhouse.insert({
table: 'table_name',
values: [{ field1: value1, field2: value2 }],
format: 'JSONEachRow'
});
```
- **query方法**适合原始SQL语句
```typescript
await clickhouse.query({
query: `INSERT INTO table_name (field1, field2) VALUES (?, ?)`,
values: [[value1, value2]]
});
```
### 4. Enum类型字段
对于Enum类型字段如`event_type`、`funnel_stage`等插入时使用定义的枚举字符串值ClickHouse会自动转换为内部数字表示
```typescript
// 正确:使用枚举字符串值
event_type: 'comment',
funnel_stage: 'consideration',
```
## 常见错误处理
1. **JSON格式错误**通常与时间戳和日期字段有关尽可能使用ClickHouse默认值
2. **枚举值错误**:确保使用表定义中的精确枚举字符串
3. **数据类型不匹配**:检查每个字段的类型是否与表定义匹配
## 性能考虑
1. 批量插入比单条插入更高效
2. 对于大批量数据,考虑使用流式插入
3. 高频小数据量插入,考虑使用异步插入方法