# Search Pattern
<!--
ref: @protocol/search-pattern
type: protocol
tags: [search, postgres, fulltext, fts, reference, architecture, codebase]
aliases: [search-pattern, fts-pattern, search-architecture, search-design]
triggers: [postgres fts, full text search, search query design, build search, fulltext architecture, search index plan, design search]
trigger_prompt: When designing or fixing full-text search on Postgres for a codebase-style app — tsvector columns, trigram indexes, is_latest flags, two-part queries, tier-bucketed ranking — reach for this reference protocol.
category: meta
last_reviewed: 2026-05-08
complements: [@protocol/protocol-api, @protocol/api-reference, @protocol/extract]
audience: [agent-author, backend-engineer]
version: 2
updated_at: 2026-07-14T23:30:31.905Z
-->

The reference shape for full-text search on Postgres in codebase-style apps. Two-part query: structural filters first, text search + ranking second. Reads top-to-bottom; one helper builds the WHERE; results and facets share it.

This is the design that protocol.supply ships and the pattern future projects should copy.

---

## When to Use This

- New backend service needs search across a versioned table (entries, posts, items, anything with revisions).
- Existing search is "load everything from SQL, then `.filter()` in app code" — the dominant performance smell.
- The platform is Postgres ≥ 12. SQLite, MySQL, and others don't carry the same `tsvector` / `pg_trgm` toolkit.

If your search lives in Elasticsearch, Algolia, or Meilisearch — different protocol. This one is "you already have Postgres, do it well."

---

## The Five Building Blocks

Every well-built Postgres FTS app uses the same five pieces. Skip any of them and the system pays for it later.

### 1. A weighted, generated `tsvector` column

```sql
ALTER TABLE entry ADD COLUMN search_ts tsvector GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')),    'A') ||
    setweight(to_tsvector('english', coalesce(short, '')),    'A') ||
    setweight(to_tsvector('english', coalesce(metadata->>'tags', '')),     'A') ||
    setweight(to_tsvector('english', coalesce(metadata->>'triggers', '')), 'A') ||
    setweight(to_tsvector('english', coalesce(summary, '')),  'B') ||
    setweight(to_tsvector('english', coalesce(content, '')),  'D')
) STORED;

CREATE INDEX entry__search_ts__ix ON entry USING gin (search_ts);
```

**Generated, not trigger-maintained.** Triggers can be skipped by bulk operations (psql restore, pg_dump/pg_restore, direct INSERT bypassing the ORM). Generated columns are computed by the planner at write time — drift is impossible.

**Weighted with `setweight(..., 'A'..'D')`.** Title matches should beat body matches even when both produce a `ts_rank` of 0.5. Without weights, `ts_rank` treats all token matches identically.

**`metadata->>'tags'` works in generated columns.** The `->>` operator returns text and is IMMUTABLE. The english tokenizer strips brackets/quotes/commas during tokenization — `["deploy","ops"]` produces tokens `deploy`, `ops`. No subquery needed.

### 2. The `pg_trgm` extension + GIN trigram indexes

```sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE INDEX entry__title_trgm__ix ON entry USING gin (title gin_trgm_ops);
CREATE INDEX entry__slug_trgm__ix  ON entry USING gin (slug  gin_trgm_ops);
```

Without this, `LOWER(title) ILIKE '%q%'` and `LOWER(slug) ILIKE '%q%'` are sequential scans. Every short query, every partial-word query, every typo: full-table scan. With trigram GIN: index lookup.

Cost: ~2× insert/update cost vs btree. Acceptable in most write profiles. Quantify under load if ingest is ingest-heavy.

### 3. A stored "is current" flag

If your table is versioned (e.g. revision-per-edit), every list/search query asks "give me the latest non-deleted version of each row." The naïve form is a correlated subquery:

```sql
WHERE e.deleted = FALSE
  AND e.version = (SELECT MAX(e2.version) FROM entry e2
                   WHERE e2.id = e.id AND e2.deleted = FALSE)
```

This is paid **per candidate row of the outer query**. As table size grows, every list operation gets slower. No index helps — the MAX has to be computed.

The fix: a stored `is_latest BOOLEAN` flag, maintained by an after-trigger on inserts/updates/deletes. Filter queries become:

```sql
WHERE is_latest = TRUE AND deleted = FALSE
```

Constant time per row; backed by a partial index:

```sql
CREATE INDEX entry__active_repo__ix
  ON entry (repo_id)
  WHERE is_latest = TRUE AND deleted = FALSE;
```

The trigger has two correctness pitfalls:

- **Recursion**: the maintenance UPDATE re-fires the trigger. Solution: filter the UPDATE with `WHERE is_latest IS DISTINCT FROM <new value>` — no-op updates don't fire.
- **Trigger column list**: `AFTER UPDATE OF id, version, deleted` (NOT `is_latest`). The maintenance UPDATE changes only `is_latest`, which doesn't fire the trigger.

If your table is NOT versioned, skip this — `WHERE deleted = FALSE` is enough.

### 4. The two-part query

The query reads in two visually distinct halves. **One helper builds both halves**; the search and facet endpoints both call it:

```ts
private buildSearchWhere(filters: SearchFilters):
    { sql: string; params: Record<string, any> } {
  const parts: string[] = [];
  const params: Record<string, any> = {};

  // Part 1 — structural filters (cheap, hits the partial index)
  parts.push('e.is_latest = TRUE');
  parts.push('e.deleted = FALSE');
  parts.push('e.repo_id = ANY(:repoIds)');     params.repoIds = filters.allowedRepos;
  if (filters.type) {
    parts.push('e.type = :type');              params.type = filters.type;
  }
  if (filters.path) {
    parts.push('(e.path = :path OR e.path LIKE :pathPrefix)');
    params.path = filters.path;
    params.pathPrefix = filters.path + '/%';
  }
  if (filters.tags?.length) {
    parts.push("(e.metadata -> 'tags') ?| :tags");
    params.tags = filters.tags;
  }

  // Part 2 — text search (FTS + ILIKE fallback + alias/trigger predicates)
  if (filters.query?.trim()) {
    parts.push(`(
      e.search_ts @@ websearch_to_tsquery('english', :q)
      OR LOWER(e.title) ILIKE :qLike
      OR LOWER(e.slug)  ILIKE :qLike
      OR EXISTS (SELECT 1 FROM jsonb_array_elements_text(e.metadata -> 'aliases')
                 a WHERE LOWER(a) = LOWER(:q))
    )`);
    params.q = filters.query.trim();
    params.qLike = '%' + filters.query.trim().toLowerCase() + '%';
  }

  return { sql: parts.join(' AND '), params };
}
```

The split is explicit. Anyone debugging tomorrow can read the helper top-to-bottom: "what's filtering" before "what's matching."

### 5. Tier-bucketed ranking

`ts_rank` alone is not enough. Users expect "exact slug match" to beat "tsvector match" even when the tsvector match has a higher `ts_rank` — the slug match is more *intentional*.

Use a CASE expression to bucket matches into tiers, then rank within each tier:

```sql
ORDER BY
  match_tier ASC,                                              -- best bucket
  ts_rank(e.search_ts, websearch_to_tsquery('english', :q)) DESC,
  e.fetch_count DESC,                                          -- popularity
  e.title ASC                                                  -- stable fallback
```

The tier expression:

```sql
CASE
  WHEN LOWER(e.slug)  = LOWER(:q)                                                                THEN 1
  WHEN LOWER(e.title) = LOWER(:q)                                                                THEN 2
  WHEN EXISTS (... aliases  ... WHERE LOWER(a) = LOWER(:q))                                      THEN 3
  WHEN EXISTS (... tags     ... WHERE LOWER(t) = LOWER(:q))                                      THEN 4
  WHEN EXISTS (... triggers ... WHERE LOWER(t) ILIKE :qLike)                                     THEN 5
  WHEN LOWER(e.slug) LIKE LOWER(:q) || '%'                                                       THEN 6
  WHEN e.search_ts @@ websearch_to_tsquery('english', :q)                                        THEN 7
  WHEN LOWER(e.title) ILIKE :qLike OR LOWER(e.slug) ILIKE :qLike                                 THEN 8
  ELSE                                                                                                 9
END AS match_tier
```

Lower number = better tier. Tiers come from product judgment: what does the user *mean* when they type a query? Tune the tiers, not the magic numbers in `ts_rank`.

---

## What Goes Wrong Without This Pattern

Common failure modes — every one of these has been observed in production code:

1. **`SELECT *` then `.filter()` in Node.** No index helps. The dominant cost in any non-trivial dataset.
2. **`plainto_tsquery` instead of `websearch_to_tsquery`.** Strips quotes, ANDs everything, no NOT operator. Users get a worse parser than Google's.
3. **Trigger-maintained `tsvector` plus bulk ingest paths that bypass the trigger.** Drift between what users see and what the index covers.
4. **`LIKE '%q%'` without trigram indexes.** Sequential scan on every short query.
5. **`ts_rank` as the only ranker.** "Exact slug match" loses to "tsvector match" because the tsvector branch has more tokens.
6. **Two endpoints (results + facets) doing two full-table scans.** Pay twice for the same filtering work.

---

## Checklist For A New Project

Before shipping a new search backend, every box should be checked:

- [ ] `tsvector` column is `GENERATED ALWAYS AS ... STORED`, not trigger-maintained
- [ ] `setweight()` per source column (A/B/C/D buckets)
- [ ] `pg_trgm` extension installed via migration (not by hand)
- [ ] GIN trigram indexes on the text columns that ILIKE-fallback predicates touch
- [ ] If versioned: `is_latest` column + after-trigger + partial index
- [ ] Search endpoint and facet endpoint share a `buildSearchWhere` helper
- [ ] Query uses `websearch_to_tsquery` (handles quotes, AND, NOT)
- [ ] Ranking has tier buckets (CASE expression), not just `ts_rank`
- [ ] Result row excludes the heavy `content` column from the SELECT
- [ ] `EXPLAIN ANALYZE` captured for one query at scale, plan checked

---

## Reference Implementation

- Schema: `backend/database/V32__pg_trgm.sql` … `V35__entry_is_latest.sql`
- Repository: `backend/src/repository/EntryRepository.ts` (`searchEntries`, `searchEntryFacets`, `buildEntrySearchWhere`)
- Types: `backend/src/repository/EntrySearch.types.ts`
- Controller: `backend/src/controller/SearchController.ts` (`searchEntries`, `getEntryFacets`)

The shape of `buildEntrySearchWhere` is the takeaway. Copy it.

---

## Why This Matters

The team is going to build more apps with this stack. Search is the third-most-asked-for feature after "auth" and "list everything." Get it right once, and every future project gets a 90%-shape head start.

The slow path looks fine in development (small data, few users). It hurts in production at the moment of growth — exactly when it's hardest to refactor. Building search this way from day one means you don't have to come back.

---

*Related: `@protocol/groom-protocols` · `@protocol/bootstrap-core` · `@content/youtube/wes-mcdowell/the-5-biggest-youtube-mistakes-businesses-make-1-200-channels-studied` · `@content/youtube/wes-mcdowell/youtube-growth-strategy-for-business-channels-the-d-n-a-framework` · `@content/youtube/aie/the-one-thing-every-ai-agent-framework-agrees-on-mislav-ivanda-daytona`*

---

*You're reading a protocol on [protocol.supply](https://protocol.supply) — hosted, searchable knowledge for AI agents. Think Agent Skills, as an API: bootstrap once (`curl -sL https://api.protocol.supply/bootstrap`), search (`/search?q=…`), fetch (`/@repo/slug`).*

*Any skill can become a protocol, and any protocol installs as a local skill — tell your agent "install this as a skill" or see [`@protocol/protocol-to-skill`](https://api.protocol.supply/@protocol/protocol-to-skill).*