Search (vector)

Pluggable vector-search module — Qdrant today, OpenSearch planned. Index CRUD, semantic query, embedding-provider switching, FlowDSL nodes.

9 min readReference

github.com/redelay/go-modules/search is a backend-agnostic vector-search module. The public contract — index CRUD, upsert, query — is identical across backends; the first shipping backend is Qdrant, with OpenSearch planned. Embeddings are computed via any registered go-ai LLM provider so callers can switch between OVH bge-m3 (€0.01/M), OpenAI text-embedding-3-small, or a local Ollama model without touching application code.

shell
go get github.com/redelay/go-modules/search

Blank-import the module + a backend + the FlowDSL node pack:

go
import (
    _ "github.com/redelay/go-modules/search"          // framework module + HTTP surface
    _ "github.com/redelay/go-modules/search/qdrant"   // Qdrant backend factory
    _ "github.com/redelay/go-modules/search/flowdsl"  // FlowDSL nodes: search-upsert, search-query
)

The admin submodule at search/admin mounts index CRUD under the admin prefix — import it from cmd/admin-api only.

Concepts

TermMeaning
IndexA named collection of vectors. Callers use a short logical name (docs); the service rewrites it to {SEARCH_INDEX_PREFIX}{name} before talking to the backend.
DocumentOne record — {id, text?, vector?, payload?}. Exactly one of text or vector must be present; the service auto-embeds text via the configured LLM provider.
QueryNearest-neighbour request — {text?, vector?, limit?, payload?, filter?}. text is auto-embedded. payload is a shortcut for exact-match filters; filter is forwarded to the backend verbatim for richer expressions (Qdrant Filter, OpenSearch knn_filter, …).
HitOne result — {id, score, payload?}.

Index prefix — safe multi-tenancy

SEARCH_INDEX_PREFIX is stamped onto every index name before it reaches the backend, and stripped off on the way back out. One Qdrant cluster can host redelay_dev_docs, redelay_prod_docs, tenant_a_docs simultaneously, with each app seeing only its own indexes via ListIndexes. Change the prefix at runtime via the admin setting search.index_prefix — existing indexes under the old prefix become invisible until moved.

Configuration

Config (ENV, startup):

KeyDefaultPurpose
SEARCH_BACKENDqdrantBackend factory id — qdrant, later opensearch
SEARCH_INDEX_PREFIXredelay_Stamped onto every index name
SEARCH_EMBEDDING_PROVIDERollamaRegistered llm provider id used for auto-embedding
SEARCH_EMBEDDING_MODELnomic-embed-textEmbedding model name
SEARCH_EMBEDDING_DIM768Dimension — must match the model (bge-m3 = 1024, ada-002 = 1536, nomic-embed = 768)
QDRANT_URLhttp://localhost:6333Qdrant HTTP endpoint
QDRANT_API_KEY(empty)Optional — sent as api-key header
SEARCH_PUBLIC_APIfalsetrue mounts the unauthenticated GET /search/indexes and POST /search/indexes/{name}/query (v0.63.0+; before that they were always on)
QDRANT_READ_URL / QDRANT_READ_API_KEY(empty)This region's read replica (v0.63.0+). From v0.65.0 a search goes there only for a versioned index whose alias points at the same version on both servers; everything else — an index written in place, a replica still on an older version — is read from QDRANT_URL (see Read copies)
QDRANT_REPLICA_URLS(empty)Comma-separated read copies in other regions; every PublishVersion is copied to each as a snapshot (no re-embedding)
QDRANT_REPLICA_API_KEYQDRANT_API_KEYKey for the replicas

Admin settings (runtime, override env):

KeyDefaultPurpose
search.default_distancecosineSimilarity metric for new indexes
search.default_limit10Top-K when callers omit limit
search.index_prefix(uses env)Runtime override
search.embedding_provider(uses env)Runtime override
search.embedding_model(uses env)Runtime override

Settings appear in /admin/settings/search — the same module pattern as ai-guard and scheduler.

HTTP surface

Public (/search/* — no auth):

MethodPathPurpose
GET/search/status{"enabled"}; the full snapshot (backend id, prefix, embedding provider/model/dim) only with SEARCH_PUBLIC_API=true
GET/search/indexesList indexes (prefix-stripped) — only with SEARCH_PUBLIC_API=true
POST/search/indexes/{name}/queryVector query by text or vector — only with SEARCH_PUBLIC_API=true
Before v0.63.0 the list and query routes were mounted on every binary with no auth: anyone could list every index and run queries, each one an embedding call paid by the app. Upgrade, and keep SEARCH_PUBLIC_API off unless a public search page really needs it — then put a rate limit in front of it.

Admin (/api/v1/admin/search/* — admin-api only, an active user with admin:access, BearerAuth):

Before go-modules v0.63.2 these admin routes had no auth: anyone who could reach admin-api could list, query, upsert into, reindex or delete every index. Upgrade.
MethodPathPurpose
GET/admin/search/indexesList
POST/admin/search/indexesCreate (body: {name, dim, distance?})
GET/admin/search/indexes/{name}Metadata — dimension, distance, points count
DELETE/admin/search/indexes/{name}Remove index + all vectors
POST/admin/search/indexes/{name}/upsertUpsert documents — body {documents: [...]}
POST/admin/search/indexes/{name}/deleteDelete by id — body {ids: [...]}
POST/admin/search/indexes/{name}/reindexRebuild the index from its source of truth (see below)

Permissions defined: search:index:list, search:index:write, search:doc:write, search:doc:delete.

Keeping an index fresh

An index is only as good as its last write. Two mechanisms keep it current, and a well-behaved owner module uses both.

1. Reindex on change (incremental, preferred)

Have the owning collection publish lifecycle events and consume them. Any store built on crud.MongoCRUD opts in with one call:

go
// programs/crud.go — emits program.created / .updated / .deleted
crud.NewMongoCRUD[*WorkoutProgram](db.Collection(coll)).WithEvents(bus, "program")

Then react to exactly the entity that changed:

go
func (m *Module) Events() []*ir.Event { return nil } // required alongside Consumers()

func (m *Module) Consumers() []*modules.ConsumerRegistration {
    return []*modules.ConsumerRegistration{
        {Topic: "program.updated", GroupID: "my-reindex", Handler: m.onChange},
    }
}

func (m *Module) onChange(ctx context.Context, ev *modules.EventMessage) error {
    doc, ok := m.buildDoc(ctx, ev.EntityID) // still published?
    if !ok {
        return search.Current().Delete(ctx, "programs", []string{ev.EntityID})
    }
    return search.Current().Upsert(ctx, "programs", []search.Document{doc})
}

This makes a newly created, edited, translated, or unpublished entity searchable (or gone) within a second — no polling. Deleting the point when the entity is no longer public is what stops unpublished rows leaking into results.

Gotcha: modules.EventsProvider requires both Events() and Consumers(). Implement only Consumers() and the type assertion fails silently — no consumer is ever registered.

2. Reindex on demand (full rebuild)

Register a rebuild callback so operators get a Reindex action in the admin — needed after a bulk translation, a schema change, or switching embedding model (a new model means new vectors for every document):

go
// Startup
search.RegisterReindexer("programs", m) // m implements search.Reindexer

func (m *Module) Reindex(ctx context.Context, index string) (int, error) {
    // re-embed + upsert everything; return the document count
}

GET /admin/search/entities then lists the index in reindexable, and POST /admin/search/indexes/programs/reindex returns {"index":"programs","documents":5,"status":"ok"}. Indexes without a registered owner return 501 Not Implemented rather than silently doing nothing.

A periodic full reindex (a ticker in the owner module) is still a cheap safety net against missed events — embeddings cost fractions of a cent per thousand documents.

Prune what no longer exists

A rebuild writes what currently exists and knows nothing about what was deleted, so upserting alone lets the index drift: an unpublished or deleted row keeps answering searches forever. Close the loop with PruneStale:

go
ids := make([]string, 0, len(docs))
for _, d := range docs { ids = append(ids, d.ID) }
svc.Upsert(ctx, index, docs)
svc.PruneStale(ctx, index, ids)   // removes every point not in ids

It pages through the index, diffs against the ids you just wrote, and deletes the remainder — returning how many it removed. Treat it as best-effort: a prune failure should not fail a rebuild that already succeeded.

Without this, deleting rows straight in the database (a cleanup script, a migration) leaves orphans that no event will ever reap.

Backend — Qdrant

The bundled backend talks to Qdrant over its REST API — no SDK, no protobuf dep.

  • Collections map 1:1 with indexes. CreateIndex is idempotent on matching params; disagreeing dimensions return a 400 from Qdrant.
  • Point IDs — Qdrant accepts only unsigned integers or UUIDs. The backend transparently hashes arbitrary string IDs (e.g. docs/admin/overview.md) to deterministic UUIDv5 values and stashes the original under payload._id. Search results restore the original string so callers see stable IDs regardless of backend encoding. Decimal-string IDs pass through as numbers.
  • Filtering — Query.Payload is a shortcut for must equality constraints; Query.Filter is forwarded verbatim for richer expressions.
  • Index options — Index.OnDisk keeps vectors on disk; Index.Quantization: "int8" adds scalar quantization (kept in RAM). Query.ScoreThreshold drops weak matches.

Versioned indexes and regions (v0.63.0+)

A versioned index is an alias pointing at an immutable collection <name>__v<unix-millis>. Service.PublishVersion(ctx, alias, idx, fill):

  1. creates a new version and runs fill on it (a failed fill deletes it; the alias is untouched);
  2. moves the alias to it atomically;
  3. copies the version to each QDRANT_REPLICA_URLS replica as a snapshot and moves the alias there;
  4. prunes older versions on each backend — only up to the version the alias pointed to before this publish, and never the live one, so overlapping rebuilds of one alias can never delete the version in use or one still filling.

Read copies {#read-copies}

Only versions are copied to replicas, so a replica can serve only what PublishVersion put there. From v0.65.0 a process with QDRANT_READ_URL reads its replica only when the index is an alias there and points at the same version as on the writer (both alias lists cached 30 s). Otherwise the search goes to the writer:

  • an index written in place (upserts outside PublishVersion): before, it was safe only because the replica answered 404. A collection of that name on the replica (a restore, a manual copy) would have been read stale forever;
  • a replica whose copy failed keeps its alias on the previous version. That is not a 404, so before it answered with the old results until the next good publish. While a publish is copying, reads use the writer, which already has the new version;
  • an unreachable replica, as before.

Lag is reported, not just routed around:

  • soft /health check search_replicas (warn, never 503) on any process with QDRANT_REPLICA_URLS or QDRANT_READ_URL: which copy lags, on which aliases;
  • GET /admin/search/replicas (admin:access): {replicas, lagging: [{replica, aliases: {alias: [primary version, replica version]}, error}]};
  • Service.ReplicaDrift(ctx) for your own checks.

Every process that runs PublishVersion must list all replicas in QDRANT_REPLICA_URLS; a replica it does not know is never copied to and shows as lagging from the reading side.

Also: Published (alias → live version), DropVersioned (alias + every version), Orphans (versions no alias points to, for a delayed cleanup), VersionTime. Service.EmbedQuery(ctx, scope, text) embeds a query once (ledger label search.query) so one vector can search several indexes.

FlowDSL nodes (search/flowdsl)

Node IDKindPurpose
redelay/search-upsertactionIndex one or more documents. Empty vectors are auto-embedded.
redelay/search-queryactionSemantic query by text (auto-embedded) or vector.

Both nodes resolve the live *search.Service lazily via search.Current() so handler registration can happen before the module's Startup. Handlers are wired in backend/imports/aiwire/aiwire.go alongside the llm-chat / llm-embed / llm-guard handlers.

Example flow — RAG over docs:

yaml
# upsert pipeline
- id: chunk
  action_ref: redelay/text-split    # project node
- id: index
  action_ref: redelay/search-upsert
  config: { index: docs }

# query pipeline
- id: search
  action_ref: redelay/search-query
  config: { index: docs, limit: 5 }
- id: build-prompt
  action_ref: redelay/template-format   # fold hits into a system prompt
- id: answer
  action_ref: redelay/llm-chat

Integration testing

go-modules/search/qdrant/integration_test.go runs end-to-end against a live Qdrant — create collection, upsert three points, nearest-neighbour query, verify the closest match, tear down. Gated on QDRANT_URL:

shell
QDRANT_URL=http://100.93.236.60:6333 go test -run Integration -v ./search/qdrant/

Pair with OVH_AI_ENDPOINTS_TOKEN set to exercise the full pipeline — OVH bge-m3 embedding → Qdrant upsert → OVH chat retrieval.

Was this page helpful?