我有一个非常简单的表:
CREATE TABLE content
(
id serial NOT NULL,
text text,
fullfilename text,
CONSTRAINT "PK_ID" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE content
OWNER TO postgres;
CREATE INDEX content_idx
ON content
USING gin
(to_tsvector('danish'::regconfig, text));
Run Code Online (Sandbox Code Playgroud)
哪里text是一个相当长的聚合文本来执行全文搜索。
当我运行以下查询时,它求助于 seq 扫描:
EXPLAIN ANALYZE SELECT id
FROM content
WHERE to_tsvector('danish', text) @@ to_tsquery('danish','felter')
"Seq Scan on content (cost=0.00..164.57 rows=249 width=4) (actual time=41.147..7235.823 rows=289 loops=1)"
" Filter: (to_tsvector('danish'::regconfig, text) @@ '''felt'''::tsquery)"
" Rows Removed by Filter: 1149"
"Planning time: …Run Code Online (Sandbox Code Playgroud) 我最近开始研究PostgreSQL,我有大约1200 万行要处理,我想在其中应用Full Text Search。我之前没有处理此类数据库的任何经验。我已尝试优化查询,但我怀疑它是否已完全优化。
现在我正在使用GIST 索引,因为我读到GIN 索引中的更新速度较慢,并且我的数据库将定期更新。
我现在只需要关注数据库的两列merchant varchar(80)和product varchar(400).
我需要使用 FTS 查找产品,并且即使商家拼写错误,我也正在尝试获取该产品。
我在大约30K行的示例数据库上运行了一些查询,以获得以下结果:
首先,我运行基本的 FTS 查询来分析结果。
explain analyze
select count(*) from products
where to_tsvector('english', product) @@ to_tsquery('hat');
Run Code Online (Sandbox Code Playgroud)Run Code Online (Sandbox Code Playgroud)Aggregate (cost=2027.27..2027.28 rows=1 width=0) (actual time=349.032..349.032 rows=1 loops=1) -> Seq Scan on products (cost=0.00..2026.90 rows=147 width=0) (actual time=43.322..348.961 rows=307 loops=1) Filter: (to_tsvector((product)::text) @@ to_tsquery('hat'::text)) Total runtime: 349.140 ms
然后我创建了 GIST 索引并运行相同的查询以查看改进。结果非常好。至少对于我来说。
create index product_gist on products …Run Code Online (Sandbox Code Playgroud)postgresql index optimization full-text-search pattern-matching