pgbson
为 PostgreSQL 提供 BSON 数据类型、比较与访问函数
仓库
buzzm/postgresbson
https://github.com/buzzm/postgresbson
源码
postgresbson-2.0.2.tar.gz
postgresbson-2.0.2.tar.gz
概览
| 扩展包名 | 版本 | 分类 | 许可证 | 语言 |
|---|---|---|---|---|
pgbson | 2.0.2 | TYPE | MIT | C |
| ID | 扩展名 | Bin | Lib | Load | Create | Trust | Reloc | 模式 |
|---|---|---|---|---|---|---|---|---|
| 3910 | pgbson | 否 | 是 | 否 | 是 | 否 | 是 | - |
| 相关扩展 | pg_jsonschema jsquery jsonb_plperl jsonb_plpython3u mongo_fdw documentdb documentdb_core documentdb_distributed |
|---|
PGXN dist name is bson, but CREATE EXTENSION name is pgbson; RPM package root is postgresbson; RPM runtime dependency is libbson.
版本
| 类型 | 仓库 | 版本 | PG 大版本 | 包名 | 依赖 |
|---|---|---|---|---|---|
| EXT | PIGSTY | 2.0.2 | 1817161514 | pgbson | - |
| RPM | PIGSTY | 2.0.2 | 1817161514 | postgresbson_$v | libbson |
| DEB | PIGSTY | 2.0.2 | 1817161514 | postgresql-$v-pgbson | - |
构建
您可以使用 pig build 命令构建 pgbson 扩展的 RPM / DEB 包:
pig build pkg pgbson # 构建 RPM / DEB 包
安装
您可以直接安装 pgbson 扩展包的预置二进制包,首先确保 PGDG 和 PIGSTY 仓库已经添加并启用:
pig repo add pgsql -u # 添加仓库并更新缓存
使用 pig 或者是 apt/yum/dnf 安装扩展:
pig install pgbson; # 当前活跃 PG 版本安装
pig ext install -y pgbson -v 18 # PG 18
pig ext install -y pgbson -v 17 # PG 17
pig ext install -y pgbson -v 16 # PG 16
pig ext install -y pgbson -v 15 # PG 15
pig ext install -y pgbson -v 14 # PG 14
dnf install -y postgresbson_18 # PG 18
dnf install -y postgresbson_17 # PG 17
dnf install -y postgresbson_16 # PG 16
dnf install -y postgresbson_15 # PG 15
dnf install -y postgresbson_14 # PG 14
apt install -y postgresql-18-pgbson # PG 18
apt install -y postgresql-17-pgbson # PG 17
apt install -y postgresql-16-pgbson # PG 16
apt install -y postgresql-15-pgbson # PG 15
apt install -y postgresql-14-pgbson # PG 14
创建扩展:
CREATE EXTENSION pgbson;
用法
语法:
CREATE EXTENSION pgbson; SELECT bson_get_datetime(bson_column, 'msg.header.event.ts') FROM my_table; SELECT (bson_column->'msg'->'header'->'event'->>'ts')::timestamp FROM my_table;来源:README
pgbson 为 PostgreSQL 增加了 BSON 数据类型,以及用于创建、检查和查询 BSON 文档的函数与操作符。上游 README 将其定位为 JSON/JSONB 的二进制、富类型替代方案,具备精确 round-trip、对日期时间和数值子类型的原生支持,以及原始字节支持。
BSON 的优势
README 强调 BSON 相比 JSON 的几项优势:
- 日期时间是第一类值
- 数值类型保持区分(
int32、int64、float、decimal) - 原始字节数组是第一类值
- 往返转换可保留完全一致的二进制表示
- 多种语言的原生 SDK 支持
访问方式
扩展提供两种访问风格:
Dotpath 访问器
这是上游文档中的高性能类型安全访问器:
SELECT bson_get_datetime(bson_column, 'msg.header.event.ts') FROM my_table;
SELECT bson_get_bson(bson_column, 'msg.header.event') FROM my_table;
README 认为它们比反复使用箭头解引用更省内存,因为它们会直接遍历 BSON 结构,只在终点处分配材料化结果。
箭头操作符
它也支持类似 JSON 的操作符:
SELECT (bson_column->'msg'->'header'->'event'->>'ts')::timestamp
FROM my_table;
JSON 互操作
BSON 类型可以通过 Extended JSON(EJSON)转换为 JSON,从而保留类型精度。这使得 BSON 值可以在需要时交给 JSON/JSONB 函数和操作符处理:
SELECT (bson_get_bson(bson_column, 'msg.header.event')::jsonb) ?& ARRAY['id','type']
FROM my_table;
说明
README 中给出了跨 Java、Kafka、Python 和 PostgreSQL 的 BSON 往返示例,强调将存储的 BSON 载荷重新转成 bytea 后可以做到字节级一致。