我只是推薦一個散列索引:
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