Array Overlap Query GIN Index

Index a tag array with GIN so && overlap and @> containment filters resolve in the index instead of scanning every row.

SqlData Fetching

Code

snippet
-- 标签列的"任一命中"查询:&& 判断两个数组是否有公共元素
CREATE TABLE articles (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title text NOT NULL,
    tags  text[] NOT NULL DEFAULT '{}'
);

INSERT INTO articles (title, tags) VALUES
    ('trail guide', ARRAY['outdoor', 'hiking']),
    ('city guide',  ARRAY['outdoor', 'urban']);

-- GIN 索引让 && 与 @> 等数组运算符走索引
CREATE INDEX articles_tags_gin ON articles USING gin (tags);

-- 含任一给定标签的文章
SELECT title
FROM articles
WHERE tags && ARRAY['hiking', 'urban'];

-- 包含全部给定标签的文章
SELECT title
FROM articles
WHERE tags @> ARRAY['outdoor', 'hiking'];

Inside the snippet

Several statements share this file — SELECT / INSERT / CREATE, with articles among the objects involved.

Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

Run it in the articles database context.

Core lines

SELECT title
FROM articles
WHERE tags @> ARRAY['outdoor', 'hiking'];
SELECT title
FROM articles
WHERE tags && ARRAY['hiking', 'urban'];
CREATE TABLE articles (
id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
tags  text[] NOT NULL DEFAULT '{}'
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`articles`.