簡體   English   中英

如何使用gin索引查詢postgres數組?

[英]How does one query a postgres array using the gin index?

我有一個帶有杜松子酒索引的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中的語法風格實現1實現的目標?
  • 在第三個,我想要任何有藍色或黃色的行。 這個查詢會使用杜松子酒索引嗎? 如果沒有,我如何使用索引進行此查詢?

為什么不試試看?

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你做的正是你想要的。 測試“藍色”是否是標簽之一。 這不是一個平等測試,它是一個成員資格測試。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM