API version: 0.3.0

---

# Schemas

A schema describes the elements of one node label or relation type. Every type has exactly one schema, which is a node
of the reserved type `Schema` and readable by everybody, see [`GET /schema`](/api/get-schema-collection.md). Schemas are
created implicitly when a type is used for the first time, and can be defined before that with
[`PUT /schema/<type>`](/api/put-schema.md), which needs the capability `schema.manage`, see
[roles and capabilities](/reference/roles-and-capabilities.md). The guide [defining a schema](/guide/defining-a-schema.md)
walks through a complete example.

## Settings

| Setting      | Meaning                                                                                                      | Default |
| ------------ | ------------------------------------------------------------------------------------------------------------ | ------- |
| `mode`       | How strictly elements are validated, see [modes](#modes).                                                    | `auto`  |
| `properties` | The definitions of the properties, see [properties](#properties) and [types](/reference/schemas/types.md).   | `{}`    |
| `files`      | Whether elements can have a file, its maximum size and mime types, see [files](#files).                      | `null`  |
| `rules`      | Expressions which every write has to satisfy, see [rules](/reference/schemas/rules.md).                      | `[]`    |
| `placement`  | Which database stores which kind of property, see [placement](/reference/schemas/placement.md).              | `null`  |
| `indices`    | Raw indices which span several properties, see [raw Neo4j indices](/reference/indices/raw-indices/neo4j.md). | `null`  |

The limits of the API, e.g. the number of rules, are listed in [limits](/reference/limits.md), the databases' limits
in [databases](/reference/databases.md).

[`GET /schema/<type>`](/api/get-schema.md) supports conditional requests: the response carries the `ETag` of the schema
node, and a request with a matching `If-None-Match` is answered with `304 Not Modified`. The response depends on the
token (the internal `_` properties are only part of it for tokens with `schema.manage`), which is why the `ETag` of the
reduced view for tokens without the capability has the suffix `-min` (`"abc-min"`, the full view has `"abc"`), and the
responses are `Cache-Control: private` and carry `Vary: Authorization`. The same applies to
`GET /schema`, [`GET /schema/<type>/revisions`](/api/get-schema-revisions.md) and
[`GET /migration`](/api/get-migration-collection.md), which have an `ETag` as well. Changing a schema with
[`PUT`](/api/put-schema.md), [`PATCH`](/api/patch-schema.md) or [`DELETE`](/api/delete-schema.md) supports `If-Match`, see the
[caching guide](/guide/caching-and-conditional-requests.md).

## Names

Node labels are written in UpperCamelCase (`SavedSearch`) and relation types in SCREAMING_SNAKE_CASE (`HAS_FILE`), so a
name tells whether it is a node label or a relation type, and no name is used for both. The rule only applies to types
which are created through the API; types which exist already keep their names. The names `Schema`, `SchemaRevision`
and `Migration` are reserved, like `User`, `Token` and `Upload`.

## Modes

| Mode      | Validation                                                                                                                                                |
| --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `auto`    | None. This is the default: elements can have any properties.                                                                                              |
| `partial` | Properties which are defined in the schema have to match their definition.                                                                                |
| `strict`  | As `partial`, and properties which are not defined in the schema are rejected, also in nested objects unless they allow them with `additionalProperties`. |

Modes only concern the properties: [rules](/reference/schemas/rules.md#evaluation) and the [files](#files) settings apply
in every mode.

Elements are validated synchronously on every write ([`POST /`](/api/post-index.md), [`POST /<uuid>`](/api/post-element.md),
[`PUT /<uuid>`](/api/put-element.md) and [`PATCH /<uuid>`](/api/patch-element.md)), violations are answered with
`400 Bad Request`. `null` removes a property on every level, at the top level of the element as well as in nested
objects, which is rejected for required properties. Existing elements are not checked when a schema changes, they are
validated the next time they are written.

## Properties

`properties` maps property names to definitions. Every definition has a `type`, which decides about the values and the
further settings, see [the type pages](/reference/schemas/types.md). These settings are available for every type:

| Setting         | Meaning                                                                                                                                                                                                                   | Default                        |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
| `type`          | Required. One of the types.                                                                                                                                                                                               |                                |
| `required`      | The property has to be present, i.e. it has to have a value which is not `null`. This is the only switch for presence; there is no `nullable` setting, except for the [items of lists](/reference/schemas/types/list.md). | `false`                        |
| `index`         | The indices of the property, an intent, a list of intents or an object per database, see [indices](/reference/indices.md).                                                                                                | none                           |
| `storage`       | The primary database which stores the property, `graph` or `document`, see [where properties are stored](/reference/schemas/placement.md).                                                                                | by placement role              |
| `search`        | Whether the property is part of the search copy in Elasticsearch.                                                                                                                                                         | `true`                         |
| `visibility`    | Whether the value is part of responses, `public` or `hidden`, see [visibility](#visibility).                                                                                                                              | `public`, `hidden` for vectors |
| `elasticsearch` | A raw mapping for Elasticsearch, see [raw Elasticsearch indices](/reference/indices/raw-indices/elasticsearch.md).                                                                                                        | none                           |
| `neo4j`         | A [raw index of Neo4j](/reference/indices/raw-indices/neo4j.md).                                                                                                                                                          | none                           |

The names `id`, `type`, `start`, `end` and `file`, and names starting with `_`, can not be defined, they are managed by
the API, see [elements](/reference/elements.md). Settings which a definition does not know, e.g. `nullable` on a
property, are rejected with `400 Bad Request`.

### Visibility

`visibility` decides whether the value of a property is part of the responses of the API. It is about relevance for
clients, not about access: who may read an element is decided by the [access model](/reference/access-model.md).

| Value      | Element responses | Rules and search                                               |
| ---------- | ----------------- | -------------------------------------------------------------- |
| `public`   | returned          | visible                                                        |
| `hidden`   | not returned      | visible to rules, stored, indexed and searchable               |
| `internal` | not returned      | not visible to rules; reserved for built-in schemas of the API |

- Hidden properties are left out of [`GET /<uuid>`](/api/get-element.md), the collections (index, children, parents and
  related elements), the [element hydration](/reference/search/element-hydration.md) search step and the schema and
  migration
  responses. They are still stored, written and patched like other properties, and a response without them is the normal
  representation of the element, so it has the same ETag. Other search steps, e.g. the raw results of an Elasticsearch
  query, return them.
- [Vectors](/reference/schemas/types/vector.md) are `hidden` unless the definition says `"visibility": "public"`. The
  normalized definition always states the visibility of a vector; for other types only `hidden` is written, `public` is
  the default.
- `internal` is reserved for the built-in schemas, users may set `public` or `hidden` only, anything else is rejected
  with `400 Bad Request`. The hash of a token and the machine state of an upload (`hashState`, `chunkIds`,
  `lastChunkId`) are `internal`. Properties which start with `_` are internal to the API anyway: they are never
  returned, never seen by rules and can't be part of a schema.
- The setting is only available for properties at the top level of the schema.

### Default properties

The properties which the API sets on every element are part of the schema of every type, node labels and relation
types, and `strict` schemas do not reject them:

| Property    | Type        |
| ----------- | ----------- |
| `createdAt` | `datetime`  |
| `updatedAt` | `datetime`  |
| `createdBy` | `elementId` |
| `updatedBy` | `elementId` |

Their definitions are fixed. A schema which defines them differently, e.g. with another type or as `required`, is
rejected with `400 Bad Request`; the same holds for the properties of the
[built-in types](/reference/schemas/built-in-schemas.md). The only setting which can be added to them is an `index`, e.g.
`{"type": "datetime", "index": "exact"}` for `createdAt`.

```json
{
  "mode": "partial",
  "properties": {
    "title": {
      "type": "string",
      "required": true,
      "maxLength": 200,
      "index": "fulltext"
    },
    "year": {
      "type": "integer",
      "index": "exact"
    },
    "tags": {
      "type": "list",
      "items": {
        "type": "string"
      }
    },
    "author": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string",
          "required": true
        }
      }
    }
  },
  "files": {
    "maxSize": 1048576,
    "mimeTypes": [
      "application/pdf",
      "image/*"
    ]
  }
}
```

## Files

`files` configures the files of the elements of the type: `enabled` (set it to `false` to forbid files), `maxSize` in
bytes and `mimeTypes`, a list of allowed mime types where `image/*` allows a whole group. The mime type is the detected
one, not the one the request states. The global maximum file size applies in addition. Uploads which violate the
settings are rejected with `400 Bad Request`. [Rules](/reference/schemas/rules.md#files) can check files in more detail.

## Revisions

Every change creates a `SchemaRevision` node, connected with `HAS_REVISION` to the schema, see
`GET /schema/<type>/revisions`. Revisions are immutable and part of backups. The full
definitions before and after the change are internal data (properties starting with `_`): they are only part of
responses to tokens with the capability `schema.manage`, and never of search results. Schema, revision and migration
nodes can not be written with the generic element endpoints; holders of the capability may, however, add access
relations to them.

## Migrations

Changing a schema does not build indices or change existing data. A [migration](/reference/schemas/migrations.md) applies
the indices, mappings and validators of the schema to the databases. The additive part is done right away, when the
schema is saved and when a [backup is loaded](/command/backup-load.md): the Elasticsearch index and the fields of its
mapping are created, and the MongoDB collection and its validator. Without it, the first element of a type would create
its Elasticsearch index with a dynamic mapping, which could contradict the schema and can not be changed afterwards.
Indices and everything which is incompatible with existing data stay migration work. If a step fails, the schema is
saved nevertheless and the migration reports the problem.

## Caching

Every write of an element needs the schemas of its type, so they are cached. A counter in Redis, the generation of the
schema cache, is incremented whenever a schema is written, changed, deleted or loaded by a backup, and by
[`schema:sync`](/command/schema-sync.md) and [`database:drop`](/command/database-drop.md). Every API instance keeps all stored
schemas in a local file named after the generation (`var/cache/<environment>/schemas/schemas-<generation>.cache`)
and builds it once, when the first request finds the file of the current generation missing. Types which are not in the
file do not have a schema. Older files are removed, and a request reads the generation and the schemas at most once.
If Redis or the file can not be used, schemas are read from the database, which is slower. A change is visible on
every instance with the next request, and the cache needs no cleanup after an update. The generation and the build
time of the file are part of the output of [`healthcheck`](/command/healthcheck.md).

## Backups

[`backup:create`](/command/backup-create.md) writes every schema to a file `schema/<Type>.json` of the backup, in one flat
folder. [`backup:load`](/command/backup-load.md) loads them before everything else, so the types of the loaded elements
already have their schema; the built-in definitions of the code win over the backup's. Backups without a
`schema` folder, e.g. from older versions, get `auto` schemas for their types when they are loaded.

---

Home: [Ember Nexus API docs](/index.md)

Full site map: [llms.txt](/llms.txt)

Previous: [Text embedding](/reference/search/text-embedding.md)

Next: [Property types](/reference/schemas/types.md)
