以二进制格式复制的 Postgres JSONB 规范

Postgres JSONB specification for Copy In binary format

我目前正在尝试通过 JDBC 优化 Postgres 中的数据加载。 我们正在使用 COPY FROM STDIN 和 FORMAT 'binary' 现在构建二进制字节数组对于字符串、长整数、uuid 等来说非常简单。但是在一个实例中,我们在 table 中有一个 JSONB 字段,我不知道如何将我的 json 对象序列化为二进制 jsonb 格式。 jsonb 有任何规范吗?

注意:我已经排除了只发送 utf-8 二进制序列化 json 字符串的可能性。

您只需要将json 对象视为普通字符串,但在版本号之前添加1(字节),这是他们目前唯一支持的版本。还要确保指定字段的长度是 "string.length" + 1(对于版本号)

所以,基本上,如果 j 是您的 json 并且 dos 是输出流:

val utfBytes = j.toString.getBytes("UTF8")
dos.writeInt(utfBytes.length + 1)
dos.write(Array(1.toByte))
dos.write(utfBytes)

这是来自 postgres 源代码的评论

 /*
  104  * jsonb type recv function
  105  *
  106  * The type is sent as text in binary mode, so this is almost the same
  107  * as the input function, but it's prefixed with a version number so we
  108  * can change the binary format sent in future if necessary. For now,
  109  * only version 1 is supported.
  110  */