pg94@db1-> psql francs psql (9.4beta3) Type "help"for help. francs=# create extension zhparser; CREATE EXTENSION --make test configuration using parser francs=# CREATE TEXT SEARCH CONFIGURATION testzhcfg (PARSER = zhparser); CREATE TEXT SEARCH CONFIGURATION --add token mapping francs=# ALTER TEXT SEARCH CONFIGURATION testzhcfg ADD MAPPING FOR n,v,a,i,e,l WITH simple; ALTER TEXT SEARCH CONFIGURATION
francs=> explain analyze select name,type,city from tbl_store where name like '%美猴王批发%'; QUERY PLAN ------------------------------------------------------------------------------------------------------------- Seq Scan on tbl_store (cost=0.00..106601.41rows=282 width=44) (actual time=0.018..870.666rows=2 loops=1) Filter: ((name)::text ~~ '%美猴王批发%'::text) Rows Removed by Filter: 2994431 Planning time: 0.964 ms Execution time: 870.706 ms (5rows)
备注:两边带有 % 的 like 走全表扫,效率很低。
创建 GIN 索引
1 2 3
francs=> create index idx_gin_tbl_store_name on tbl_store using gin(to_tsvector('testzhcfg',name)); CREATE INDEX Time: 48434.917 ms
PG 中文全文检索
1 2 3 4 5 6 7 8 9 10 11
francs=> explain analyze select name,type,city from tbl_store where to_tsvector('testzhcfg',name) @@ to_tsquery('testzhcfg','美猴王批发'); QUERY PLAN --------------------------------------------------------------------------------------------------------------------------------- Bitmap Heap Scan on tbl_store (cost=28.58..322.30rows=75 width=44) (actual time=0.352..0.356rows=2 loops=1) Recheck Cond: (to_tsvector('testzhcfg'::regconfig, (name)::text) @@ '''美猴王'' & ''批发'''::tsquery) Heap Blocks: exact=2 -> Bitmap Index Scan on idx_gin_tbl_store_name (cost=0.00..28.56rows=75 width=0) (actual time=0.342..0.342rows=2 loops=1) Index Cond: (to_tsvector('testzhcfg'::regconfig, (name)::text) @@ '''美猴王'' & ''批发'''::tsquery) Planning time: 0.168 ms Execution time: 0.398 ms (7rows)