본문 바로가기
C.W.K.
Stream
Lesson 05 of 10 · published

Elasticsearch 없이 전문 검색

~14 min · extensions, fts

Level 0스키마 새싹
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

tsvector와 tsquery

PostgreSQL 전문 검색은 문서를 정규화한 tsvector와 검색 조건인 tsquery@@로 맞춰. GIN 색인을 두면 많은 문서에서도 빠르게 후보를 찾을 수 있어.

검색어를 만들고 순위를 매겨

to_tsvector('english', text), to_tsquery('english', 'postgres & performance')가 기본이고, 사용자 입력에는 plainto_tsquerywebsearch_to_tsquery가 편해. ts_rankts_rank_cd는 관련도를, ts_headline은 일치 구절을 보여줘.

검색 벡터는 저장해 재사용해

tsvector를 STORED 생성 열로 만들고 GIN 색인을 걸면 쓸 때 한 번 계산하고 모든 검색에서 재사용해. 수백만 문서를 ms 단위로 찾는 기반이 돼.

Code

전문 검색 구성하기·sql
CREATE TABLE articles (
    id        INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    title     TEXT NOT NULL,
    body      TEXT NOT NULL,
    tsv       tsvector GENERATED ALWAYS AS (
                to_tsvector('english', coalesce(title,'') || ' ' || coalesce(body,''))
              ) STORED,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX articles_tsv_gin ON articles USING gin (tsv);
검색 결과에 순위와 문맥 조각 더하기·sql
WITH q AS (SELECT websearch_to_tsquery('english', 'postgres performance') AS query)
SELECT id, title,
       ts_rank(tsv, q.query)                            AS score,
       ts_headline('english', body, q.query,
                   'StartSel=<mark>, StopSel=</mark>')   AS snippet
FROM   articles, q
WHERE  tsv @@ q.query
ORDER  BY score DESC
LIMIT  10;

External links

Exercise

텍스트가 많은 테이블에 생성 tsvector 열과 GIN 색인을 추가해. 순위와 강조된 문맥 조각을 포함한 전문 검색을 실행하고 단순한 ILIKE '%term%' 질의와 속도를 비교해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.