btree_gin索引不用于排序

时间:2016-03-17 10:18:03

标签: postgresql indexing

我们假设我有这张表:

CREATE TABLE test.widgets
(
  id          bigserial primary key,
  categories  int[] not null
);

使用btree_gin索引:

CREATE EXTENSION btree_gin;
CREATE INDEX widgets_idx ON test.widgets USING gin (categories, id);

我插入了一些测试数据:

INSERT INTO test.widgets (categories)
(
  SELECT ARRAY[
      (random() * 1000)::int,
      (random() * 1000)::int,
      (random() * 1000)::int,
      (random() * 1000)::int
  ]
  FROM generate_Series(1,100000)
);

然后我想查询给定类别中的所有小部件,但是按id排序:

SELECT id, categories
FROM test.widgets
WHERE ARRAY[48] <@ widgets.categories
ORDER BY id;

不是使用btree_gin索引进行排序,而是在内存中完成排序:

Sort  (cost=2124.05..2125.45 rows=561 width=40) (actual time=5.107..5.120 rows=402 loops=1)
  Sort Key: id
  Sort Method: quicksort  Memory: 56kB
  ->  Bitmap Heap Scan on widgets  (cost=1244.35..2098.43 rows=561 width=40) (actual time=4.759..5.061 rows=402 loops=1)
        Recheck Cond: ('{48}'::integer[] <@ categories)
        Heap Blocks: exact=320
        ->  Bitmap Index Scan on widgets_idx  (cost=0.00..1244.21 rows=561 width=0) (actual time=4.700..4.700 rows=402 loops=1)
              Index Cond: ('{48}'::integer[] <@ categories)
Planning time: 0.158 ms
Execution time: 5.171 ms

如何确保查询利用索引?

0 个答案:

没有答案