再次查看执行计划和执行时间,如下所示:
- mydb=> EXPLAIN ANALYZE SELECT * FROM test_search WHERE to_tsvector('english',name) @@ Bitmap Heap Scan on test_search (cost=18.39..128.38 rows=50 width=36) (actual time=0.071..0.071 rows=1 loops=1)
- Recheck Cond: (to_tsvector('english'::regconfig, name) @@ '''1'' & ''franc'''::tsquery)
- Heap Blocks: exact=1
- -> Bitmap Index Scan on idx_gin_search (cost=0.00..18.38 rows=50 width=0) (actual time=0.064..0.064 rows=1 loops=1)
- Index Cond: (to_tsvector('english'::regconfig, name) @@ '''1'' & ''franc'''::tsquery)
- Planning time: 0.122 ms
- Execution time: 0.104 ms
- (7 rows)
创建索引后,以上查询走了索引并且执行时间下降到0.104毫秒,性能提升了3个数量级,值得一提的是如果SQL改成以下,则不走索引,如下所示:
- mydb=> EXPLAIN ANALYZE SELECT * FROM test_search WHERE to_tsvector(name) @@ to_tsquery('1_francs');
- Seq Scan on test_search (cost=0.00..1037730.00 rows=50 width=18) (actual time=0.036..10297.764 rows=1 loops=1)
- Filter: (to_tsvector(name) @@ to_tsquery('1_francs'::text))
- Rows Removed by Filter: 1999999
- Planning time: 0.098 ms
- Execution time: 10297.787 ms
- (5 rows)
由于创建索引时使用的是to_tsvector('english',name)函数索引,带了两个参数,因此where条件中的to_tsvector函数带两个参数才能走索引,而to_tsvector(name)不走索引。
2、JSON、JSONB全文检索实践
在PostgreSQL 10版本之前全文检索不支持json和jsonb数据类型,10版本的一个重要特性是全文检索支持json和jsonb数据类型。
10版本与9.6版本to_tsvector函数的差异
先来看下9.6版本to_tsvector函数,如下:
- [postgres@pghost1 ~]$ psql francs francs
- psql (9.6.3)
- Type "help" for help.
- mydb=> df *to_tsvector*
- List of functions
- Schema | Name | Result data type | Argument data types | Type
- ------------+-------------------+------------------+---------------------+--------
- pg_catalog | array_to_tsvector | tsvector | text | normal
- pg_catalog | to_tsvector | tsvector | regconfig, text | normal
- pg_catalog | to_tsvector | tsvector | text | normal
- (3 rows)
从以上看出9.6版本to_tsvector函数的输入参数仅支持text、text数据类型,接着看下10版本的to_tsvector函数,如下所示:
- [postgres@pghost1 ~]$ psql mydb pguser
- psql (10.0)
- pg_catalog | to_tsvector | tsvector | json | normal
- pg_catalog | to_tsvector | tsvector | jsonb | normal
- pg_catalog | to_tsvector | tsvector | regconfig, json | normal
- pg_catalog | to_tsvector | tsvector | regconfig, jsonb | normal
从以上看出,10版本的to_tsvector函数支持的数据类型增加了json和jsonb。
创建数据生成函数
为了便于生成测试数据,创建以下两个函数用来随机生成指定长度的字符串,创建random_range(int4, int4)函数如下:
- CREATE OR REPLACE FUNCTION random_range(int4, int4)
- RETURNS int4
- LANGUAGE SQL
- AS $$
- SELECT ($1 + FLOOR(($2 - $1 + 1) * random ))::int4;
- $$;
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|