@neon/skills 1.1.2 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -1
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/skills/neon/SKILL.md +15 -5
- package/skills/neon-ai-gateway/SKILL.md +2 -2
- package/skills/neon-functions/SKILL.md +85 -46
- package/skills/neon-functions/references/mastra-studio.md +2 -2
- package/skills/neon-functions/references/sse.md +8 -5
- package/skills/neon-object-storage/SKILL.md +2 -2
- package/skills/neon-postgres/SKILL.md +18 -2
- package/skills/neon-postgres/references/full-text-search.md +99 -0
- package/skills/neon-postgres/references/hybrid-search.md +90 -0
- package/skills/neon-postgres/references/vector-search.md +137 -0
package/README.md
CHANGED
|
@@ -111,7 +111,13 @@ Plugin changes apply to new sessions, so run `/new` afterward.
|
|
|
111
111
|
|
|
112
112
|
### Pi
|
|
113
113
|
|
|
114
|
-
You can also install the skills in [Pi](https://pi.dev)
|
|
114
|
+
You can also install the skills in [Pi](https://pi.dev) from npm:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
pi install npm:@neon/skills
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Or straight from this repo:
|
|
115
121
|
|
|
116
122
|
```bash
|
|
117
123
|
pi install git:github.com/neondatabase/agent-skills
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neon/skills",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Agent Skills for Neon: Lakebase Postgres, branching, Object Storage, Functions, and the AI Gateway",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"validate:ci": "npm run validate:agent-plugin && npm run validate:plugins && npm run validate:versions && npm run validate:skills && npm run validate:references"
|
|
50
50
|
},
|
|
51
51
|
"devDependencies": {
|
|
52
|
-
"prettier": "3.9.
|
|
52
|
+
"prettier": "3.9.6",
|
|
53
53
|
"skills-ref": "0.1.5"
|
|
54
54
|
}
|
|
55
55
|
}
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "neon-postgres",
|
|
4
|
-
"version": "1.
|
|
4
|
+
"version": "1.2.0",
|
|
5
5
|
"description": "Manage your Neon backend with the Neon agent skills and the Neon MCP Server: Lakebase Postgres, branching, Object Storage, Functions, and the AI Gateway",
|
|
6
6
|
"author": {
|
|
7
7
|
"name": "Neon",
|
package/skills/neon/SKILL.md
CHANGED
|
@@ -41,7 +41,7 @@ Neon bundles several backend primitives for building apps and agents that all br
|
|
|
41
41
|
|
|
42
42
|
Object Storage, Functions, and AI Gateway are in public beta.
|
|
43
43
|
|
|
44
|
-
Beta access features are
|
|
44
|
+
Beta access features are currently available on projects in `us-east-2` and `eu-central-1`. Before guiding a user through any of these services, confirm they are working in one of these regions. If not, they will need to create a new project in a supported region.
|
|
45
45
|
|
|
46
46
|
## Architecture: How to Use Neon
|
|
47
47
|
|
|
@@ -86,7 +86,7 @@ The skills below live in the [`neondatabase/agent-skills`](https://github.com/ne
|
|
|
86
86
|
|
|
87
87
|
| Skill | Use it for |
|
|
88
88
|
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
|
89
|
-
| `neon-postgres` | Working with databases, including connections, schemas, queries, and autoscaling: SQL development, schema design, performance optimization, and scaling decisions.
|
|
89
|
+
| `neon-postgres` | Working with databases, including connections, schemas, queries, search, and autoscaling: SQL development, schema design, performance optimization, and scaling decisions. |
|
|
90
90
|
| `neon-postgres-branches` | Choosing or creating the right branch type for dev, preview, test, or CI workflows. Use this skill as a slash command. |
|
|
91
91
|
| `neon-object-storage` | Storing and serving files (uploads, images, blobs), including branching them with the database. |
|
|
92
92
|
| `neon-functions` | Deploying long-running or streaming serverless functions — APIs, agents, SSE/WebSocket servers. |
|
|
@@ -243,11 +243,21 @@ Reconcile the declaration from the CLI — the Neon equivalent of `terraform sta
|
|
|
243
243
|
```bash
|
|
244
244
|
neon status # print the branch's live config (read-only). Alias for `neon config status`.
|
|
245
245
|
neon config plan # dry-run diff of what apply would change (read-only)
|
|
246
|
-
neon deploy
|
|
246
|
+
neon deploy --env <file> # apply neon.ts. Pass --env when Function env reads process.env. Alias for `neon config apply`
|
|
247
247
|
```
|
|
248
248
|
|
|
249
249
|
`apply` / `deploy` provision the declared services **and then pull the branch's env into your local `.env.local`** (e.g. `Pulled 5 Neon variables into .env.local: DATABASE_URL, …`), so your local env always matches what's deployed.
|
|
250
250
|
|
|
251
|
+
### Function env and `neon deploy`
|
|
252
|
+
|
|
253
|
+
`neon deploy` is the preferred full deployment: it applies `neon.ts` (services and functions) to the linked branch. `neon deploy --env <file>` loads that file into `process.env` before evaluating `neon.ts`, then uploads those values as Function env. Use it every time Function env reads `process.env`.
|
|
254
|
+
|
|
255
|
+
`<file>` is the gitignored file `neon env pull` already writes (`.env` if that file exists, otherwise `.env.local`). Env pull writes Neon-managed vars only (`DATABASE_URL`, `NEON_AI_GATEWAY_*`, …). Add every key under `preview.functions.*.env` to that file yourself, then pass the same path to `--env`.
|
|
256
|
+
|
|
257
|
+
Every declared Function env key must be a defined string. `undefined` (an unset `process.env.X`) means you listed a key you want written but the value is missing: `defineConfig` throws. Omit the key from `neon.ts` if you do not want to write it. Never coerce a missing `process.env` value to an empty string: that uploads `""` and deletes the live key. An empty assignment in the file (`KEY=`) is also `""`. If TypeScript needs a type assertion, use `process.env.X!` and make sure the file actually has the value.
|
|
258
|
+
|
|
259
|
+
Use `neon functions deploy` when you are not applying `neon.ts`: a single function by slug, or a targeted `--env KEY=VALUE` update (that flag is not a file path).
|
|
260
|
+
|
|
251
261
|
### Type-safe env vars with parseEnv
|
|
252
262
|
|
|
253
263
|
`@neon/env`'s `parseEnv` takes your `neon.ts` config object and returns a parsed, typed env object, validated against the services you declared. The shape of `env` follows your config, and missing variables are flagged with clear errors.
|
|
@@ -364,7 +374,7 @@ Because `link` and `checkout` pull env by default, the branch's `DATABASE_URL` l
|
|
|
364
374
|
|
|
365
375
|
### How checkout composes with neon.ts
|
|
366
376
|
|
|
367
|
-
When a `neon.ts` is present, `neon checkout` applies your policy as it **creates** a branch, so a fresh branch comes up with its declared settings and services already in place. Checking out an _existing_ branch never reconciles it — apply config changes to it explicitly with `neon
|
|
377
|
+
When a `neon.ts` is present, `neon checkout` applies your policy as it **creates** a branch, so a fresh branch comes up with its declared settings and services already in place. That create-apply does not load `--env`; if Function env reads `process.env`, run `neon deploy --env <file>` after checkout (add `--update-existing` if checkout already created the branch). Checking out an _existing_ branch never reconciles it — apply config changes to it explicitly with `neon deploy --env <file>` (alias for `neon config apply`). The bundled `env pull` also checks `neon.ts` against the linked branch and fails fast if the branch is missing a declared service, pointing you at `neon deploy --env <file>` to provision it, so your local env and the remote branch never drift apart silently.
|
|
368
378
|
|
|
369
379
|
### Opting out of local env vars
|
|
370
380
|
|
|
@@ -381,7 +391,7 @@ For reading env you _already_ have on disk (typed and validated against your `ne
|
|
|
381
391
|
|
|
382
392
|
## Observability
|
|
383
393
|
|
|
384
|
-
Neon exposes branch-scoped logs. **Today they cover Neon Functions and Object Storage only.** Postgres computes and the AI Gateway are coming; until then, neither emits records. Logs are region-gated like the other beta services above.
|
|
394
|
+
Neon exposes branch-scoped logs. **Today they cover Neon Functions and Object Storage only.** Postgres computes and the AI Gateway are coming; until then, neither emits records. Logs are region-gated like the other beta services above. `us-east-2` and `eu-central-1` are enabled today. A branch that can't serve logs at all answers `404` with `reason: telemetry_not_enabled` (the message says whether it's the wrong region or a branch not collecting telemetry yet), versus a `200` empty result when the branch is enabled but has no records in the window; an unknown branch answers `reason: branch_not_found`.
|
|
385
395
|
|
|
386
396
|
Use Neon CLI 3.1 or newer first. **Decide which branch you are querying.** Without `--branch`, the CLI uses the branch pinned in `.neon`, or the project's default branch when the workspace isn't linked. A deployed function or bucket usually lives on a different branch than the one checked out for development, so an empty result is more often the wrong branch than a missing log.
|
|
387
397
|
|
|
@@ -27,7 +27,7 @@ npx skills add neondatabase/agent-skills --skill neon
|
|
|
27
27
|
|
|
28
28
|
# Neon AI Gateway
|
|
29
29
|
|
|
30
|
-
This is a public beta feature
|
|
30
|
+
This is a public beta feature, currently available in `us-east-2` and `eu-central-1`.
|
|
31
31
|
|
|
32
32
|
The Neon AI Gateway is the LLM inference layer built into your Neon branch: one API and one Neon credential give you access to frontier and open-source models from many providers (Anthropic, OpenAI, Google, Meta, and more), all hosted and powered by Databricks. The catalog shifts over time, so treat `/v1/models` and the [models.dev Neon page](https://models.dev/providers/neon) as the source of truth rather than a fixed provider list. Your existing OpenAI/Anthropic/Gemini SDK works by changing only the base URL.
|
|
33
33
|
|
|
@@ -55,7 +55,7 @@ If the user already has a deep, single-provider integration and no interest in N
|
|
|
55
55
|
|
|
56
56
|
Check these preconditions before setting anything up:
|
|
57
57
|
|
|
58
|
-
The AI Gateway is a public beta feature available in
|
|
58
|
+
The AI Gateway is a public beta feature currently available in `us-east-2` and `eu-central-1`. Foundation model access requires a paid Neon plan. Confirm the user's project is in one of these regions.
|
|
59
59
|
|
|
60
60
|
### Enabling the gateway: plan and model-catalog gating
|
|
61
61
|
|
|
@@ -27,7 +27,7 @@ npx skills add neondatabase/agent-skills --skill neon
|
|
|
27
27
|
|
|
28
28
|
# Neon Functions
|
|
29
29
|
|
|
30
|
-
This is a public beta feature
|
|
30
|
+
This is a public beta feature, currently available in `us-east-2` and `eu-central-1`.
|
|
31
31
|
|
|
32
32
|
Neon Functions are long-running Node.js HTTP handlers deployed onto a Neon branch. Each function gets a public HTTPS URL, runs in the same region as your database, and — if the branch has Postgres — gets `DATABASE_URL` injected automatically. You deploy and manage them through the same Neon CLI, `neon.ts`, and API you already use.
|
|
33
33
|
|
|
@@ -43,7 +43,7 @@ Reach for Neon Functions when the workload is a request/response handler that be
|
|
|
43
43
|
- **A backend that branches with your data.** Each branch runs its own version of the function at its own URL, against its own isolated database (and storage, and gateway) state. Preview deployments, CI, and dev environments each get a self-contained backend — deploying to a child never affects the parent.
|
|
44
44
|
- **Webhooks, bots, and post-response work.** Webhook handlers that fan out into multiple DB writes, Discord/WebSocket bots, and fire-and-forget follow-ups via `waitUntil` (analytics, audit logs) all fit.
|
|
45
45
|
|
|
46
|
-
If the workload is a pure static site, a cron/background job that needs its own lifecycle and cancellation, or something that must run outside `us-east-2` today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).
|
|
46
|
+
If the workload is a pure static site, a cron/background job that needs its own lifecycle and cancellation, or something that must run outside the supported regions (`us-east-2`, `eu-central-1`) today, this isn't the right tool yet (see [Timeouts and Runtime Limits](#timeouts-and-runtime-limits) and [Availability](#availability)).
|
|
47
47
|
|
|
48
48
|
## What It Does
|
|
49
49
|
|
|
@@ -55,7 +55,7 @@ If the workload is a pure static site, a cron/background job that needs its own
|
|
|
55
55
|
|
|
56
56
|
## Availability
|
|
57
57
|
|
|
58
|
-
Check this precondition before setting anything up: Neon Functions is a public beta feature available in
|
|
58
|
+
Check this precondition before setting anything up: Neon Functions is a public beta feature currently available in `us-east-2` and `eu-central-1`. Confirm the user's Neon project is in one of these regions. Functions usage isn't billed during the public beta.
|
|
59
59
|
|
|
60
60
|
## Architecture: Where Functions Fit
|
|
61
61
|
|
|
@@ -132,12 +132,14 @@ attachDatabasePool(pool);
|
|
|
132
132
|
|
|
133
133
|
```bash
|
|
134
134
|
neon dev # serves every function in neon.ts with hot reload; injects DATABASE_URL & friends
|
|
135
|
-
neon deploy #
|
|
135
|
+
neon deploy --env <file> # preferred full deploy from neon.ts; --env is the file Function env is read from
|
|
136
136
|
```
|
|
137
137
|
|
|
138
|
-
|
|
138
|
+
Keep `.env` or `.env.local` up to date with every key under `preview.functions.*.env`. `neon env pull` writes Neon-managed vars only; add Function secrets to that file, then pass it as `--env`. `neon deploy --env <file>` loads that file into `process.env` each time, then uploads those values. A missing value is `undefined` and `defineConfig` throws. Omit the key from `neon.ts` if you do not want to write it. Never coerce a missing `process.env` value to an empty string (that uploads `""` and deletes the live key). An empty assignment (`KEY=`) is also `""`. Use `process.env.X!` when TypeScript needs an assertion.
|
|
139
139
|
|
|
140
|
-
|
|
140
|
+
To deploy a single function without applying `neon.ts`: `neon functions deploy <slug> --src src/index.ts` (`--src` takes either the entry file or a directory containing `index.ts`, `index.mjs`, or `index.js`). That command's `--env` is `KEY=VALUE` (repeatable), not a file path. Use it for a targeted env update. Retrieve the public URL with `neon functions get <slug>` (the `invocation_url` field, of the form `https://<branch_id>-<slug>.compute.<cell>.us-east-2.aws.neon.tech`). Manage with `neon functions list|get|delete`.
|
|
141
|
+
|
|
142
|
+
When `neon checkout` _creates_ a new branch and a `neon.ts` is present, it applies the policy automatically. That create-apply does not load `--env`. If Function env reads `process.env`, run `neon deploy --env <file>` after checkout (add `--update-existing` if checkout already created the branch). Checking out an existing branch does not re-deploy; run `neon deploy --env <file>` explicitly.
|
|
141
143
|
|
|
142
144
|
## Neon Infrastructure as Code (`neon.ts`)
|
|
143
145
|
|
|
@@ -146,10 +148,10 @@ The `preview.functions` block from [Setup](#setup) is part of `neon.ts`, Neon's
|
|
|
146
148
|
```bash
|
|
147
149
|
neon config status # print the branch's live config (deployed functions)
|
|
148
150
|
neon config plan # dry-run diff of what apply would change
|
|
149
|
-
neon config apply
|
|
151
|
+
neon config apply --env <file> # bundle + deploy the declared functions (neon deploy is an alias; pass --env when Function env reads process.env)
|
|
150
152
|
```
|
|
151
153
|
|
|
152
|
-
Functions are **branch-scoped**: each branch runs its own deployment at its own URL. When a `neon.ts` is present, `neon checkout` applies the policy as it _creates_ a branch
|
|
154
|
+
Functions are **branch-scoped**: each branch runs its own deployment at its own URL. When a `neon.ts` is present, `neon checkout` applies the policy as it _creates_ a branch. That create-apply does not load `--env`. If Function env reads `process.env`, run `neon deploy --env <file>` after checkout. Checking out an _existing_ branch doesn't redeploy — run `neon deploy --env <file>` to apply changes.
|
|
153
155
|
|
|
154
156
|
Per-branch deploy tuning (e.g. `runtime`) lives in the `branch` closure, keyed by slug, so it can vary by branch without changing which functions exist:
|
|
155
157
|
|
|
@@ -180,7 +182,7 @@ Object storage (`AWS_*`) and AI Gateway (`NEON_AI_GATEWAY_*`) vars are also inje
|
|
|
180
182
|
|
|
181
183
|
`neon env pull` / `neon-env run` / `neon dev` emit `NEON_BRANCH` (and the connection strings) into your local dev environment too, so local runs mirror the deployed runtime.
|
|
182
184
|
|
|
183
|
-
**Your own secrets** are per-deployment.
|
|
185
|
+
**Your own secrets** are per-deployment. Preferred path: declare them in `neon.ts` and run `neon deploy --env <file>`. `<file>` is the gitignored file env pull already writes (`.env` if that file exists, otherwise `.env.local`). Env pull writes Neon-managed vars only; add Function secrets to that file. All declared Function env keys must be present. Omit a key from `neon.ts` if you do not want to write it. `undefined` means you asked to write the key and the value is missing (`defineConfig` throws). Never coerce a missing `process.env` value to an empty string: that uploads `""` and deletes the live key. An empty assignment in the file (`KEY=`) is also `""`. If TypeScript needs an assertion, use `process.env.X!` and make sure the file has the value:
|
|
184
186
|
|
|
185
187
|
```typescript
|
|
186
188
|
functions: {
|
|
@@ -192,7 +194,9 @@ functions: {
|
|
|
192
194
|
}
|
|
193
195
|
```
|
|
194
196
|
|
|
195
|
-
|
|
197
|
+
`neon functions deploy --env KEY=VALUE` is the manual path (repeatable; `--env KEY=` deletes a key; unmentioned keys carry over). Use it for a targeted env update, not a full `neon.ts` apply.
|
|
198
|
+
|
|
199
|
+
Load Function secrets into the same file env pull wrote, then `neon deploy --env <file>`. Pull the branch's Neon-managed vars onto disk for local dev with `neon env pull` (`link`/`checkout` do this automatically; pass `--no-env-pull` to skip and use `neon-env run -- <cmd>` for runtime injection). Limits: ≤1,000 vars, ≤64 KiB total, and the `NEON_` prefix is reserved.
|
|
196
200
|
|
|
197
201
|
## Connecting to Postgres
|
|
198
202
|
|
|
@@ -296,7 +300,7 @@ Pass the JWKS/issuer URL to the function via its `env` (see [Environment Variabl
|
|
|
296
300
|
|
|
297
301
|
A WebSocket server is the canonical Functions workload: a long-running handler holds connections open in-process, with no external state store needed to keep a stream coherent. The connection stays alive as long as bytes flow (15-minute heartbeat, see [Timeouts](#timeouts-and-runtime-limits)).
|
|
298
302
|
|
|
299
|
-
**Upgrade from inside `fetch`.** Call `upgradeWebSocket(request)` from [`@neon/functions`](https://www.npmjs.com/package/@neon/functions) and return the response it gives you. There is one entrypoint and no WebSocket dependency to install:
|
|
303
|
+
**Upgrade from inside `fetch`.** Call `upgradeWebSocket(request)` from [`@neon/functions`](https://www.npmjs.com/package/@neon/functions) and return the response it gives you. Hono apps use the same primitive via `@neon/functions/hono` (see [Hono](#hono) below). There is one entrypoint and no WebSocket dependency to install:
|
|
300
304
|
|
|
301
305
|
```typescript
|
|
302
306
|
import { upgradeWebSocket } from "@neon/functions";
|
|
@@ -319,7 +323,7 @@ export default {
|
|
|
319
323
|
Three rules that matter:
|
|
320
324
|
|
|
321
325
|
- **Return `response` unchanged.** A `101` can't be built as a plain `Response` (the fetch spec caps constructed responses at 200–599), so the runtime hands back an object carrying the pending upgrade. `clone()`, or rebuilding it with `new Response(res.body, res)` as response-rewriting middleware does, discards the upgrade and fails the request.
|
|
322
|
-
- **Refuse a handshake by returning an ordinary `Response`.**
|
|
326
|
+
- **Refuse a handshake by returning an ordinary `Response`.** Return a `401`, `403`, or `404` from `fetch`, before you upgrade, to gate a socket. A browser client can't read why a handshake was refused; it sees only a generic connection failure, not your status or body. Refuse to keep clients out, but send any detail the client needs over a separate authenticated request.
|
|
323
327
|
- **`binaryType` defaults to `"arraybuffer"`**, not the browser's `"blob"`. `event.data` is a `string` for text frames and an `ArrayBuffer` for binary ones, so branch on `typeof`.
|
|
324
328
|
|
|
325
329
|
**With auth.** Browsers can't set headers on a WebSocket, so authenticate with a `?token=` query param (verify it the same way as the [agent backend](#functions-as-an-agent-backend-nextjs-and-similar-frameworks): `jwtVerify` against your JWKS) and refuse before upgrading:
|
|
@@ -354,37 +358,52 @@ export default {
|
|
|
354
358
|
|
|
355
359
|
**Subprotocols.** Pass `{ protocol }` to select one the client offered; it is echoed in `Sec-WebSocket-Protocol` and exposed as `socket.protocol`. Selecting one the client did not offer throws a `TypeError`. Omit it and no protocol is negotiated. No extensions are negotiated either — `socket.extensions` is always `""` and `permessage-deflate` is not available.
|
|
356
360
|
|
|
357
|
-
**Hono.**
|
|
361
|
+
**Hono.** Use `upgradeWebSocket` from `@neon/functions/hono` — the same primitive as Hono's own WebSocket helper, with no `ws` dependency and not the deprecated `@hono/node-ws`. Auth is ordinary middleware; gate upgrade requests before `next()`:
|
|
358
362
|
|
|
359
363
|
```typescript
|
|
360
364
|
// src/index.ts
|
|
361
365
|
import { Hono } from "hono";
|
|
362
|
-
import { upgradeWebSocket } from "@neon/functions";
|
|
366
|
+
import { upgradeWebSocket } from "@neon/functions/hono";
|
|
363
367
|
|
|
364
|
-
const
|
|
368
|
+
const clients = new Set<WebSocket>();
|
|
365
369
|
|
|
366
|
-
app
|
|
370
|
+
const app = new Hono<{ Variables: { userId: string } }>();
|
|
367
371
|
|
|
368
|
-
app.
|
|
372
|
+
app.use("/ws", async (c, next) => {
|
|
369
373
|
const identity = await verifyToken(c.req.query("token"));
|
|
370
374
|
if (!identity) return c.text("Unauthorized", 401);
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
socket.addEventListener("open", () => socket.send("welcome"));
|
|
374
|
-
socket.addEventListener("message", (event) =>
|
|
375
|
-
socket.send(`echo: ${event.data}`),
|
|
376
|
-
);
|
|
377
|
-
return response;
|
|
375
|
+
c.set("userId", identity.id);
|
|
376
|
+
await next();
|
|
378
377
|
});
|
|
379
378
|
|
|
380
|
-
|
|
379
|
+
app.get(
|
|
380
|
+
"/ws",
|
|
381
|
+
upgradeWebSocket((c) => ({
|
|
382
|
+
onOpen(_event, ws) {
|
|
383
|
+
clients.add(ws.raw);
|
|
384
|
+
ws.send("welcome");
|
|
385
|
+
},
|
|
386
|
+
onClose(_event, ws) {
|
|
387
|
+
clients.delete(ws.raw);
|
|
388
|
+
},
|
|
389
|
+
onMessage(event, ws) {
|
|
390
|
+
ws.send(`echo: ${event.data}`);
|
|
391
|
+
},
|
|
392
|
+
})),
|
|
393
|
+
);
|
|
394
|
+
|
|
395
|
+
export default app;
|
|
381
396
|
```
|
|
382
397
|
|
|
398
|
+
Connect from the browser with the function's `wss://` URL (from `neon functions get <slug>`), for example `new WebSocket("wss://<branch>-<slug>.compute.<region>.aws.neon.tech/ws?token=<jwt>")`. Reconnect on close — isolates are evictable and idle connections may be terminated after 15 minutes.
|
|
399
|
+
|
|
400
|
+
Do not put `cors()` on the upgrade route, and do not read `c.res` before `await next()` or call `c.header()` after it — both rebuild the `101` and break the upgrade. See `@neon/functions` README for the full middleware table.
|
|
401
|
+
|
|
383
402
|
### Heartbeat (keep the socket alive)
|
|
384
403
|
|
|
385
404
|
A connection stays open **only while bytes flow**: Neon evicts a silent stream after 15 minutes ([Timeouts and Runtime Limits](#timeouts-and-runtime-limits)), and intermediary proxies / load balancers are usually far stricter (often tens of seconds). Don't rely on the app being chatty enough — send a periodic keepalive from the server so the socket never goes quiet.
|
|
386
405
|
|
|
387
|
-
The standard `WebSocket` interface has no `ping()`, so send an application-level message the client
|
|
406
|
+
The standard `WebSocket` interface has no `ping()`, so send an application-level message the client filters out:
|
|
388
407
|
|
|
389
408
|
```typescript
|
|
390
409
|
const HEARTBEAT_MS = 25_000; // comfortably under proxy idle timeouts
|
|
@@ -397,7 +416,7 @@ const beat = setInterval(() => {
|
|
|
397
416
|
beat.unref?.();
|
|
398
417
|
```
|
|
399
418
|
|
|
400
|
-
The client
|
|
419
|
+
The client skips these when handling messages. There is no protocol-level shortcut here: the standard `WebSocket` from `upgradeWebSocket` has no `ping()`, and a browser can't send ping frames from JavaScript, so an application-level message is the only keepalive a browser client can use. (A Node `ws` client can send ping frames, and the server auto-replies with a pong, but a browser can't.)
|
|
401
420
|
|
|
402
421
|
### Keeping clients in sync across isolates (do not skip this)
|
|
403
422
|
|
|
@@ -408,26 +427,42 @@ Module state doesn't survive eviction anyway, so **Postgres is the shared source
|
|
|
408
427
|
**1. Poll Postgres — the default, and the only option that keeps Scale to Zero.** Each isolate re-reads the shared state (or rows past a cursor) on a short interval and pushes changes to its own clients. One query per isolate per tick (not per client), and none when the isolate has no clients — so an idle compute still suspends.
|
|
409
428
|
|
|
410
429
|
```typescript
|
|
411
|
-
let lastId = 0;
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
430
|
+
let lastId = "0"; // bigint id, so a string
|
|
431
|
+
let polling = false;
|
|
432
|
+
|
|
433
|
+
async function poll() {
|
|
434
|
+
if (polling || clients.size === 0) return; // guard overlap; no clients → no query → compute can scale to zero
|
|
435
|
+
polling = true;
|
|
436
|
+
try {
|
|
437
|
+
const { rows } = await pool.query(
|
|
438
|
+
"SELECT id, payload FROM events WHERE id > $1 ORDER BY id",
|
|
439
|
+
[lastId],
|
|
440
|
+
);
|
|
441
|
+
for (const { id, payload } of rows) {
|
|
442
|
+
lastId = id;
|
|
443
|
+
for (const socket of clients) {
|
|
444
|
+
if (socket.readyState === socket.OPEN) socket.send(payload);
|
|
445
|
+
}
|
|
422
446
|
}
|
|
447
|
+
} catch (err) {
|
|
448
|
+
console.error("[poll]", err);
|
|
449
|
+
} finally {
|
|
450
|
+
polling = false;
|
|
423
451
|
}
|
|
424
|
-
}
|
|
425
|
-
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
// Seed from the latest id so a fresh isolate sends only new rows, not the whole table, then poll.
|
|
455
|
+
pool
|
|
456
|
+
.query("SELECT coalesce(max(id), 0)::text AS id FROM events")
|
|
457
|
+
.then((seed) => { lastId = seed.rows[0].id; })
|
|
458
|
+
.catch((err) => console.error("[seed]", err))
|
|
459
|
+
.finally(() => setInterval(poll, 1000).unref?.());
|
|
426
460
|
```
|
|
427
461
|
|
|
428
462
|
- **Latency:** up to the interval (~1s) — fine for counters, chat, and dashboards.
|
|
429
463
|
- **Scaling:** database load grows with the number of live isolates, not clients. Keep the cursor on an indexed `serial`/`bigserial` PK and the interval sane.
|
|
430
464
|
- **Scale to Zero:** ✅ preserved — polling stops when no clients are connected, so the compute suspends on its normal timer.
|
|
465
|
+
- **Ordering:** `WHERE id > cursor` can skip a row that commits out of sequence: a transaction that took a lower id but commits after a higher one is already behind the cursor, so the poll never returns it. For a broadcast feed occasional loss is usually fine; when you need every row, use `LISTEN`/`NOTIFY` or poll by `created_at` with a small overlap window and dedupe by id.
|
|
431
466
|
|
|
432
467
|
**2. `LISTEN`/`NOTIFY` — lowest latency, but requires disabling Scale to Zero.** Each isolate `LISTEN`s on a channel over a dedicated **unpooled** connection; broadcasting is `NOTIFY`, so every isolate (including the sender's) re-pushes to its sockets. Near-instant — but the listener holds an idle connection that **does not count as active**, so [Scale to Zero](https://neon.com/docs/introduction/scale-to-zero) suspends the compute and drops it, silently killing the feed. Only use it on an **always-on** compute (Scale to Zero disabled — a paid-plan setting).
|
|
433
468
|
|
|
@@ -442,7 +477,7 @@ const CHANNEL = "chat_events";
|
|
|
442
477
|
// One dedicated DIRECT connection per isolate, just to receive events.
|
|
443
478
|
// Use DATABASE_URL_UNPOOLED — LISTEN needs a real session, not a pooled one.
|
|
444
479
|
// Don't call attachDatabasePool here: it would silence the idle drop that killed the feed.
|
|
445
|
-
//
|
|
480
|
+
// The error listener keeps the process alive; reconnect the client on error in production (omitted here).
|
|
446
481
|
const listener = new Client({
|
|
447
482
|
connectionString: process.env.DATABASE_URL_UNPOOLED,
|
|
448
483
|
});
|
|
@@ -508,16 +543,19 @@ When you only need **server → client** streaming (live counters, notifications
|
|
|
508
543
|
// src/index.ts — minimal SSE endpoint
|
|
509
544
|
const encoder = new TextEncoder();
|
|
510
545
|
export default {
|
|
511
|
-
fetch: () =>
|
|
512
|
-
|
|
546
|
+
fetch: () => {
|
|
547
|
+
let t: ReturnType<typeof setInterval>;
|
|
548
|
+
return new Response(
|
|
513
549
|
new ReadableStream<Uint8Array>({
|
|
514
550
|
start(controller) {
|
|
515
551
|
controller.enqueue(encoder.encode("data: hello\n\n"));
|
|
516
|
-
|
|
552
|
+
t = setInterval(
|
|
517
553
|
() => controller.enqueue(encoder.encode(": ping\n\n")),
|
|
518
554
|
25_000,
|
|
519
555
|
);
|
|
520
|
-
|
|
556
|
+
},
|
|
557
|
+
cancel() {
|
|
558
|
+
clearInterval(t); // fires when the client disconnects
|
|
521
559
|
},
|
|
522
560
|
}),
|
|
523
561
|
{
|
|
@@ -526,7 +564,8 @@ export default {
|
|
|
526
564
|
"Cache-Control": "no-cache, no-transform",
|
|
527
565
|
},
|
|
528
566
|
},
|
|
529
|
-
)
|
|
567
|
+
);
|
|
568
|
+
},
|
|
530
569
|
};
|
|
531
570
|
```
|
|
532
571
|
|
|
@@ -102,8 +102,8 @@ functions: {
|
|
|
102
102
|
name: "my app",
|
|
103
103
|
source: "src/index.ts",
|
|
104
104
|
env: {
|
|
105
|
-
MASTRA_PROJECT_ID: process.env.MASTRA_PROJECT_ID
|
|
106
|
-
MASTRA_PLATFORM_ACCESS_TOKEN: process.env.MASTRA_PLATFORM_ACCESS_TOKEN
|
|
105
|
+
MASTRA_PROJECT_ID: process.env.MASTRA_PROJECT_ID!,
|
|
106
|
+
MASTRA_PLATFORM_ACCESS_TOKEN: process.env.MASTRA_PLATFORM_ACCESS_TOKEN!,
|
|
107
107
|
},
|
|
108
108
|
},
|
|
109
109
|
}
|
|
@@ -17,17 +17,20 @@ export default {
|
|
|
17
17
|
const url = new URL(request.url);
|
|
18
18
|
if (url.pathname !== "/events") return new Response("ok");
|
|
19
19
|
|
|
20
|
+
let timer: ReturnType<typeof setInterval>;
|
|
20
21
|
const stream = new ReadableStream<Uint8Array>({
|
|
21
22
|
start(controller) {
|
|
22
23
|
// An SSE frame is `data: <payload>\n\n`. A line starting with `:` is a
|
|
23
24
|
// comment — used here as a heartbeat to keep the stream from going idle.
|
|
24
25
|
controller.enqueue(encoder.encode("data: hello\n\n"));
|
|
25
|
-
|
|
26
|
+
timer = setInterval(
|
|
26
27
|
() => controller.enqueue(encoder.encode(": ping\n\n")),
|
|
27
28
|
25_000,
|
|
28
29
|
);
|
|
29
|
-
|
|
30
|
-
|
|
30
|
+
},
|
|
31
|
+
// cancel() fires when the client disconnects.
|
|
32
|
+
cancel() {
|
|
33
|
+
clearInterval(timer);
|
|
31
34
|
},
|
|
32
35
|
});
|
|
33
36
|
|
|
@@ -42,7 +45,7 @@ export default {
|
|
|
42
45
|
};
|
|
43
46
|
```
|
|
44
47
|
|
|
45
|
-
> `cancel()` is
|
|
48
|
+
> `cancel()` is a method on the stream's underlying source; it fires when the client disconnects. Use it to drop the client from any broadcast set and clear timers. A cleanup function returned from `start()` is ignored, so it has to be a real `cancel()` method.
|
|
46
49
|
|
|
47
50
|
## With Hono
|
|
48
51
|
|
|
@@ -91,7 +94,7 @@ const CHANNEL = "events";
|
|
|
91
94
|
// One dedicated DIRECT connection per isolate to receive events (LISTEN needs a
|
|
92
95
|
// real session — use DATABASE_URL_UNPOOLED, not the pooled URL).
|
|
93
96
|
// Don't call attachDatabasePool here: it would silence the idle drop that killed the feed.
|
|
94
|
-
//
|
|
97
|
+
// The error listener keeps the process alive; reconnect the client on error in production (omitted here).
|
|
95
98
|
const listener = new Client({
|
|
96
99
|
connectionString: process.env.DATABASE_URL_UNPOOLED,
|
|
97
100
|
});
|
|
@@ -27,7 +27,7 @@ npx skills add neondatabase/agent-skills --skill neon
|
|
|
27
27
|
|
|
28
28
|
# Neon Object Storage
|
|
29
29
|
|
|
30
|
-
This is a public beta feature
|
|
30
|
+
This is a public beta feature, currently available in `us-east-2` and `eu-central-1`.
|
|
31
31
|
|
|
32
32
|
Neon Object Storage is S3-compatible object storage that branches with your projects: every branch gets its own isolated storage state, so files and database rows stay in sync across dev, preview, staging, and production.
|
|
33
33
|
|
|
@@ -53,7 +53,7 @@ If the files in question ship with the app itself — HTML, JS bundles, CSS, the
|
|
|
53
53
|
|
|
54
54
|
## Availability
|
|
55
55
|
|
|
56
|
-
Check this precondition before setting anything up: Neon Object Storage is a public beta feature available in
|
|
56
|
+
Check this precondition before setting anything up: Neon Object Storage is a public beta feature currently available in `us-east-2` and `eu-central-1`. Confirm the user's Neon project is in one of these regions before proceeding.
|
|
57
57
|
|
|
58
58
|
## Architecture: Where Object Storage Fits
|
|
59
59
|
|
|
@@ -5,12 +5,14 @@ description: >-
|
|
|
5
5
|
behind Neon. Covers setup, connection methods and drivers, pooled vs direct
|
|
6
6
|
connections, branching, schema migrations, autoscaling, scale-to-zero, instant
|
|
7
7
|
restore, read replicas, connection pooling, IP allow lists, and logical
|
|
8
|
-
replication.
|
|
8
|
+
replication. Also covers Lakebase Search: semantic vector search, full-text
|
|
9
|
+
search with BM25 ranking, and hybrid search.
|
|
9
10
|
Use when users ask about "Lakebase Postgres", "Neon setup", "connect to Neon",
|
|
10
11
|
"Neon project", "DATABASE_URL", "serverless Postgres", "Neon CLI", "neon", "Neon MCP",
|
|
11
12
|
"Neon Auth", "@neondatabase/serverless", "@neondatabase/neon-js",
|
|
12
13
|
"scale to zero", "Neon autoscaling", "Neon read replica",
|
|
13
|
-
"Neon connection pooling",
|
|
14
|
+
"Neon connection pooling", "schema migrations", "semantic search", "vector
|
|
15
|
+
search", "full-text search", "BM25", or "hybrid search".
|
|
14
16
|
metadata:
|
|
15
17
|
parent: neon
|
|
16
18
|
source: https://github.com/neondatabase/agent-skills/tree/main/skills/neon-postgres
|
|
@@ -165,6 +167,20 @@ Key points:
|
|
|
165
167
|
|
|
166
168
|
Link: https://neon.com/docs/guides/logical-replication-guide.md
|
|
167
169
|
|
|
170
|
+
## Lakebase Search
|
|
171
|
+
|
|
172
|
+
Use Lakebase Search for semantic, full-text, and hybrid search:
|
|
173
|
+
|
|
174
|
+
- For semantic search, read [Vector search](references/vector-search.md).
|
|
175
|
+
- For full-text search with BM25 ranking, read [Full-text search](references/full-text-search.md).
|
|
176
|
+
- For combining semantic and lexical results, read [Hybrid search](references/hybrid-search.md).
|
|
177
|
+
|
|
178
|
+
Links:
|
|
179
|
+
|
|
180
|
+
- [Get started with Lakebase Search](https://neon.com/docs/ai/lakebase-search-get-started)
|
|
181
|
+
- [`lakebase_vector` reference](https://neon.com/docs/extensions/lakebase-vector)
|
|
182
|
+
- [`lakebase_text` reference](https://neon.com/docs/extensions/lakebase-text)
|
|
183
|
+
|
|
168
184
|
## Gotchas
|
|
169
185
|
|
|
170
186
|
### Pooled vs direct connections: use the direct URL for migrations, dumps, and replication
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Full-Text Search with BM25 Ranking
|
|
2
|
+
|
|
3
|
+
Use `lakebase_text` for BM25 relevance ranking with PostgreSQL's standard `tsvector` type. The `lakebase_bm25` index adds corpus-aware ranking and top-K pushdown.
|
|
4
|
+
|
|
5
|
+
Lakebase Search requires Postgres 16 or later. Enable the extension before creating the index:
|
|
6
|
+
|
|
7
|
+
```sql
|
|
8
|
+
CREATE EXTENSION IF NOT EXISTS lakebase_text;
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`lakebase_text` has no extension dependency. It relies on a preloaded library that Neon enables by default; if the project customized its preloaded-library list, confirm the library remains enabled.
|
|
12
|
+
|
|
13
|
+
## Prepare and Index Text
|
|
14
|
+
|
|
15
|
+
Prefer a stored generated `tsvector` when search text comes from stable table columns:
|
|
16
|
+
|
|
17
|
+
```sql
|
|
18
|
+
CREATE TABLE documents (
|
|
19
|
+
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
20
|
+
title text NOT NULL,
|
|
21
|
+
body text NOT NULL,
|
|
22
|
+
body_tsv tsvector GENERATED ALWAYS AS
|
|
23
|
+
(to_tsvector('english', body)) STORED
|
|
24
|
+
);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Create the index after the initial corpus has been inserted so build-time corpus statistics are meaningful. BM25 scoring is tuned by two storage parameters set at index-build time:
|
|
28
|
+
|
|
29
|
+
- `k1` controls term-frequency saturation (default `1.2`, range `1.2`–`2.0`): higher values let repeated terms keep adding relevance.
|
|
30
|
+
|
|
31
|
+
- `b` controls document-length normalization (default `0.75`, range `0.0`–`1.0`): higher values penalize longer documents more.
|
|
32
|
+
|
|
33
|
+
Both can only be set in the `WITH` clause, and updating them rebuilds the index:
|
|
34
|
+
|
|
35
|
+
```sql
|
|
36
|
+
CREATE INDEX documents_body_bm25 ON documents
|
|
37
|
+
USING lakebase_bm25 (body_tsv)
|
|
38
|
+
WITH (k1 = 1.2, b = 0.75);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
After a large bulk load, run `VACUUM` to refresh the statistics used by BM25 scoring.
|
|
42
|
+
|
|
43
|
+
## Query and Interpret Scores
|
|
44
|
+
|
|
45
|
+
`to_bm25query` binds the query `tsvector` to the BM25 index whose corpus statistics should be used. The `<@>` operator returns a negative BM25 score, so lower (more negative) values are more relevant and must sort ascending:
|
|
46
|
+
|
|
47
|
+
```sql
|
|
48
|
+
SELECT
|
|
49
|
+
id,
|
|
50
|
+
title,
|
|
51
|
+
body_tsv <@> to_bm25query(
|
|
52
|
+
to_tsvector('english', $1),
|
|
53
|
+
'documents_body_bm25'::regclass
|
|
54
|
+
) AS score
|
|
55
|
+
FROM documents
|
|
56
|
+
ORDER BY score
|
|
57
|
+
LIMIT $2;
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Use the same text-search configuration for document and query vectors. Select a language-specific or custom configuration that matches the corpus.
|
|
61
|
+
|
|
62
|
+
## Set the Candidate Limit
|
|
63
|
+
|
|
64
|
+
`lakebase_bm25.default_limit` controls how many rows the index returns before PostgreSQL applies the SQL `LIMIT`. Its default is `1000`; setting it close to the requested top-K avoids unnecessary scoring.
|
|
65
|
+
|
|
66
|
+
## Use Prefilter Selectively
|
|
67
|
+
|
|
68
|
+
Enable prefilter when a `WHERE` condition is strict or unpredictable and cheap to evaluate. It lets the index prune rows before BM25 scoring. A loose or expensive filter can be slower with prefilter enabled.
|
|
69
|
+
|
|
70
|
+
```sql
|
|
71
|
+
BEGIN;
|
|
72
|
+
SET LOCAL lakebase_bm25.default_limit = 20;
|
|
73
|
+
SET LOCAL lakebase_bm25.prefilter = on;
|
|
74
|
+
|
|
75
|
+
SELECT
|
|
76
|
+
id,
|
|
77
|
+
title,
|
|
78
|
+
body_tsv <@> to_bm25query(
|
|
79
|
+
to_tsvector('english', $1),
|
|
80
|
+
'documents_body_bm25'::regclass
|
|
81
|
+
) AS score
|
|
82
|
+
FROM documents
|
|
83
|
+
WHERE id % 1000 = 0
|
|
84
|
+
ORDER BY score
|
|
85
|
+
LIMIT $2;
|
|
86
|
+
COMMIT;
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Set Parameters at Build Time or Per Query
|
|
90
|
+
|
|
91
|
+
Several BM25 parameters can be set in two places. As an index storage parameter in the `CREATE INDEX` `WITH` clause, a value is fed into the index as its build-time default. As a session GUC via `SET` (or `SET LOCAL`), it applies per query and takes precedence over the stored default when both are present.
|
|
92
|
+
|
|
93
|
+
- `default_limit` and `prefilter` exist in both forms: set an index default that fits the common case, then override it per query with a GUC without rebuilding.
|
|
94
|
+
- `k1` (default `1.2`) and `b` (default `0.75`) are storage parameters only. There is no GUC for them.
|
|
95
|
+
- `enable_scan` (default `on`) is a GUC only.
|
|
96
|
+
|
|
97
|
+
The examples use `SET LOCAL` so each override is scoped to its own transaction, which is required behind a connection pool or stateless driver.
|
|
98
|
+
|
|
99
|
+
Source: [`lakebase_text` documentation](https://neon.com/docs/extensions/lakebase-text).
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Hybrid Search
|
|
2
|
+
|
|
3
|
+
Use hybrid search when either semantic similarity or exact vocabulary can identify a relevant document. Lakebase Search does not provide a built-in hybrid function: run vector and BM25 retrieval separately, then combine their results with a fusion strategy suited to the workload.
|
|
4
|
+
|
|
5
|
+
Lakebase Search requires Postgres 16 or later. Hybrid search uses both extensions:
|
|
6
|
+
|
|
7
|
+
```sql
|
|
8
|
+
CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
|
|
9
|
+
CREATE EXTENSION IF NOT EXISTS lakebase_text;
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
`lakebase_vector` installs `pgvector` through `CASCADE`; `lakebase_text` has no extension dependency. Both rely on preloaded libraries that Neon enables by default. If the project customized its preloaded-library list, confirm both libraries remain enabled.
|
|
13
|
+
|
|
14
|
+
Prepare a table with both vector and text-search columns:
|
|
15
|
+
|
|
16
|
+
```sql
|
|
17
|
+
CREATE TABLE documents (
|
|
18
|
+
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
19
|
+
title text NOT NULL,
|
|
20
|
+
body text NOT NULL,
|
|
21
|
+
embedding vector(1536),
|
|
22
|
+
body_tsv tsvector GENERATED ALWAYS AS
|
|
23
|
+
(to_tsvector('english', body)) STORED
|
|
24
|
+
);
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Replace `1536` with the embedding model's dimension. Use the same model and preprocessing for stored-document and query embeddings, and choose a PostgreSQL text-search configuration appropriate for the corpus.
|
|
28
|
+
|
|
29
|
+
Create and validate each retriever independently before combining them. Follow [Vector search](vector-search.md) and [Full-text search](full-text-search.md) for their indexes, query operators, and tuning.
|
|
30
|
+
|
|
31
|
+
Reciprocal Rank Fusion (RRF) is the approach in the Lakebase Search get-started guide and a useful default because it combines ranks instead of incomparable raw distances and scores. It is not the only option: weighted rank fusion, normalized score fusion, or a reranker may fit applications with different relevance signals.
|
|
32
|
+
|
|
33
|
+
## RRF Example
|
|
34
|
+
|
|
35
|
+
For rank `r` and constant `k`, each retriever contributes `1 / (k + r)`. The documented starting point uses 40 candidates per retriever and `k = 60`; tune both for the corpus and workload.
|
|
36
|
+
|
|
37
|
+
Bind the query embedding as `$1`, query text as `$2`, and final result count as `$3`:
|
|
38
|
+
|
|
39
|
+
```sql
|
|
40
|
+
WITH vector_ranked AS (
|
|
41
|
+
SELECT id, RANK() OVER (ORDER BY distance) AS rank
|
|
42
|
+
FROM (
|
|
43
|
+
SELECT id, embedding <=> $1::vector AS distance
|
|
44
|
+
FROM documents
|
|
45
|
+
ORDER BY distance
|
|
46
|
+
FETCH FIRST 40 ROWS WITH TIES
|
|
47
|
+
) AS vector_candidates
|
|
48
|
+
),
|
|
49
|
+
keyword_ranked AS (
|
|
50
|
+
SELECT id, RANK() OVER (ORDER BY score) AS rank
|
|
51
|
+
FROM (
|
|
52
|
+
SELECT
|
|
53
|
+
id,
|
|
54
|
+
body_tsv <@> to_bm25query(
|
|
55
|
+
to_tsvector('english', $2),
|
|
56
|
+
'documents_body_bm25'::regclass
|
|
57
|
+
) AS score
|
|
58
|
+
FROM documents
|
|
59
|
+
ORDER BY score
|
|
60
|
+
FETCH FIRST 40 ROWS WITH TIES
|
|
61
|
+
) AS keyword_candidates
|
|
62
|
+
)
|
|
63
|
+
SELECT
|
|
64
|
+
d.id,
|
|
65
|
+
d.title,
|
|
66
|
+
COALESCE(1.0 / (60 + v.rank), 0) +
|
|
67
|
+
COALESCE(1.0 / (60 + k.rank), 0) AS rrf_score
|
|
68
|
+
FROM documents AS d
|
|
69
|
+
LEFT JOIN vector_ranked AS v ON v.id = d.id
|
|
70
|
+
LEFT JOIN keyword_ranked AS k ON k.id = d.id
|
|
71
|
+
WHERE v.id IS NOT NULL OR k.id IS NOT NULL
|
|
72
|
+
ORDER BY rrf_score DESC, d.id
|
|
73
|
+
LIMIT $3;
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`RANK()` gives tied retrieval scores the same rank. Sort by `rrf_score` descending and use the stable ID as a final tie-breaker.
|
|
77
|
+
|
|
78
|
+
`FETCH FIRST ... ROWS WITH TIES` keeps every candidate tied at the cutoff, so `RANK()` receives the complete boundary tie group. The candidate set can therefore exceed 40 rows. `lakebase_bm25.default_limit` defaults to `1000`; increase it only when the BM25 candidate set needs to exceed that value.
|
|
79
|
+
|
|
80
|
+
## Adapt the Hybrid Search
|
|
81
|
+
|
|
82
|
+
- Retrieve more candidates from each source than the final result count; otherwise one retriever can dominate before fusion has enough overlap. Keep `lakebase_bm25.default_limit` above the BM25 candidate target and allow room for boundary ties.
|
|
83
|
+
- Keep each retriever's operator and index configuration correct independently before tuning RRF.
|
|
84
|
+
- Tune candidate counts and the RRF constant with judged or behavioral relevance data, plus latency measurements.
|
|
85
|
+
- Add weights only when product evidence shows one retriever should contribute more. Weight the reciprocal-rank contributions, not the raw vector distance and negative BM25 score.
|
|
86
|
+
- Apply the same access-control and tenant filters to both candidate CTEs. If BM25 filters are strict and cheap, evaluate whether `lakebase_bm25.prefilter` improves the filtered query.
|
|
87
|
+
|
|
88
|
+
Source: [Lakebase Search get-started guide][lakebase-search-guide].
|
|
89
|
+
|
|
90
|
+
[lakebase-search-guide]: https://neon.com/docs/ai/lakebase-search-get-started#combine-results-with-hybrid-search
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# Semantic Vector Search
|
|
2
|
+
|
|
3
|
+
Use `lakebase_vector` for approximate nearest-neighbor retrieval over embeddings. It retains pgvector's vector types, distance operators, and query syntax; the index access method is `lakebase_ann`.
|
|
4
|
+
|
|
5
|
+
## Contents
|
|
6
|
+
|
|
7
|
+
- [Create the extension](#create-the-extension) — enable `lakebase_vector` and its `pgvector` dependency
|
|
8
|
+
- [Prepare embeddings](#prepare-embeddings) — define the vector column and keep embedding dimensions consistent
|
|
9
|
+
- [Build the index](#build-the-index) — match the distance metric, operator class, and query operator
|
|
10
|
+
- [Tune the index](#tune-the-index) — configure index-build options and concurrent index management
|
|
11
|
+
- [Query](#query) — rank by vector distance or filter by a similarity radius
|
|
12
|
+
- [Tune search](#tune-search) — inspect the index and tune recall against latency
|
|
13
|
+
- [Use prefilter selectively](#use-prefilter-selectively) — apply selective filters before ANN scoring
|
|
14
|
+
|
|
15
|
+
## Create the Extension
|
|
16
|
+
|
|
17
|
+
Lakebase Search requires Postgres 16 or later. Enable the extension before creating vector columns or indexes:
|
|
18
|
+
|
|
19
|
+
```sql
|
|
20
|
+
CREATE EXTENSION IF NOT EXISTS lakebase_vector CASCADE;
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`lakebase_vector` installs `pgvector` through `CASCADE`. It relies on a preloaded library that Neon enables by default; if the project customized its preloaded-library list, confirm the library remains enabled.
|
|
24
|
+
|
|
25
|
+
## Prepare Embeddings
|
|
26
|
+
|
|
27
|
+
Use any embedding provider whose vector dimensions and distance metric match the schema and index:
|
|
28
|
+
|
|
29
|
+
```sql
|
|
30
|
+
CREATE TABLE documents (
|
|
31
|
+
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
|
32
|
+
title text NOT NULL,
|
|
33
|
+
body text NOT NULL,
|
|
34
|
+
embedding vector(1536)
|
|
35
|
+
);
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Replace `1536` with the embedding model's dimension. Generate stored-document and query embeddings with the same model and preprocessing. Keep embedding generation outside SQL unless the architecture already provides an in-database embedding function.
|
|
39
|
+
|
|
40
|
+
## Build the Index
|
|
41
|
+
|
|
42
|
+
Choose the operator class and query operator as a matched pair:
|
|
43
|
+
|
|
44
|
+
| Metric | Common use | Operator class | Distance operator |
|
|
45
|
+
| --- | --- | --- | --- |
|
|
46
|
+
| Cosine | Most text embeddings | `vector_cosine_ops` | `<=>` |
|
|
47
|
+
| L2 / Euclidean | Absolute distance matters; vectors do not need normalization | `vector_l2_ops` | `<->` |
|
|
48
|
+
| Inner product | Unit-normalized vectors; matches cosine for unit vectors | `vector_ip_ops` | `<#>` |
|
|
49
|
+
|
|
50
|
+
```sql
|
|
51
|
+
CREATE INDEX documents_embedding_ann ON documents
|
|
52
|
+
USING lakebase_ann (embedding vector_cosine_ops);
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Tune the Index
|
|
56
|
+
|
|
57
|
+
The default index options suit most workloads:
|
|
58
|
+
|
|
59
|
+
- `build_mode = 'standard'` balances recall and index build time. Use `quality` for better recall when a longer build is acceptable.
|
|
60
|
+
- `lists = 'auto'` chooses the IVF partition layout from the number of indexed vectors. Choose between `auto` and a manual value case by case: test both on the target dataset and use the value that better meets recall and performance targets.
|
|
61
|
+
|
|
62
|
+
To prioritize recall over index build time:
|
|
63
|
+
|
|
64
|
+
```sql
|
|
65
|
+
CREATE INDEX documents_embedding_ann_quality ON documents
|
|
66
|
+
USING lakebase_ann (embedding vector_cosine_ops)
|
|
67
|
+
WITH (build_mode = 'quality');
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
To override the automatic partition layout instead:
|
|
71
|
+
|
|
72
|
+
```sql
|
|
73
|
+
CREATE INDEX documents_embedding_ann_lists ON documents
|
|
74
|
+
USING lakebase_ann (embedding vector_cosine_ops)
|
|
75
|
+
WITH (lists = '1024');
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
For a large table, use `CREATE INDEX CONCURRENTLY` to avoid locking out writes while creating the index. For a frequently changing table, periodically use `REINDEX INDEX CONCURRENTLY` to rebuild the index with minimal write locking.
|
|
79
|
+
|
|
80
|
+
## Query
|
|
81
|
+
|
|
82
|
+
Generate the query embedding with the same model and preprocessing used for stored documents, then bind it as a parameter:
|
|
83
|
+
|
|
84
|
+
```sql
|
|
85
|
+
SELECT id, title, embedding <=> $1::vector AS distance
|
|
86
|
+
FROM documents
|
|
87
|
+
ORDER BY distance
|
|
88
|
+
LIMIT $2;
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Distance sorts ascending: a smaller value is a closer match. Keep the query operator consistent with the index operator class.
|
|
92
|
+
|
|
93
|
+
To filter by a similarity radius, use the matching boolean range operator in `WHERE` and the distance operator in `ORDER BY`:
|
|
94
|
+
|
|
95
|
+
```sql
|
|
96
|
+
SELECT id, title
|
|
97
|
+
FROM documents
|
|
98
|
+
WHERE embedding <<=>> sphere($1::vector, 0.5)
|
|
99
|
+
ORDER BY embedding <=> $1::vector
|
|
100
|
+
LIMIT $2;
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The cosine range operator `<<=>>` returns a boolean; do not use it as the ranking expression.
|
|
104
|
+
|
|
105
|
+
## Tune Search
|
|
106
|
+
|
|
107
|
+
Inspect the index before overriding defaults:
|
|
108
|
+
|
|
109
|
+
```sql
|
|
110
|
+
SELECT lakebase_ann_index_info('documents_embedding_ann');
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
This reports `lists`, `default_probes`, and `default_epsilon`. Small datasets use exact flat search before IVF lists are built. In that state, `lists` and `default_probes` are empty. Leave `lakebase_ann.probes` set to its default of `'auto'`; `lakebase_ann.epsilon` still controls full-precision reranking during flat search.
|
|
114
|
+
|
|
115
|
+
For an IVF index, `lakebase_ann.probes` controls how many partitions are searched at each level. Higher values generally improve recall at the cost of speed. Its default is `'auto'`. When `lists` is not empty, the shape of `probes` must match the shape of `lists`: use one value for a one-level index or two comma-separated values for a two-level index. At each level, the `probes` value must be no larger than the corresponding `lists` value. A mismatched or out-of-range value causes an error.
|
|
116
|
+
|
|
117
|
+
`lakebase_ann.epsilon` controls how many candidates are reranked using full-precision distances. Higher values rerank more candidates and take longer. Its default is `'auto'`, which works well for most workloads.
|
|
118
|
+
|
|
119
|
+
### Use Prefilter Selectively
|
|
120
|
+
|
|
121
|
+
By default, PostgreSQL applies non-vector filters after the ANN index returns candidate rows. Enable prefilter when a filter is cheap to evaluate and removes most rows. Leave it off for loose or expensive filters.
|
|
122
|
+
|
|
123
|
+
```sql
|
|
124
|
+
BEGIN;
|
|
125
|
+
SET LOCAL lakebase_ann.prefilter = on;
|
|
126
|
+
|
|
127
|
+
SELECT id, title
|
|
128
|
+
FROM documents
|
|
129
|
+
WHERE id % 100 = 0
|
|
130
|
+
ORDER BY embedding <=> $1::vector
|
|
131
|
+
LIMIT $2;
|
|
132
|
+
COMMIT;
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
Start with `probes` and `epsilon` set to `'auto'`. Benchmark manual probe values against representative query embeddings and choose the smallest values that satisfy recall and tail-latency targets. Keep session settings and the query in the same transaction when using a connection pool or stateless driver.
|
|
136
|
+
|
|
137
|
+
Source: [`lakebase_vector` documentation](https://neon.com/docs/extensions/lakebase-vector).
|