跳到内容
光环标志
光环基地

Indexes

Make the slow queries of your project fast: pick the index type for the query, create it in SQL or Studio, confirm with EXPLAIN that PostgreSQL uses it, and drop the ones that only cost writes.

操作指南10分钟 读取级别 中间

此页面尚不支持您的语言。它以英文显示。

An index lets PostgreSQL find rows without reading the whole table. It speeds up the queries that match its columns and slows down every insert, update and delete a little, since each index is updated with the table. Create one for a query you have measured, not for every column.

Prerequisites#

  • A linked project: aura link <project-id>.

  • The example schema, installed with the service role key of the project:

    export AURABASE_SERVICE_ROLE_KEY=aura_sk_…
    aura db seed --example docs

    It creates profiles, orgs, org_members, posts, todos, the view open_todos and the function todo_count(p_user uuid). See Example schema.

The examples create the table sch_idx_events with 20,000 rows, then remove it. The example schema already has two indexes: todos_user_id_idx and posts_user_id_idx.

Choose an index#

QueryIndexExample
=, <, >, between, order by on one columnB-tree (the default)create index on todos (user_id)
No duplicates allowedUnique (or a unique constraint)create unique index on profiles (lower(username))
Filter on one column, sort on anotherComposite, filtered column first(user_id, created_at desc)
A small, often-read part of the tablePartial… (created_at) where kind = 'error'
A function of a columnExpression… (lower(email))
jsonb containment (@>), keys (?)GINusing gin (payload jsonb_path_ops)
Arrays (@>, &&), full text (@@)GINusing gin (tags), using gin (search)
like '%word%', similarityGIN with pg_trgmusing gin (title gin_trgm_ops)
Ranges, overlaps, exclusion constraintsGiSTusing gist (during)
Very large tables in time orderBRINusing brin (created_at)
Nearest vectorsHNSW or IVFFlat (pgvector)using hnsw (embedding vector_cosine_ops)

A primary key and each unique constraint already create a B-tree index. A foreign key does not: index the referencing column when you filter on it or delete from the parent table. pg_trgm, btree_gin, btree_gist and vector are installed in every project.

Where to create an index#

DoorWhat it can create
SQL with aura db raw or the Studio SQL editorAny index, except concurrently (see Large tables).
Studio, Index tab of a tableColumns, unique, method (btree, gin, gist, hash, brin, hnsw, ivfflat) and an optional where clause; it runs the create index as a migration of the project.
Schema API, POST /v1/db/{project_id}/schema/tablesThe indexes of a table at its creation only (name, columns, unique, method, where_clause). The index is named <table>_<name>.
aura db tableNo index command.

A table to index#

create table sch_idx_events (
  id bigint generated always as identity primary key,
  user_id uuid not null,
  kind text not null,
  payload jsonb not null default '{}',
  created_at timestamptz not null default now()
);

insert into sch_idx_events (user_id, kind, payload, created_at)
select
  ('00000000-0000-4000-8000-' || lpad((i % 500)::text, 12, '0'))::uuid,
  case when i % 50 = 0 then 'error' else 'view' end,
  jsonb_build_object('page', '/p/' || (i % 40), 'ms', i % 900),
  timestamptz '2026-11-01' + i * interval '1 minute'
from generate_series(1, 20000) as i;

analyze sch_idx_events;
  ℹ No results (0 rows).

analyze refreshes the statistics the planner uses; PostgreSQL also does it in the background after enough writes.

Read the plan before#

explain shows how PostgreSQL will run a query, without running it. (costs off) hides the estimates, which change from one run to the next:

aura db raw "explain (costs off) select id, kind from sch_idx_events where user_id = '00000000-0000-4000-8000-000000000042' order by created_at desc limit 10"
  QUERY PLAN
  ──────────────────────────────────────────────────────────────────────────────
  Limit
    ->  Sort
          Sort Key: created_at DESC
          ->  Seq Scan on sch_idx_events
                Filter: (user_id = '00000000-0000-4000-8000-000000000042'::uuid)

  ℹ 5 row(s).

Seq Scan reads all 20,000 rows to keep the 40 of this user, then sorts them. explain analyze runs the query and adds the real times and row counts; use it on reads only, since it executes the statement.

Create the indexes#

create index sch_idx_events_user_created on sch_idx_events (user_id, created_at desc);
create index sch_idx_events_errors on sch_idx_events (created_at) where kind = 'error';
create index sch_idx_events_payload on sch_idx_events using gin (payload jsonb_path_ops);
  ℹ No results (0 rows).
  • sch_idx_events_user_created serves "the latest events of a user": the filter column first, then the sort column in the order of the query.
  • sch_idx_events_errors only holds the 400 error rows: small, and used by any query that has kind = 'error' in its filter.
  • sch_idx_events_payload serves payload @> '{…}'. jsonb_path_ops is smaller and faster for @> than the default jsonb_ops, but does not support the key operators ?, ?|, ?&.

Read the plan after#

aura db raw "explain (costs off) select id, kind from sch_idx_events where user_id = '00000000-0000-4000-8000-000000000042' order by created_at desc limit 10"
aura db raw "explain (costs off) select id from sch_idx_events where payload @> '{\"page\": \"/p/7\"}'"
  QUERY PLAN
  ────────────────────────────────────────────────────────────────────────────
  Limit
    ->  Index Scan using sch_idx_events_user_created on sch_idx_events
          Index Cond: (user_id = '00000000-0000-4000-8000-000000000042'::uuid)

  ℹ 3 row(s).
  QUERY PLAN
  ──────────────────────────────────────────────────────────────
  Bitmap Heap Scan on sch_idx_events
    Recheck Cond: (payload @> '{"page": "/p/7"}'::jsonb)
    ->  Bitmap Index Scan on sch_idx_events_payload
          Index Cond: (payload @> '{"page": "/p/7"}'::jsonb)

  ℹ 4 row(s).

The first query reads the index in order and stops after ten entries: no sort, no full scan. On a small table PostgreSQL may keep a Seq Scan even with an index, because reading a few pages is cheaper; judge an index on realistic volumes.

Index vectors#

Without an index, a nearest-neighbour query compares the query vector with every row. HNSW gives fast approximate results; build it with the operator class of the distance you order by (vector_l2_ops for <->, vector_cosine_ops for <=>, vector_ip_ops for <#>):

create table sch_idx_docs (id bigint generated always as identity primary key, embedding vector(3));
insert into sch_idx_docs (embedding) values ('[1,0,0]'), ('[0,1,0]'), ('[0.9,0.1,0]');
create index sch_idx_docs_embedding on sch_idx_docs using hnsw (embedding vector_cosine_ops);
  ℹ No results (0 rows).

Building an HNSW index on many rows takes memory and time: on a large table, build it through the direct connection (see below). Choose column types shows the distance operators.

Large tables and concurrent builds#

create index blocks writes to the table while it builds. create index concurrently avoids that, but PostgreSQL refuses it inside a transaction, and aura db raw runs every request in one:

aura db raw "create index concurrently sch_idx_events_kind on sch_idx_events (kind)" || echo "exit code: $?"
Error: [400] BAD_REQUEST: Invalid request: CREATE INDEX CONCURRENTLY cannot run inside a transaction block
exit code: 1

A build also has to finish within the statement timeout of the endpoint, 10 seconds by default. For a large table, connect with the direct connection (Connect to your database), which runs statements outside a transaction and has no statement timeout, and run create index concurrently there.

Find unused indexes#

/raw refuses the catalog views (pg_indexes, pg_stat_user_indexes), so aura db inspect indexes reads them for you: each index with its table, size, number of scans since the statistics were last reset, and an unused flag for indexes never scanned that are neither unique nor primary.

aura db inspect indexes | grep -c 'sch_idx_events'
4

Output of aura db inspect indexes (sizes and scan counts differ on your project):

» Inspect: indexes
  index_name | is_unique | scans | size_bytes | table_name | unused
  sch_idx_events_payload | false | 1 | 65536 | sch_idx_events | false
  sch_idx_events_errors | false | 0 | 16384 | sch_idx_events | true
  …
  ℹ 1 unused index(es) (never scanned, not unique/primary): consider dropping them.

An index that stays unused under real traffic only costs writes and storage: drop it with drop index <name>. Studio shows the indexes of a table in its Index tab. Slow queries themselves are listed by aura db slow-queries; see Performance.

Result#

The table has its three new indexes, with their method and the condition of the partial one. aura db table list --json lists the indexes of each table except the primary key's:

aura db table list --json | node -e 'const t = JSON.parse(require("fs").readFileSync(0, "utf8")).find((x) => x.name === "sch_idx_events")
for (const i of t.indexes) console.log(i.name, i.method ?? "", i.where_clause ?? "")'
sch_idx_events_errors btree (kind = 'error'::text)
sch_idx_events_payload gin
sch_idx_events_user_created btree

Common errors#

MessageCauseFix
CREATE INDEX CONCURRENTLY cannot run inside a transaction blockconcurrently through aura db raw, the SDK db.sql() or the Studio SQL editor.Use the direct connection, or a plain create index on a small table.
relation "…" already existsAn index (or table) with the same name exists in the project.Pick another name, or create index if not exists.
A message containing the query ran longer than this project's statement timeout (10 s)The build took longer than the endpoint allows (10 s by default).Build it through the direct connection.
could not create unique index "…"A unique index on a column that already has duplicates.Remove the duplicates first.
A Seq Scan remains after creating the indexSmall table, stale statistics, or a filter that does not match the index (a function, another column order).analyze <table>; match the indexed expression and column order.

Clean up#

Dropping the tables drops their indexes:

drop table if exists sch_idx_events;
drop table if exists sch_idx_docs;
  ℹ No results (0 rows).

See also#

@aurabase/aurabase-js@0.7.5 · aura@0.3.4↗ 报告问题