目录
-
- 摘要
- 一、语言概述
-
- [1.1 DolphinDB脚本语言特点](#1.1 DolphinDB脚本语言特点)
- [1.2 与其他语言对比](#1.2 与其他语言对比)
- 二、变量与数据类型
-
- [2.1 变量定义](#2.1 变量定义)
- [2.2 标量类型](#2.2 标量类型)
- [2.3 向量(Vector)](#2.3 向量(Vector))
- [2.4 矩阵(Matrix)](#2.4 矩阵(Matrix))
- [2.5 字典(Dictionary)](#2.5 字典(Dictionary))
- 三、运算符
-
- [3.1 算术运算符](#3.1 算术运算符)
- [3.2 比较运算符](#3.2 比较运算符)
- [3.3 逻辑运算符](#3.3 逻辑运算符)
- [3.4 向量化运算](#3.4 向量化运算)
- 四、控制流
-
- [4.1 条件语句](#4.1 条件语句)
- [4.2 循环语句](#4.2 循环语句)
- [4.3 向量化替代循环](#4.3 向量化替代循环)
- 五、函数
-
- [5.1 内置函数](#5.1 内置函数)
- [5.2 自定义函数](#5.2 自定义函数)
- [5.3 匿名函数与高阶函数](#5.3 匿名函数与高阶函数)
- [5.4 函数应用示例](#5.4 函数应用示例)
- 六、SQL查询
-
- [6.1 基本查询](#6.1 基本查询)
- [6.2 聚合查询](#6.2 聚合查询)
- [6.3 连接查询](#6.3 连接查询)
- [6.4 窗口函数](#6.4 窗口函数)
- 七、模块化编程
-
- [7.1 模块定义](#7.1 模块定义)
- [7.2 模块使用](#7.2 模块使用)
- 八、错误处理
-
- [8.1 try-catch](#8.1 try-catch)
- [8.2 断言](#8.2 断言)
- 九、最佳实践
-
- [9.1 代码风格](#9.1 代码风格)
- [9.2 性能优化](#9.2 性能优化)
- [9.3 代码示例](#9.3 代码示例)
- 十、总结
- 参考资料
摘要
本文系统讲解DolphinDB脚本语言的核心语法和编程技巧。从变量定义、数据类型到函数定义、控制流语句,逐步带领读者掌握DolphinDB脚本编程。重点介绍向量化计算、自定义函数、模块化编程等高级特性,并提供大量工业物联网场景的代码示例。本文适合需要在DolphinDB上进行数据分析和应用开发的工程师阅读。
一、语言概述
1.1 DolphinDB脚本语言特点
DolphinDB脚本语言是一门专为数据分析设计的领域特定语言(DSL),具有以下特点:
语言特点
向量化计算
高效处理批量数据
SQL集成
脚本中直接写SQL
函数式编程
高阶函数支持
动态类型
灵活的类型系统
分布式计算
自动并行化
1.2 与其他语言对比
| 特性 | DolphinDB | Python | SQL |
|---|---|---|---|
| 向量化计算 | ✅ 原生支持 | ✅ NumPy | ❌ |
| SQL语法 | ✅ 内置 | ❌ | ✅ |
| 分布式计算 | ✅ 原生 | ⚠️ 需框架 | ⚠️ 需扩展 |
| 时序函数 | ✅ 丰富 | ⚠️ 需库 | ⚠️ 有限 |
| 学习曲线 | ⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐ |
二、变量与数据类型
2.1 变量定义
python
// 基本变量定义
a = 10 // 整数
b = 3.14 // 浮点数
c = "Hello DolphinDB" // 字符串
d = true // 布尔值
e = 2024.01.15 // 日期
f = now() // 时间戳
// 查看变量类型
typestr(a) // "INT"
typestr(b) // "DOUBLE"
typestr(c) // "STRING"
typestr(d) // "BOOL"
// 常量定义(不可修改)
def PI = 3.14159265
2.2 标量类型
| 类型 | 示例 | 说明 |
|---|---|---|
| BOOL | true, false |
布尔值 |
| CHAR | 'a', 97c |
字符 |
| SHORT | 100h |
短整数 |
| INT | 100 |
整数 |
| LONG | 100l |
长整数 |
| FLOAT | 3.14f |
单精度浮点 |
| DOUBLE | 3.14 |
双精度浮点 |
| STRING | "hello" |
字符串 |
| SYMBOL | syma` |
符号 |
| DATE | 2024.01.15 |
日期 |
| TIMESTAMP | 2024.01.15T10:30:00 |
时间戳 |
2.3 向量(Vector)
向量是DolphinDB最基本的数据结构:
python
// 创建向量
v1 = 1..10 // 1到10的整数向量
v2 = rand(100.0, 10) // 10个随机浮点数
v3 = `A`B`C`D`E // 字符串向量
v4 = true false true true // 布尔向量
// 向量操作
v1 + 10 // 向量加常数:[11,12,13,...,20]
v1 * 2 // 向量乘常数:[2,4,6,...,20]
v1 + v1 // 向量相加:[2,4,6,...,20]
// 向量函数
sum(v1) // 求和:55
avg(v1) // 平均值:5.5
max(v1) // 最大值:10
min(v1) // 最小值:1
size(v1) // 元素个数:10
// 向量索引(从0开始)
v1[0] // 第一个元素:1
v1[-1] // 最后一个元素:10
v1[0:5] // 前5个元素:[1,2,3,4,5]
v1[[0,2,4]] // 取第0,2,4个元素
2.4 矩阵(Matrix)
python
// 创建矩阵
m1 = matrix(1..12).reshape(3,4) // 3x4矩阵
m2 = 1..12$3:4 // 简写形式
// 矩阵运算
m1 + 10 // 矩阵加常数
m1 * 2 // 矩阵乘常数
m1 + m1 // 矩阵相加
m1 @ transpose(m1) // 矩阵乘法
// 矩阵索引
m1[0,] // 第一行
m1[,0] // 第一列
m1[0:2, 1:3] // 子矩阵
2.5 字典(Dictionary)
python
// 创建字典
d = dict(STRING, ANY)
d[`name] = "DolphinDB"
d[`version] = "2.00.11"
d[`users] = 1000
// 或使用键值对创建
d = dict(`name`version`users, ["DolphinDB", "2.00.11", 1000])
// 访问字典
d[`name] // "DolphinDB"
d.keys() // 获取所有键
d.values() // 获取所有值
d.hasKey(`name) // 检查键是否存在
三、运算符
3.1 算术运算符
| 运算符 | 说明 | 示例 |
|---|---|---|
| + | 加法 | 1 + 2 → 3 |
| - | 减法 | 5 - 3 → 2 |
| * | 乘法 | 3 * 4 → 12 |
| / | 除法 | 10 / 3 → 3.333... |
| \ | 整除 | 10 \ 3 → 3 |
| % | 取模 | 10 % 3 → 1 |
| ^ | 幂运算 | 2 ^ 3 → 8 |
3.2 比较运算符
| 运算符 | 说明 | 示例 |
|---|---|---|
| == | 等于 | 1 == 1 → true |
| != | 不等于 | 1 != 2 → true |
| < | 小于 | 1 < 2 → true |
| <= | 小于等于 | 1 <= 1 → true |
| > | 大于 | 2 > 1 → true |
| >= | 大于等于 | 2 >= 2 → true |
3.3 逻辑运算符
python
// 逻辑运算
true and false // false
true or false // true
not true // false
// 短路运算
1 < 2 and 2 < 3 // true
1 < 2 or 2 > 3 // true
// 向量逻辑运算
v = 1..10
v > 5 // [false,false,false,false,false,true,true,true,true,true]
v >= 5 and v <= 8 // [false,false,false,false,true,true,true,true,false,false]
3.4 向量化运算
DolphinDB的核心优势是向量化计算:
python
// 向量运算自动应用到每个元素
v = 1..10
v * 2 // [2,4,6,8,10,12,14,16,18,20]
v ^ 2 // [1,4,9,16,25,36,49,64,81,100]
// 条件运算
v > 5 // 返回布尔向量
v[v > 5] // 过滤:[6,7,8,9,10]
// 向量间运算
a = 1..5
b = 6..10
a + b // [7,9,11,13,15]
a * b // [6,14,24,36,50]
四、控制流
4.1 条件语句
python
// if-else语句
x = 10
if (x > 5) {
print("x大于5")
} else {
print("x不大于5")
}
// 多条件判断
score = 85
if (score >= 90) {
grade = "A"
} else if (score >= 80) {
grade = "B"
} else if (score >= 70) {
grade = "C"
} else if (score >= 60) {
grade = "D"
} else {
grade = "F"
}
print("成绩等级: " + grade)
// 三元运算符
result = x > 5 ? "大于5" : "不大于5"
4.2 循环语句
python
// for循环
for (i in 1..5) {
print(i)
}
// 遍历向量
devices = `device1`device2`device3
for (device in devices) {
print("设备: " + device)
}
// while循环
i = 0
while (i < 5) {
print(i)
i += 1
}
// do-while循环
i = 0
do {
print(i)
i += 1
} while (i < 5)
// break和continue
for (i in 1..10) {
if (i == 3) continue // 跳过3
if (i == 7) break // 到7停止
print(i)
}
4.3 向量化替代循环
DolphinDB推荐使用向量化操作替代循环:
python
// 不推荐:使用循环计算
result = array(DOUBLE, 0)
for (i in 1..10000) {
result.append!(i * 2)
}
// 推荐:向量化计算
result = 1..10000 * 2 // 快100倍以上
五、函数
5.1 内置函数
DolphinDB内置1400+函数,涵盖各类数据处理需求:
python
// 数学函数
abs(-10) // 绝对值:10
sqrt(16) // 平方根:4
log(100) // 自然对数
log10(100) // 以10为底的对数:2
exp(1) // e的幂次方
round(3.14159, 2) // 四舍五入:3.14
floor(3.9) // 向下取整:3
ceil(3.1) // 向上取整:4
// 统计函数
v = rand(100.0, 1000)
mean(v) // 平均值
std(v) // 标准差
var(v) // 方差
median(v) // 中位数
quantile(v, 0.95) // 95%分位数
// 字符串函数
s = "Hello DolphinDB"
len(s) // 长度:14
upper(s) // 大写
lower(s) // 小写
substr(s, 0, 5) // 子串:Hello
split(s, " ") // 分割
trim(" hello ") // 去空格
// 时间函数
now() // 当前时间戳
today() // 今天日期
year(now()) // 年份
month(now()) // 月份
day(now()) // 日期
hour(now()) // 小时
minute(now()) // 分钟
second(now()) // 秒
5.2 自定义函数
python
// 基本函数定义
def add(a, b) {
return a + b
}
add(1, 2) // 3
// 带默认参数的函数
def greet(name, greeting="Hello") {
return greeting + ", " + name + "!"
}
greet("DolphinDB") // "Hello, DolphinDB!"
greet("DolphinDB", "Hi") // "Hi, DolphinDB!"
// 多返回值函数
def stats(v) {
return avg(v), max(v), min(v)
}
a, m, n = stats(1..100)
// 递归函数
def factorial(n) {
if (n <= 1) return 1
return n * factorial(n - 1)
}
factorial(5) // 120
5.3 匿名函数与高阶函数
python
// 匿名函数
f = def (x) { return x * 2 }
f(10) // 20
// 高阶函数:each
each(def (x) { return x * 2 }, 1..5) // [2,4,6,8,10]
// 高阶函数:eachLeft
eachLeft(add, 1..3, 10) // [11,12,13]
// 高阶函数:eachRight
eachRight(add, 10, 1..3) // [11,12,13]
// 高阶函数:reduce
reduce(def (x, y) { return x + y }, 1..10) // 55
// 高阶函数:accumulate
accumulate(def (x, y) { return x + y }, 1..5) // [1,3,6,10,15]
5.4 函数应用示例
python
// 工业物联网场景:设备状态判断
def getDeviceStatus(temperature, humidity, pressure) {
// 温度异常判断
tempStatus = iif(temperature > 35, "高温警告",
iif(temperature < 10, "低温警告", "正常"))
// 湿度异常判断
humidStatus = iif(humidity > 80, "高湿警告",
iif(humidity < 30, "低湿警告", "正常"))
// 压力异常判断
pressStatus = iif(pressure > 1020, "高压警告",
iif(pressure < 980, "低压警告", "正常"))
// 综合判断
if (tempStatus != "正常" or humidStatus != "正常" or pressStatus != "正常") {
return "异常"
}
return "正常"
}
// 应用函数
getDeviceStatus(38.5, 50.0, 1010.0) // "异常"(高温)
getDeviceStatus(25.0, 50.0, 1010.0) // "正常"
六、SQL查询
6.1 基本查询
python
// 创建测试表
t = table(1..100 as device_id,
take(`A`B`C`D, 100) as location,
rand(20..35, 100) as temperature,
rand(40..70, 100) as humidity,
2024.01.01 + rand(30, 100) as date)
// 基本查询
select * from t limit 10
// 条件查询
select * from t where temperature > 30
// 排序
select * from t order by temperature desc
// 去重
select distinct location from t
6.2 聚合查询
python
// 分组聚合
select location,
count(*) as device_count,
avg(temperature) as avg_temp,
max(temperature) as max_temp,
min(temperature) as min_temp
from t
group by location
// 多列分组
select location, date,
count(*) as count,
avg(temperature) as avg_temp
from t
group by location, date
// having子句
select location, avg(temperature) as avg_temp
from t
group by location
having avg(temperature) > 27
// 多聚合函数
select location,
sum(temperature) as sum_temp,
avg(temperature) as avg_temp,
std(temperature) as std_temp,
max(temperature) as max_temp,
min(temperature) as min_temp
from t
group by location
6.3 连接查询
python
// 创建关联表
devices = table(1..10 as device_id, `device` + string(1..10) as device_name)
readings = table(1 1 2 2 3 3 as device_id,
now() + 1..6 as timestamp,
rand(20..30, 6) as temperature)
// 左连接
select r.device_id, d.device_name, r.timestamp, r.temperature
from readings r
left join devices d on r.device_id = d.device_id
// 内连接
select * from lj(readings, devices, `device_id)
// 全连接
select * from fj(readings, devices, `device_id)
6.4 窗口函数
python
// 排名函数
select device_id, temperature,
rank() over (order by temperature desc) as temp_rank,
dense_rank() over (order by temperature desc) as dense_rank,
row_number() over (order by temperature desc) as row_num
from t
// 分区窗口函数
select device_id, date, temperature,
rank() over (partition by date order by temperature desc) as daily_rank
from t
// 移动窗口
select device_id, temperature,
mavg(temperature, 3) over (order by device_id) as moving_avg,
msum(temperature, 5) over (order by device_id) as moving_sum
from t
七、模块化编程
7.1 模块定义
python
// 文件: modules/iot_utils.dos
// 模块声明
module iot_utils
// 设备状态判断函数
def getDeviceStatus(temperature, humidity, pressure) {
tempStatus = iif(temperature > 35, "高温警告",
iif(temperature < 10, "低温警告", "正常"))
humidStatus = iif(humidity > 80, "高湿警告",
iif(humidity < 30, "低湿警告", "正常"))
pressStatus = iif(pressure > 1020, "高压警告",
iif(pressure < 980, "低压警告", "正常"))
if (tempStatus != "正常" or humidStatus != "正常" or pressStatus != "正常") {
return "异常"
}
return "正常"
}
// 温度单位转换
def celsiusToFahrenheit(celsius) {
return celsius * 9 / 5 + 32
}
def fahrenheitToCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9
}
// 数据质量检查
def checkDataQuality(t) {
return select count(*) as total,
sum(iif(temperature is null, 1, 0)) as null_temp,
sum(iif(temperature < 0 or temperature > 100, 1, 0)) as invalid_temp
from t
}
7.2 模块使用
python
// 加载模块
use iot_utils
// 使用模块中的函数
status = getDeviceStatus(38.5, 50.0, 1010.0)
print(status) // "异常"
fahrenheit = celsiusToFahrenheit(25.0)
print(fahrenheit) // 77.0
// 检查数据质量
t = table(1..100 as device_id,
rand(20..30, 100) as temperature,
rand(40..60, 100) as humidity)
checkDataQuality(t)
八、错误处理
8.1 try-catch
python
// 基本错误处理
try {
result = 1 / 0
} catch(ex) {
print("错误: " + ex)
}
// 带finally
try {
conn = connect("localhost", 8848)
// 执行操作
} catch(ex) {
print("连接失败: " + ex)
} finally {
// 清理资源
if (not isVoid(conn)) conn.close()
}
8.2 断言
python
// 断言检查
def divide(a, b) {
assert(b != 0, "除数不能为0")
return a / b
}
divide(10, 2) // 5
divide(10, 0) // 抛出异常
九、最佳实践
9.1 代码风格
| 规范 | 说明 | 示例 |
|---|---|---|
| 变量命名 | 小驼峰或下划线 | deviceId 或 device_id |
| 函数命名 | 动词开头 | getDeviceStatus |
| 常量命名 | 全大写 | MAX_RETRY_COUNT |
| 注释 | 说明复杂逻辑 | // 计算设备健康度 |
9.2 性能优化
性能优化
向量化优先
避免循环
批量操作
内存管理
使用向量运算
使用each/eachLeft等
批量插入数据
及时释放大变量
9.3 代码示例
python
// 推荐:向量化计算
def calculateHealthScore(temperature, humidity, pressure) {
// 向量化计算,高效处理批量数据
tempScore = 100 - abs(temperature - 25) * 2
humidScore = 100 - abs(humidity - 50) * 0.5
pressScore = 100 - abs(pressure - 1013) * 0.1
return (tempScore + humidScore + pressScore) / 3
}
// 应用到整列
t = table(rand(20..30, 1000) as temperature,
rand(40..60, 1000) as humidity,
rand(1000..1020, 1000) as pressure)
t[`healthScore] = calculateHealthScore(t.temperature, t.humidity, t.pressure)
十、总结
本文系统介绍了DolphinDB脚本语言的核心语法。核心要点如下:
- 数据类型:标量、向量、矩阵、字典等丰富类型
- 运算符:算术、比较、逻辑运算符,支持向量化
- 控制流:if-else、for、while等控制语句
- 函数:内置函数、自定义函数、高阶函数
- SQL查询:完整的SQL语法支持
- 模块化:代码组织和复用
思考题:
- 如何使用向量化操作替代循环以提升性能?
- 如何设计可复用的模块化函数库?
- 在工业物联网场景中,如何利用脚本语言处理实时数据?