我只是推荐一个散列索引:
create index mytable_phrase_idx on mytable using hash(phrase);
这种方式查询,如
select floatval from mytable where phrase='foo bar';
会非常快。测试:
create temporary table test (k varchar(50), v float);
insert into test (k, v) select 'foo bar number '||generate_series(1,1000000), 1;
create index test_k_idx on test using hash (k);
analyze test;
explain analyze select v from test where k='foo bar number 634652';
QUERY PLAN
-----------------------------------------------------------------------------------------------------------------
Index Scan using test_k_idx on test (cost=0.00..8.45 rows=1 width=8) (actual time=0.201..0.206 rows=1 loops=1)
Index Cond: ((k)::text = 'foo bar number 634652'::text)
Total runtime: 0.265 ms
(3 rows)
使用varchar时,索引键的比较也要昂贵得多,因为它们可以识别locale。整数索引肯定会比任何其他选项快得多。 – 2010-04-14 15:00:33
@Magnus:比较只应该做'log(n)'次数,所以我不会称这个“很多”更贵,但是你是对的,它也会增加一些'CPU'循环。 – Quassnoi 2010-04-14 16:22:24