# Data model how-to guides

> Goal-oriented, runnable recipes for the Vectros data model. Every snippet is grounded
> in calls that run against the live platform. Examples use the Node SDK; data is
> **synthetic** throughout (fictional names and values only).

## Setup

Install and construct a client once. Sub-clients are grouped by area
(`client.schemas`, `client.records`, `client.documents`, `client.folders`,
`client.search`).

```ts
import { VectrosClient } from '@vectros-ai/sdk';

const client = new VectrosClient({
  token: process.env.VECTROS_API_KEY!,          // sk_*, ssk_*, or st_* credential
  environment: 'https://api.vectros.ai',
});
```

> **Version note.** The API spec is currently at **0.51.0**. Two calls in this guide
> require **SDK 0.26+** and are marked inline: record/document/folder **PATCH**, and
> creating a record by `typeName` alone (the `typeName` XOR `schemaId` either-or) — relevant
> only if your own integration pins an SDK build older than 0.26. Every first-party client
> (CLI, MCP server, React toolkit, reference web apps) is well past that line today.

---

## Define a schema

**Goal:** declare a record type with validated fields, a searchable field, a filterable
field, and a unique lookup field.

```ts
const schema = await client.schemas.createSchema({
  body: {
    typeName: 'patient_intake',
    displayName: 'Patient Intake Record',
    indexMode: 'HYBRID',                 // index instances for hybrid search
    allowedSurfaces: ['record'],         // REQUIRED, non-empty
    fields: [
      { fieldId: 'name',       fieldType: 'string', required: true,  searchable: true  },
      { fieldId: 'notes',      fieldType: 'string', required: false, searchable: true  },
      { fieldId: 'department', fieldType: 'string', required: false, filterable: true  },
      { fieldId: 'email',      fieldType: 'string', required: true,  searchable: false },
    ],
    lookupFields: [{ fieldName: 'email', unique: true }],
    capabilities: { auditHistory: true },
  },
});

const schemaId = schema.id!;
```

**Expected result:** a schema with a system-assigned `id` and `schemaVersion: 1`.
`allowedSurfaces` is required — omitting it is a 400.

> A **bare schema** (just `typeName`, `displayName`, `allowedSurfaces`) is valid;
> records written against it are stored without payload validation.

> **Re-running this call is safe for you, not for a second owner.** `createSchema` is
> idempotent by `typeName` **within your own ownership scope** — re-issuing it with your
> own credential returns your existing schema instead of failing. A *different* owner
> (a different `userId`/`scopes`) defining a schema under a `typeName` that already exists
> must set `basedOn` to the existing schema's id, making theirs a customization of it — an
> omitted `basedOn` on a name someone else already claimed is rejected with a `400`. See
> the [data model reference](reference.md#schema-fields) for the full `basedOn` contract.

---

## Link records with a reference field

**Goal:** declare a typed link from one record type to another.

A field with `fieldType: 'reference'` carries a typed link to another record (or to an
identity). It takes a few extra keys on the field definition:

```ts
await client.schemas.createSchema({
  body: {
    typeName: 'encounter',
    displayName: 'Clinical Encounter',
    indexMode: 'HYBRID',
    allowedSurfaces: ['record'],
    fields: [
      { fieldId: 'summary', fieldType: 'string', required: true, searchable: true },
      {
        fieldId: 'patient',
        fieldType: 'reference',
        targetTypeName: 'patient_intake',   // required: the type pointed at
        targetSurface: 'record',            // required: record/document/user, or an entity-backed namespace (org/client/…)
        targetField: 'email',               // optional: a unique lookup on the target (default externalId)
        cardinality: 'one',                 // optional: one (default) | many
      },
    ],
  },
});
```

**Behavior:** by default the platform **resolves the reference at write time** — the
target record must already exist (matched on `targetField`), or the write is rejected. So
create the target before the record that points at it. A schema can opt out with
`capabilities.validateReferences: false` (an order-independent bulk load that accepts
unresolved references). `targetTypeName` and `targetSurface` are required on a reference
field; `targetField` must name a **unique** lookup on the target type.

---

## Create a record

**Goal:** write a validated record and confirm it indexed.

```ts
const record = await client.records.createRecord({
  body: {
    typeName: 'patient_intake',
    schemaId,                            // typeName + schemaId may both be given (must agree)
    payload: {
      name: 'Jane Doe',
      notes: 'presents with hypertension and complains of chest pain',
      department: 'cardiology',
      email: 'jane.doe@example.com',
    },
    userId,                              // optional ownership (Vectros user UUID)
    scopes: [`org:${orgId}`],            // optional ownership (namespaced entity edges, <= 2)
  },
});

// Freshly created records are queued for indexing.
// record.indexStatus === 'PENDING_INDEX'
```

**SDK 0.26+ variant — create by `typeName` alone.** You may omit `schemaId` and let the
server resolve the schema — to your own `basedOn` variant of `typeName` when you have one,
otherwise the shared base:

```ts
// (SDK 0.26+)
const record = await client.records.createRecord({
  body: {
    typeName: 'patient_intake',
    payload: { name: 'Jane Doe', email: 'jane.doe@example.com', department: 'cardiology' },
  },
});
```

**Expected result:** a `RecordResponse` with an `id`, `version: 1`, and
`indexStatus: 'PENDING_INDEX'`. Poll the record by id until `indexStatus` is `INDEXED`
before relying on it surfacing in search. Treat `FAILED` as a terminal outcome too — stop
polling and inspect `indexFailure.code`: `TEXT_INDEX_FAILED`, `EMBEDDING_FAILED`, and
`VECTOR_LIMIT_EXCEEDED` mean the record is still findable by the surviving strategy, while
`INDEXING_FAILED` / `SOURCE_UNAVAILABLE` mean it is not searchable at all, and `INTERNAL` is
an error on the platform's side (retry, and contact support if it persists). Branch on the
`code`, not the message text (see the code table in the operations-trust reference).

---

## Get a record

**Goal:** read a record back by id.

```ts
const loaded = await client.records.getRecord({ id: record.id! });
// loaded.payload, loaded.userId, loaded.version, loaded.indexStatus ...
```

A by-id GET always returns the full payload (even when it is externalized for size).

---

## Update a record (PUT — full replace)

**Goal:** change fields. Remember: `payload` is replaced in full, so resend the complete
payload. An update that meets another write to the same record at the same moment gets a
`409` even without `expectedVersion` (see below).

```ts
await client.records.updateRecord({
  id: record.id!,
  body: {
    typeName: 'patient_intake',
    schemaId,
    payload: {
      name: 'Jane Doe',
      notes: 'updated note',           // changed
      department: 'cardiology',
      email: 'jane.doe@example.com',   // re-supplied — omitting it would drop it
    },
    userId,
    scopes: [`org:${orgId}`],
  },
});
```

**Expected result:** the record's `version` increments; an audit version row capturing
the prior state is written asynchronously.

### Make the update conditional (optimistic concurrency)

Pass the `version` you last read as `expectedVersion`:

```ts
await client.records.updateRecord({
  id: record.id!,
  body: {
    typeName: 'patient_intake',
    schemaId,
    payload: { /* full payload */ },
    expectedVersion: loaded.version,   // reject with 409 if the record moved on
  },
});
```

**Expected result:** `409 VERSION_CONFLICT` if another writer changed the record since
you read it; the stored record is left untouched. Without `expectedVersion` you still get
the `409` when another write lands between the server's read and your write (the other
write is kept); re-read the record and retry.

---

## Patch a record (PATCH — true partial update, SDK 0.26+)

**Goal:** change a single payload field without resending the whole payload, using
RFC 7386 JSON Merge Patch.

```ts
// (SDK 0.26+)
await client.records.patchRecord({
  id: record.id!,
  body: {
    payload: {
      notes: 'patched note',           // overwrite this key only
      department: null,                 // null DELETES this key from the payload
    },
    status: 'ARCHIVED',                 // change a top-level mutable field
  },
});
```

**Behavior:** keys present in `payload` overwrite; nested objects recurse; a key set to
`null` **inside `payload`** is deleted; absent keys are preserved. A **top-level** field
(such as `status` or `folderId`) set to `null` is *not* a delete — it is rejected with
`400`. Immutable fields (`typeName`, `schemaId`, `externalId`, `indexMode`) are rejected if
present. `expectedVersion` may be included for conditional patches.

---

## Look a record up by field

**Goal:** fetch a record directly by a declared lookup field — no scan.

```ts
const results = await client.records.lookupRecords({
  type: 'patient_intake',
  field: 'email',
  value: 'jane.doe@example.com',
});

// List envelope: { data, nextCursor }
const found = results.data ?? [];      // email is unique → exactly one row
// results.nextCursor === null
```

**Expected result:** for a `unique` lookup field, `data` has at most one element. For a
non-unique field the result is an enumeration — page it with `nextCursor` (see below).

> **Sensitive fields:** if the lookup field is marked `sensitive`, the value may not
> travel in a URL. Use the body-based variant so the value stays out of access logs.
> The same `{ data, nextCursor }` envelope applies.

> **Composite lookups.** A schema can declare a lookup across two or three fields
> together (`lookupFields: [{ fieldNames: ['status', 'area'] }]` instead of a single
> `fieldName`). Query it with a comma-joined `field` and a matching `values` array, in
> the same order as `fieldNames`:
>
> ```ts
> const grouped = await client.records.lookupRecords({
>   type: 'support_ticket',
>   field: 'status,area',
>   values: ['open', 'east'],   // a single-element values means the same as value
> });
> ```
>
> Field order is fixed when the schema is authored: you can query the first field alone,
> the first two, and so on, but never a later field by itself — that needs its own
> lookup. Supply fewer values than the schema declares fields and the response **groups**
> by the fields you left out (`sortBy` then orders within each group, not across the
> whole result). A composite lookup can't be `unique` or `rangeEnabled`, and only binds
> to `record` schemas.

> **Narrow an exact lookup to a time window.** An exact-`value` lookup accepts optional
> `sortFrom`/`sortTo` bounds on the lookup field's own sort key, inclusive, in that
> field's units (epoch milliseconds for a timestamp field such as `createdAt`):
>
> ```ts
> const recent = await client.records.lookupRecords({
>   type: 'patient_intake',
>   field: 'department',
>   value: 'cardiology',
>   sortFrom: Date.now() - 30 * 24 * 60 * 60 * 1000,   // last 30 days
> });
> ```
>
> On a composite lookup, a `sortFrom`/`sortTo` window needs the full tuple of values —
> it isn't available on a grouped/partial query. Records with no value on the sorted
> field sort ahead of ones that have one, and are excluded from a bounded window.

---

## List and paginate (drain the cursor)

**Goal:** retrieve every record of a type, draining the `{ data, nextCursor }` list
envelope. The pattern is identical for `listRecords`, `listSchemas`, `listDocuments`,
`listFolders`, and the lookup/versions endpoints.

```ts
const ids: string[] = [];
let cursor: string | null | undefined;

do {
  const page = await client.records.listRecords(
    cursor ? { type: 'patient_intake', startFrom: cursor, limit: 100 }
           : { type: 'patient_intake', limit: 100 });
  ids.push(...(page.data ?? []).map((r) => r.id!));
  cursor = page.nextCursor;
} while (cursor);
```

**Expected result:** every page's `data` accumulated; the loop ends when `nextCursor`
is `null` — that is the only signal that you're done. Feed the **verbatim** `nextCursor`
back as `startFrom`; never compute your own offsets or construct a `startFrom` value (a
caller-constructed one is rejected with `400`). A page can come back short, or even
empty, while more results remain, so don't treat page size or fullness as a completion
signal — only `nextCursor === null` means "no more data."

You can narrow a list by ownership — `listRecords({ type, userId })` or
`{ type, scope: 'org:<id>' }` returns only that owner's records of the type (one `scope` filter
per call), paged the same way, so a page can be short or empty while `nextCursor` is set:

```ts
const mine = await client.records.listRecords({ type: 'patient_intake', userId, limit: 100 });
const orgsRecords = await client.records.listRecords({ type: 'patient_intake', scope: `org:${orgId}`, limit: 100 });
```

---

## Read version history

**Goal:** inspect the audit trail for a record — the change rows.

```ts
// Create, update, then read history.
const page = await client.records.getRecordVersions({ id: record.id! });
const versions = page.data ?? [];      // { data, nextCursor } list envelope

for (const v of versions) {
  // v.changeType: 'CREATE' | 'UPDATE' | 'DELETE'
  // v.previousContent: JSON string of the state BEFORE this change (null on CREATE)
  // v.changedBy, v.createdAt, v.changedFields
  // v.actingVia: present only when an agent run made the change on changedBy's behalf
  //   ({ kind: 'agent-run', actorId: <agent id>, runId, tool })
}

const update = versions.find((v) => v.changeType === 'UPDATE');
if (update?.previousContent) {
  const before = JSON.parse(update.previousContent);
  // before.payload.notes === 'original note'  (the pre-update state)
}
```

**Expected result:** at least one `CREATE` row plus one `UPDATE` row after an update.
Version rows are written asynchronously (typically 1–3 seconds after the write returns),
so poll briefly if you read history immediately after a write. The current state lives on
the record itself; history captures the "before" side of each transition.

---

## Confirm a delete left a tombstone

**Goal:** hard-delete a record and verify the tombstone.

```ts
await client.records.deleteRecord({ id: record.id! });

// Tombstone propagates shortly after delete.
const tomb = await client.records.getRecordTombstone({ id: record.id! });
```

**Expected result:** the record, its lookup rows, and its search-index entry are gone;
the tombstone row remains for audit.

---

## Ingest a text document (search-ready)

**Goal:** ingest inline text, wait for indexing, and retrieve it via search.

```ts
const doc = await client.documents.ingestDocument({
  body: {
    title: 'Hypertension Clinical Guidelines',
    text: 'Hypertension, commonly known as high blood pressure, is defined as ' +
          'systolic blood pressure consistently above 130 mmHg ... (full body)',
    indexMode: 'HYBRID',
    folderId,                            // optional
    userId,                              // optional ownership
    payload: {                           // free-form, filterable by key in search
      category: 'clinical-guidelines',
      specialty: 'cardiology',
    },
  },
});

// doc.indexStatus === 'PENDING_INDEX' → poll getDocument until indexStatus is 'INDEXED'
// (or 'SKIPPED', 'STORED' or 'FAILED' — terminal outcomes; inspect indexFailure.code on 'FAILED')

const results = await client.search.content({
  query: 'blood pressure',
  mode: 'HYBRID',
  limit: 50,
});
const hit = (results.results ?? []).find((r) => r.documentId === doc.id);
```

**Expected result:** the document indexes and surfaces in hybrid search. `search.content`
is **not** enveloped — read `results.results` directly. (Hybrid search modes, scoring, and
filters are covered in the search documentation.)

### Retrieve the stored text

```ts
const resp = await client.documents.getDocumentText({ id: doc.id! });
// resp.text contains the original body (text-ingested documents always retain it)
```

A long text can be read in parts. `offset` and `limit` count characters; each response carries
`totalLength` and, while text remains, `nextOffset` to pass as the next `offset`:

```ts
let text = '';
let offset: number | undefined = 0;
while (offset !== undefined) {
  const part = await client.documents.getDocumentText({ id: doc.id!, offset, limit: 10000 });
  text += part.text ?? '';
  offset = part.nextOffset;
}
```

---

## List documents of one type

**Goal:** list only the documents bound to a schema of a given `typeName`.

```ts
const page = await client.documents.listDocuments({ type: 'investigation_report', limit: 100 });
// Documents with no schema never match. Combine with folderId, userId or scope to narrow further.
```

The filter applies to each page as it is read, so a page can hold fewer than `limit` documents,
or none, while `nextCursor` is set. Keep paging until `nextCursor` is `null`.

---

## Upload a file (presigned handshake)

**Goal:** upload a file in the three-step handshake — request URL, PUT bytes, poll.

```ts
import * as fs from 'fs';

// Step 1 — request a presigned upload URL. `size` (the exact byte length) binds the upload: the URL is
// signed for that length and the media type, so a body that does not match is refused before it is stored.
const body = fs.readFileSync('clinical-note.pdf');
const upload = await client.documents.uploadDocument({
  fileName: 'clinical-note.pdf',
  fileType: 'application/pdf',
  size: body.length,
  indexMode: 'HYBRID',
  userId,
  payload: { category: 'clinical-note' },
});
// upload.uploadUrl, upload.expiresAt (ISO-8601, 15 min)

// Step 2 — PUT the raw bytes to the URL. NO Authorization header on this request, but every header in
// `requiredHeaders` IS mandatory — the URL is single-use, and these headers (the Content-Type it is signed
// for among them) are a signed part of the request; omitting one (or sending a different value) fails with
// a 403 SignatureDoesNotMatch before the request ever reaches this API.
const put = await fetch(upload.uploadUrl!, {
  method: 'PUT',
  body,
  headers: { ...upload.requiredHeaders },
});
// put.status === 200

// Step 3: poll until a terminal indexStatus (file extraction adds latency).
let loaded = await client.documents.getDocument({ id: upload.id! });
// repeat getDocument until loaded.indexStatus is 'INDEXED', 'SKIPPED' or 'FAILED'
// (on 'FAILED', stop and inspect loaded.indexFailure.code)
// loaded.extraction.outcome says how text extraction went: 'OK', 'TRUNCATED', or the reason
// the file yielded no text ('NO_TEXT', 'ENCRYPTED', 'UNSUPPORTED', 'TOO_LARGE', 'UNREADABLE', or
// 'NOT_EXTRACTED' for a type text is not extracted from, such as audio, video, images or a zip)
```

**Expected result:** the file's text is extracted, indexed, and searchable
(`extraction.outcome` is `OK`) for a document format; other files are stored and downloadable, with
`extraction.outcome` `NOT_EXTRACTED`. Fetch the file later via `getDocumentDownloadUrl({ id })`,
which returns a presigned `downloadUrl`.

A document-format file with no extractable text, such as a scanned PDF page, ends `SKIPPED`, or `INDEXED` when its bound schema declares
searchable fields, with `extraction.outcome: 'NO_TEXT'`: it is stored and downloadable, but it has no text, so
`getDocumentText` returns `404`. Text is kept up to 1,000,000 characters; a longer file ends
`INDEXED` with `extraction.outcome: 'TRUNCATED'` and `extraction.truncated: true`.


---

## Patch a document (SDK 0.26+)

**Goal:** change document metadata without resending everything.

```ts
// (SDK 0.26+. From SDK 0.46.0 the fields sit beside `id`; earlier SDKs take them under `body`.)
await client.documents.patchDocument({
  id: doc.id!,
  title: 'Hypertension Guidelines (2024 revision)',
  payload: { specialty: 'cardiology', reviewed: true },  // merged into existing payload
});
```

To re-ingest the body, include `text` in the patch — it is re-indexed write-through, the
same as a PUT update.

---

## Create a folder

**Goal:** create a folder and a subfolder.

```ts
const root = await client.folders.createFolder({
  body: {
    name: 'Patient Records 2024',
  },
});
// root.parentFolderId is the context's protected root (not null);
// root.isProtected === false

const sub = await client.folders.createFolder({
  body: {
    name: 'Intake Forms',
    parentFolderId: root.id!,            // set at CREATE only — folders cannot be moved
  },
});
// sub.parentFolderId === root.id
```

**Expected result:** folders nest under the given parent (or the context root if
omitted). A folder's parent is fixed at creation; there is no move/reparent operation.
Deleting a folder that still has children is rejected with a 400 — empty it first.

## Publish records for anonymous reading

A type with a `publicView` is readable by anyone who holds one of its app context's publishable keys, with no
sign-in. Use it for listing, detail and search pages, and mobile screens that show public data.

1. **The account owner turns public access on and chooses a public budget.** Nothing public is served until both
   are set: the account owner switches public access on and chooses the budget on the developer portal's Public access
   page, or sets the budget with `vectros public budget set --mode reserved --credits 2000` (the account owner's login).
2. **Declare the view** on the schema: `mode: 'projection'` (the default) publishes only the `fields` you list, and
   `mode: 'record'` publishes every declared field (image fields are never served). See [reference.md](reference.md) for `publicView`.
   `vectros blueprint apply` lists the fields that become public before it confirms.
3. **Issue a browser key** for the app context: `vectros public keys create --context my-app` (or
   `POST /v1/admin/public-keys`). A browser key (`pub_...`) is publishable: put it in your pages or app.
4. **Read from a page or an app** with `createPublicClient` from `@vectros-ai/react/public`:

   ```ts
   import { createPublicClient } from '@vectros-ai/react/public';

   const pub = createPublicClient({ key: 'pub_...' });
   const event = await pub.get('event', publicId);                        // one record: its public fields only
   const page = await pub.list('event', { by: { city: 'Lisbon' } });      // one published lookup field
   for await (const e of pub.listAll('event', { by: { city: 'Lisbon' } })) render(e); // every page
   const hits = await pub.search('event', { q: 'beach cleanup', mode: 'text' });
   ```

   `usePublicRecord(pub, 'event', publicId)` and `usePublicList(pub, 'event', { by: { city: 'Lisbon' } })` wrap the
   same reads in TanStack Query.

**Server-side rendering.** A server that builds public pages can use a server key (`vectros public keys create
--class pubs`) for higher rate limits: its server secret is printed once, and the client sends it in the
`X-Vectros-Public-Server-Secret` header. `createPublicClient({ key: 'pubs_...', serverSecret })` runs only outside a
browser page, Web Worker or React Native app, and refuses a server key without its secret.

**Python and Java.** The SDKs' `public` sub-client (`public_()` in Java) reads without a token: construct the client
with no `token` and pass the key as `k`. In Python:

```python
from vectros import VectrosApi

client = VectrosApi(base_url="https://api.vectros.ai")
record = client.public.get_public_record("event", public_id, k="pub_...")
page = client.public.list_public_records(type="event", k="pub_...",
                                         request_options={"additional_query_parameters": {"city": "Lisbon"}})
```

**What the answers mean.** A record that does not exist, is not published, or belongs to another app context is the
same `404`. A `429` carries `Retry-After`. A `503` carries an `errorCode`: what the account is missing
first (for example `PUBLIC_ACCESS_NOT_ENABLED`, `PUBLIC_BUDGET_MODE_UNSET`) or a budget that has run out. A public image answers 503 while its account's public access is paused. Public access is paused, for example, when the public budget is used up or the account is suspended. When the budget is the only reason, the answer says so.

**Rotating a key.** An app context holds at most two active keys. Issue the new key, move your pages to it, then
revoke the old one: revoking a key also revokes every older key of the same context
(`vectros public keys revoke <keyId> --context my-app` lists every key it covered).

**A key issue that timed out.** Send an `Idempotency-Key` header with `POST /v1/admin/public-keys` (1 to 128
characters of letters, digits, `.`, `_`, `:` and `-`; a UUID fits), and send the same value again when you retry an
issue that got no answer, a `429`, a `502`, `503` or `504`, or a `409` saying another key was issued at the same time: the platform answers the repeat with the key it already
issued (and, for a server key, the same secret) instead of issuing another, for 30 days. A repeat is refused with `422` `IDEMPOTENCY_KEY_REUSED` when the `Idempotency-Key` was used for the other key class, its key was revoked, or the app context was re-created: send a new one. `vectros public keys create`
and the developer portal do this for you. If an issue still ends without an answer, the key may have been issued: list
the context's keys (`vectros public keys list --context my-app`), and if a key you did not receive is there, revoke it
and issue again. Re-issue a server key whose answer was lost only after listing.

---

## Where to go next

- [explanation.md](explanation.md) — the concepts behind these calls.
- [reference.md](reference.md) — every method, parameter, validation rule, limit, and
  error code.
- [../operations-trust/compliance.md](../operations-trust/compliance.md) — version
  history retention and sensitive-data handling.
