作者
digoal
日期
2019-11-08
标签
PostgreSQL , gzip , gunzip , text 压缩 , bytea 压缩
背景
PG支持变成类型,例如text, bytea,变长类型最大1GB,可以在数据库中存储较大文本或文件。存储在数据库中,PG会自动使用pglz压缩,但是,如果用户要把数据查询到客户端,在客户端需要查询到这部分内容时,传输的内容并没有压缩(pglz到列级透明压缩和解压是在类型层面实现的),会导致传输占用较大带宽。
为了解决这个网络传输压缩的问题,我们通常来说有几种方法:
1、使用ssl链路,ssl可以配置压缩。客户端和数据库之间传输的是加密并压缩的数据。但是会引入加解密的cpu额外开销。
2、本文提到的gzip插件,由于使用了标准的压缩库,所以只要客户端支持gzip就可以解压。那么我们可以在存储时、返回结果时使用压缩值,压缩传输内容。
client - search(gzip result) - pgdb
gzip插件是一个压缩解压缩插件,接口如下
gzip(uncompressed BYTEA, [compression_level INTEGER]) returns BYTEA
gzip(uncompressed TEXT, [compression_level INTEGER]) returns BYTEA
gunzip(compressed BYTEA) returns BYTEA
解决传输问题,使用gzip的结果返回给客户端。
select gzip (column, 压缩级别)
解决存储问题,使用gzip的结果存储值(使用bytea类型)。
insert into table values (gzip (column, 压缩级别))
查询时可以选择数据库端解压,也可以选择在客户端解压(要求客户端有gzipLIB)
安装gzip 插件
```
wget http://api.pgxn.org/dist/gzip/1.0.0/gzip-1.0.0.zip
unzip gzip-1.0.0.zip
cd gzip-1.0.0/
USE_PGXS=1 make
USE_PGXS=1 make install
pg12@pg11-test-> psql
psql (12beta2)
Type "help" for help.
postgres=# create extension gzip ;
CREATE EXTENSION
```
使用例子
```
SELECT gzip('this is my this is my this is my this is my text');
gzip
\x1f8b08000000000000132bc9c82c5600a2dc4a851282ccd48a12002e7a22ff30000000
```
What, the compressed output is longer?!? No, it only looks that way, because in hex every character requires two hex digits. The original string looks like this in hex:
```
SELECT 'this is my this is my this is my this is my text'::bytea;
bytea
\x74686973206973206d792074686973206973206d792074686973206973206d792074686973206973206d792074657874
```
And for really long, repetitive things, compression naturally works like a charm:
```
SELECT gzip(repeat('this is my ', 100));
bytea
\x1f8b08000000000000132bc9c82c5600a2dc4a859251e628739439ca24970900d1341c5c4c040000
```
Converting a bytea back into an equivalent text uses the encode() function with the escape encoding.
```
SELECT encode(gunzip(gzip('this is my this is my this is my this is my text')), 'escape')
encode
this is my this is my this is my this is my text
```
参考
https://pgxn.org/dist/gzip/1.0.0/
PostgreSQL 许愿链接
您的愿望将传达给PG kernel hacker、数据库厂商等, 帮助提高数据库产品质量和功能, 说不定下一个PG版本就有您提出的功能点. 针对非常好的提议,奖励限量版PG文化衫、纪念品、贴纸、PG热门书籍等,奖品丰富,快来许愿。开不开森.