我的用例是,我需要对字段进行文本搜索,然后按照与文本搜索无关的其他列进行排序,但我似乎无法创建处理这两者的索引。
创建表格:
create table file (
id bigint,
path character varying(2048),
peers bigint,
text_search tsvector
);
要测试的一些指数:
create index idx_file_text_search_1 on file using gin (text_search);
create index idx_file_text_search_2 on file using gin (peers, text_search);
create index idx_file_peers on file using btree (peers desc);
这是我的主要问题:
explain analyze
select *
from file_fast
where text_search @@ to_tsquery('whatever')
order by peers desc
limit 10;
然而它只使用同行指数:
Limit (cost=0.43..20870.27 rows=10 width=316) (actual time=2507.304..9016.220 rows=10 loops=1)
-> Index Scan using idx_file_peers on file (cost=0.43..18286146.09 rows=8762 width=316) (actual time=2507.301..9016.205 rows=10 loops=1)
Filter: (text_search @@ to_tsquery('ole'::text))
Rows Removed by Filter: 497504
Planning time: 0.399 ms
Execution time: 9016.265 ms
(6 rows)
当我在没有订单的情况下尝试它时,似乎使用文本搜索索引:
-------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=104.15..143.54 rows=10 width=316) (actual time=76.949..76.977 rows=10 loops=1)
-> Bitmap Heap Scan on file (cost=104.15..34612.36 rows=8762 width=316) (actual time=76.946..76.970 rows=10 loops=1)
Recheck Cond: (text_search @@ to_tsquery('ole'::text))
Heap Blocks: exact=10
-> Bitmap Index Scan on idx_file_text_search_1 (cost=0.00..101.96 rows=8762 width=0) (actual time=76.802..76.802 rows=515 loops=1)
Index Cond: (text_search @@ to_tsquery('ole'::text))
Planning time: 0.376 ms
Execution time: 175.775 ms
(8 rows)
postgres是否真的缺少能够进行文本搜索的索引,并对另一个字段进行排序?
答案 0 :(得分:1)
不知道你是否可以改进索引,但如果第二个查询更快,你可以拆分查询
with cte as (
select *
from file_fast
where text_search @@ to_tsquery('whatever')
)
SELECT *
FROM cte
order by peers desc
limit 10;