2014-02-28 46 views
17

我有一個杜松子酒索引一個postgres陣列列:如何使用杜松子索引查詢postgres數組?

CREATE TABLE things (
    id integer NOT NULL, 
    tags character varying(255)[] 
); 

CREATE INDEX index_things_on_tags ON things USING gin (tags); 

有幾種方法可檢查的元件的列中的存在下,使用各種陣列運算符。下面是我見過的那些:

  1. select * from things where 'blue' = ANY (tags)
  2. select * from things where tags <@ '{"blue"}'
  3. select * from things where '{"blue","yellow"}' && tags;

了在Postgres 9.3:

  • 將第一個用杜松子酒指數?
  • 我很確定第二個將使用索引。但是,與第一個不同。它不允許我檢查藍色是否是其中一個標籤,它需要我指定確切的數組。有沒有辦法讓語法的風格達到2實現的目標?
  • 第三,我想要任何有藍色或黃色的行。這個查詢會使用杜松子酒索引嗎?如果不是,我該如何使用索引執行此查詢?
+0

只要運行'explain analyze',你的問題就會得到解答 –

回答

17

爲什麼不測試看看?

regress=> SET enable_seqscan = off; 
SET 

regress=> explain select * from things where 'blue' = ANY (tags); 
           QUERY PLAN         
--------------------------------------------------------------------------- 
Seq Scan on things (cost=10000000000.00..10000000037.67 rows=6 width=36) 
    Filter: ('blue'::text = ANY ((tags)::text[])) 
(2 rows) 

regress=> explain select * from things where tags <@ '{"blue"}'; 
            QUERY PLAN          
------------------------------------------------------------------------------------ 
Bitmap Heap Scan on things (cost=12.05..21.52 rows=6 width=36) 
    Recheck Cond: (tags <@ '{blue}'::character varying[]) 
    -> Bitmap Index Scan on index_things_on_tags (cost=0.00..12.05 rows=6 width=0) 
     Index Cond: (tags <@ '{blue}'::character varying[]) 
(4 rows) 

regress=> explain select * from things where '{"blue","yellow"}' && tags; 
            QUERY PLAN          
------------------------------------------------------------------------------------- 
Bitmap Heap Scan on things (cost=12.10..22.78 rows=12 width=36) 
    Recheck Cond: ('{blue,yellow}'::character varying[] && tags) 
    -> Bitmap Index Scan on index_things_on_tags (cost=0.00..12.09 rows=12 width=0) 
     Index Cond: ('{blue,yellow}'::character varying[] && tags) 
(4 rows) 

所以PG是利用指數爲&&<@查詢,但不爲= ANY (...)

我確定有可能教Pg將x = ANY (y)轉換成ARRAY[x] @> y,但現在還沒有。

2所做的正是你所說的你想要的。測試「藍色」是否是其中一個標籤。這不是一個平等測試,它是一個會員測試。

+1

謝謝!我不熟悉'SET enable_seqscan = off;'爲了測試小數據的索引使用情況。 –

+0

這裏是我觀察2的行爲:https://gist.github.com/jjb/9281339 –

+2

@JohnBachir倒過來; '@>'。順便說一下,http://sqlfiddle.com/對於這種事情更有用。 –

相關問題