---
title: "API Reference for Virtuoso Vector Index"
description: "Complete API reference for the Virtuoso vector index — SQL DDL (CREATE VECTOR INDEX, DROP INDEX), SQL query functions (X_SIMILAR, VECTOR_DISTANCE), vector math functions (DOT_PRODUCT, VECTOR_NORM, VVEC_* arithmetic), SPARQL DDL and query surfaces, vector search over RDF literals (knnSimilar), embedding model management procedures, maintenance procedures, internal BIFs, registry settings, and catalog tables."
url: urn:osdi:this
dateModified: 2026-10-31T21:57:28Z
language: en
---
One page of the Vector Index documentation, MERGED by build_vector_index_docs.py from this template and the markdown in fixture/vector-index/. Do not edit the generated file: change this template or the generator and rebuild. It opens on the documentation header (dxshell.py), not on the site hero.

[Home](urn:osdi:site)/[Virtuoso](urn:osdi:sitevirtuoso/)/[Vector index](urn:osdi:sitevirtuoso/docs/vector-index/)/API reference for the Virtuoso vector index

# API reference for the Virtuoso vector index

Complete API reference for the Virtuoso vector index — SQL DDL (CREATE VECTOR INDEX, DROP INDEX), SQL query functions (X_SIMILAR, VECTOR_DISTANCE), vector math functions (DOT_PRODUCT, VECTOR_NORM, VVEC_* arithmetic), SPARQL DDL and query surfaces, vector search over RDF literals (knnSimilar), embedding model management procedures, maintenance procedures, internal BIFs, registry settings, and catalog tables.

Start  [Overview](urn:osdi:sitevirtuoso/docs/vector-index/) [Quickstart](urn:osdi:sitevirtuoso/docs/vector-index/quickstart/) [Tutorial: FAQ semantic search](urn:osdi:sitevirtuoso/docs/vector-index/tutorial-faq-semantic-search/)  Build  [SQL vector index how-to](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/) [SPARQL vector index how-to](urn:osdi:sitevirtuoso/docs/vector-index/howto-sparql-vector-index/) [Search RDF literals (knnSimilar)](urn:osdi:sitevirtuoso/docs/vector-index/knn-similar/)  Configure  [Embedding models](urn:osdi:sitevirtuoso/docs/vector-index/embedding-models/) [Index parameters](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/) [Similarity metrics](urn:osdi:sitevirtuoso/docs/vector-index/similarity-metrics/)  Operate  [VVec Console (web UI)](urn:osdi:sitevirtuoso/docs/vector-index/vvec-console/) [Troubleshooting](urn:osdi:sitevirtuoso/docs/vector-index/troubleshooting/)  Reference  API reference

This is the consolidated API reference for Virtuoso's native vector index. It lists every SQL and SPARQL entry point you use to create, query, maintain, and introspect a vector index, from DDL down to the internal `__VEC_*` BIFs and the catalog tables that back the feature.

The reference is organized by surface:

- **SQL DDL**: `CREATE VECTOR INDEX` and `DROP INDEX`
- **SQL query functions**: `X_SIMILAR` and `VECTOR_DISTANCE`
- **Vector math functions**: distance (`COSINE_DISTANCE`, `L1_DISTANCE`, `L2_DISTANCE`), `DOT_PRODUCT`/`INNER_PRODUCT`, `VECTOR_NORM`, and the `VVEC_*` arithmetic set
- **SPARQL DDL**: `create`/`refresh`/`drop vector index`
- **SPARQL query**: the `bif:vector_search` magic predicate and the procedures behind it
- **Vector search over RDF literals**: `knnSimilar` / `bif:knnSimilar` and the `DB.DBA.RDF_OBJ_VEC_INDEX_*` procedures
- **Embedding model management**: registration, embedding, refresh
- **Maintenance procedures (SQL and SPARQL)**: queue draining and workers
- **Internal BIFs**: the `__VEC_*` family
- **Registry settings** and **catalog tables**

Note

These pages describe the vector index in Virtuoso Open Source 7.2 as merged into the `develop/7` branch (server version 07.20.3243), built with `--enable-onnxruntime` and with the `vonnx` plugin loaded. It is not yet part of a tagged release.

For worked examples rather than a flat signature list, see [SQL vector index how-to](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/) or [SPARQL vector index how-to](urn:osdi:sitevirtuoso/docs/vector-index/howto-sparql-vector-index/).

---

## SQL DDL

### CREATE VECTOR INDEX

SQL

```
CREATE VECTOR INDEX <index_name>
ON <TABLE> [ (<column>) ]
[ USING '<model_name>' ]
[ WITH (
  dimensions      = <INTEGER>,
  distance_metric = 'cosine' | 'l2' | 'l1',
  hnsw_m          = <INTEGER>,
  ef_construction = <INTEGER>,
  reduce          = 'none' | 'truncate',
  build           = 'auto' | 'incremental' | 'bulk',
  rebuild         = 'auto' | 'replay' | 'fast',
  source_kind     = 'text' | 'vector'
) ]
[ IF NOT EXISTS ];
```

`CREATE VECTOR INDEX` creates a vector index on one column of a table, bound to an embedding model registered in `DB.DBA.ONNX_MODELS` — or, with `source_kind = 'vector'`, over a column that already holds vectors.

- **Requirements**: the table must have a **single-column primary key of an integer type** (`SMALLINT`, `INTEGER`, `BIGINT` or `NUMERIC`). The indexed column must hold text: `VARCHAR`, `NVARCHAR`, `LONG VARCHAR`, `LONG NVARCHAR` or `ANY`. Anything else fails with `VEC11`.
- **`USING '<model_name>'`** is required unless `source_kind = 'vector'` (`VEC12` without either; `VEC84` with both). A model name not in `DB.DBA.ONNX_MODELS` fails with `VEC18`.
- **The column list and `WITH (...)` are optional.** `dimensions` is taken from the model's `output_shape`, and the column is inferred when the table leaves no choice — exactly one text column. Two candidates, or none, is an error (`VEC11`) that names the candidates rather than a guess, because indexing the wrong column succeeds silently and only shows up later as poor search results. The shortest working form is:SQL`CREATE VECTOR INDEX "DOCS_VIDX" ON "DB"."DBA"."DOCS" USING 'granite-384-local';`
- **Defaults**: `dimensions` from the model, `distance_metric = 'cosine'`, `hnsw_m = 16`, `ef_construction = 200`, `reduce = 'none'`, `build = 'auto'` (incremental), `rebuild = 'auto'`, `source_kind = 'text'`. An explicit `dimensions` must equal the model's output (`VEC19`).
- **Privileges**: a DBA account — a non-DBA is refused even on a table it owns. Writing rows of an indexed table needs only the ordinary table privileges; for searching, see [Permissions](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/#permissions).
- **Atomic**: if any step of the build fails, the whole index is rolled back and no partial state is left behind.
- **Backfill**: rows already in the table are embedded and indexed inside the `CREATE` statement; when it returns, they are searchable.
- **Change tracking**: the statement creates `AFTER INSERT`, `AFTER UPDATE`, and `AFTER DELETE` triggers that record each change in `DB.DBA.VEC_SQL_QUEUE`. Changes reach the index when the queue is drained — see [Maintenance procedures (SQL)](#maintenance-procedures-sql).
- **`reduce = 'truncate'`**: Matryoshka dimension reduction — vectors are truncated to the first `dimensions` elements and L2-renormalized before they go into the graph. Requires `dimensions`, which may not exceed the model's output. Only for MRL-trained models (e.g. OpenAI text-embedding-3-small). See [Index parameters: Matryoshka reduction](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/#matryoshka-dimension-reduction).
- **`build`**: how the backfill builds the graph — linked one row at a time (`'incremental'`, which `'auto'` also means) or derived in one parallel pass once every row is embedded (`'bulk'`). See [Index parameters: build](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/#build-default-auto-which-means-incremental).
- **`rebuild`**: the index's **default rebuild method** — the one `__VEC_INDEX_REBUILD('<name>')` uses when called with no explicit method. `'fast'` builds the graph in memory in parallel and writes the packed page format; `'replay'` reinserts one node at a time (legacy page format); `'auto'` (default) uses `'fast'` from 10,000 rows, within the fast builder's memory cap. See Maintenance: rebuild methods.
- **`source_kind = 'vector'`**: the column already holds embeddings (`ANY`, `LONG ANY` or `(LONG) VARBINARY`, else `VEC87`); no model is involved, and `dimensions` is required. Off until a DBA runs `registry_set ('__vvec_passthrough_column', 'on')` (`VEC83`). See [Bring your own vectors](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/#bring-your-own-vectors-precomputed-embeddings).
- **`IF NOT EXISTS`**: when an index of that name already exists the statement does nothing.
- **Accepted aliases**: `d`/`dimension` for `dimensions`, `mt`/`metric` for `distance_metric`, `hm` for `hnsw_m`, `ef` for `ef_construction`, `rd`/`dim_reduce`/`reduction` for `reduce`, `bd`/`build_method` for `build`, `rb`/`rebuild_method` for `rebuild`, `sk` for `source_kind`. `rebuild` also accepts `'insert'` and `'incremental'` for `'replay'`, and `'bulk'` for `'fast'`.

Note

The `WITH` clause also accepts a set of **internal** keys that the DDL layer populates itself (`model`/`m`, `hidden_table`/`ht`, `state`/`st`, `model_id`/`mid`, `source_column`/`sc`, `pk_column`/`pk`). You do not set these by hand — `CREATE VECTOR INDEX` derives them from `ON <table> (<col>)` and `USING '<model>'`.

Tip

Because the build backfills existing rows inside the statement, a large table takes as long to index as it takes to embed. Create big indexes with `build = 'bulk'`, during a maintenance window.

A vector index on `DB.DBA.RDF_OBJ` is the index behind `knnSimilar`; create it with [`DB.DBA.RDF_OBJ_VEC_INDEX_CREATE`](#dbdbardf_obj_vec_index_create), which names it, records which literals it covers, and builds it.

### DROP INDEX

SQL

```
DROP INDEX <index_name> [ <TABLE> ] [ IF EXISTS ];
```

`DROP INDEX` removes the hidden managed table, the maintenance triggers, and the HNSW graph associated with the index. It does **not** drop the base table or the registered embedding model. An index that does not exist fails with `SQ019` unless `IF EXISTS` is given.

Important

There is no `DROP VECTOR INDEX` statement in SQL, and no `ON <table>` clause. Use the standard `DROP INDEX` statement. (SPARQL has its own [`drop vector index`](#drop-vector-index) for SPARQL indexes.)

---

## SQL query functions

### X_SIMILAR

SQL

```
X_SIMILAR(column, query [, k] [, metric])
```

`X_SIMILAR` returns a normalized **similarity score** in the range `[0, 1]`, where higher means more similar.

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `column` | column reference | — | The vector-indexed column |
| `query` | `VARCHAR` or vector | — | Query text, embedded with the index's bound model; or a query vector |
| `k` | `INTEGER` | the query's `TOP n` | How many candidates the HNSW search returns; it is also the search beam width |
| `metric` | `VARCHAR` | the index's metric | `'cosine'`, `'l2'` or `'l1'`; picks the index when the column has one per metric |

How it behaves depends on where it appears:

- **In a `WHERE` comparison with a bound** — `X_SIMILAR (c, 'text') > 0.7` with an explicit `k`, or in a query with `TOP n` — the HNSW index drives the scan (a *leading* ANN search). It returns at most `k` candidates, nearest first, each then tested against the threshold and the query's other predicates.
- **In a `WHERE` comparison with no bound** — no `k` and no `TOP` — an ANN search cannot answer a threshold, so none is used: every row that the other predicates admit is scored exactly, and the result is complete.
- **In the `SELECT` list**: scores each row returned. When the same query has a leading ANN search on that column, its score is reused.

While a leading ANN search runs, the select list can also name the virtual columns `SIMILARITY` and `DISTANCE` for its score and raw distance.

The score is derived from the raw distance:

- **cosine**: `1 - (distance / 2)`
- **L2 / L1**: `1 / (1 + distance)`

Given two vectors instead of a column, `X_SIMILAR (a, b [, metric])` scores them directly, with no index.

### VECTOR_DISTANCE

SQL

```
VECTOR_DISTANCE(column, query [, metric])
```

`VECTOR_DISTANCE` returns the **raw distance** value, where lower means more similar.

| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `column` | column reference | — | The vector-indexed column |
| `query` | `VARCHAR` or vector | — | Query text, embedded with the index's bound model; or a query vector |
| `metric` | `VARCHAR` | the index's metric | `'cosine'`, `'l2'` or `'l1'`; picks the index when the column has one per metric |

- **In `ORDER BY` of a query with `TOP n`**: the HNSW index drives the scan and returns the `n` nearest rows. Without `TOP`, every row is scored and sorted.

Distance ranges by metric:

- **cosine**: `[0, 2]`
- **L2**: `[0, inf)`
- **L1**: `[0, inf)`

Note

Both `X_SIMILAR` and `VECTOR_DISTANCE` accept the query as **plain text**. You do not embed the query yourself — the index embeds it with its own bound model at query time. The text must be a literal in the statement: text bound as a parameter (`?`) is not embedded and fails with `VEC33: Malformed query vector`, so embed a parameter with `DB.DBA.ONNX_EMBED_TEXT_FOR_MODEL` and pass the vector (see [Query with text](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/#query-with-text-primary-form)). For the difference between the two functions and when to use each, see [Similarity metrics](urn:osdi:sitevirtuoso/docs/vector-index/similarity-metrics/). A text query reads the model registry, so a non-DBA caller also needs read access to it — `SQ033` on `DB.DBA.ONNX_MODELS` otherwise; see [Permissions](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/#permissions).

---

## Vector math functions

These operate on **vector values**, not on indexes, and are callable by any user. They take and return vectors interchangeably with `vector(...)` literals and with embeddings from `ONNX_EMBED_TEXT`, so they compose freely.

A vector comes in two forms, and every function here accepts both: a `vector (...)` literal is an array of boxed numbers (`__tag` 193), while the embedding functions return — and the index stores — a flat array of 32-bit floats (`DV_ARRAY_OF_FLOAT`, `__tag` 202), which the engine reads with one copy instead of one unboxing per dimension. `isvector` is true for either; `VVEC_TO_FLOAT_VECTOR (v)` converts a vector to the flat form.

### Distance and magnitude

| Function | Returns |
| --- | --- |
| `COSINE_DISTANCE(a, b)` | cosine distance, `1 - similarity` |
| `L1_DISTANCE(a, b)` | Manhattan distance |
| `L2_DISTANCE(a, b)` | Euclidean distance |
| `VECTOR_DISTANCE(a, b [, metric])` | distance under a named metric, cosine by default |
| `DOT_PRODUCT(a, b)` | raw inner product — unbounded, may be negative |
| `INNER_PRODUCT(a, b)` | another spelling of `DOT_PRODUCT` |
| `VECTOR_NORM(a)` | Euclidean length |

SQL

```
SELECT DOT_PRODUCT (VECTOR (1.0, 2.0, 3.0), VECTOR (4.0, 5.0, 6.0));  -- 32
SELECT VECTOR_NORM (VECTOR (3.0, 4.0));                               -- 5
```

Together they give cosine similarity directly, which is the identity worth remembering:

SQL

```
SELECT DOT_PRODUCT (a, b) / (VECTOR_NORM (a) * VECTOR_NORM (b));
--  equals  1 - COSINE_DISTANCE (a, b)
```

Important

Inner product is available as a **function**, not as an index `distance_metric`. A raw inner product is unbounded and larger-is-closer, while a search score is derived from the distance into `[0, 1]` — `1 - distance / 2` for cosine, `1 / (1 + distance)` otherwise — and `score_limit` is bounded to `[0, 1]`: inner-product distances would fall outside every range the query surface accepts. If you want inner-product ranking *from an index*, normalize your vectors: for unit vectors cosine and inner product coincide, and cosine is already the default.

### Arithmetic

| Function | Returns |
| --- | --- |
| `VVEC_ADD(a, b)` | elementwise sum |
| `VVEC_SUBTRACT(a, b)` | elementwise difference |
| `VVEC_MULTIPLY(a, b)` | elementwise product |
| `VVEC_DIVIDE(a, b)` | elementwise quotient |
| `VVEC_SCALAR_MULTIPLY(a, k)` | every element times `k` |
| `VVEC_SCALAR_DIVIDE(a, k)` | every element over `k` |
| `VVEC_NORMALIZE(a)` | `a` scaled to unit length |
| `VVEC_DIMENSION(a)` | the vector's width |

`VVEC_MULTIPLY` is the counterpart of `VVEC_DIVIDE`. Results are flat float vectors.

SQL

```
--  centroid of three embeddings
SELECT VVEC_SCALAR_DIVIDE (VVEC_ADD (VVEC_ADD (v1, v2), v3), 3);

--  cosine similarity the long way round
SELECT DOT_PRODUCT (VVEC_NORMALIZE (a), VVEC_NORMALIZE (b));
```

Note

Dividing by zero, and normalizing a zero vector, **raise** (`22012`/`VEC41`) rather than returning `inf`/`NaN`. A `NaN` inside a vector does not fail where it was created — it would silently corrupt every later distance computation, and the damage would surface as wrong search results with nothing pointing back at the cause.

Mismatched dimensions, and arguments that are not vectors, are refused by every function in both tables with SQLSTATE `22023`.

---

## SPARQL DDL

### CREATE VECTOR INDEX (shorthand)

SPARQL

```
SPARQL CREATE VECTOR INDEX <iri>
  ON GRAPH <graph_iri>
  for predicate <predicate_iri>
  USING MODEL '<model_name>'
  WITH (dimensions = <INT>, distance = 'cosine' | 'l1' | 'l2', hnsw_m = <INT>,
        ef_construction = <INT>, maintenance = 'manual' | 'async',
        reduce = 'none' | 'truncate', build = 'auto' | 'incremental' | 'bulk',
        rebuild = 'auto' | 'replay' | 'fast', label = '<text>', comment = '<text>')
```

The shorthand form targets a single graph and predicate. Use it when your embeddable text lives in one predicate across one graph.

- **Options and defaults**: `dimensions` comes from the model when omitted (it is required with `reduce = 'truncate'`, `VEC73`), `distance = 'cosine'`, `hnsw_m = 16`, `ef_construction = 200`, `maintenance = 'manual'`, `reduce = 'none'`. `build` and `rebuild` mean what they mean in SQL (`build_method` and `rebuild_method` are accepted too).
- **Option names are SPARQL's own**: the metric is `distance`, and the SQL short aliases are not accepted — an unknown option fails with `VEC13`. The values of `distance`, `maintenance` and `reduce` must be written in lower case.
- **`maintenance`** selects whether changes to the graph are queued automatically (`'async'`) or picked up only by `refresh vector index` (`'manual'`).
- **`reduce`** enables Matryoshka dimension reduction — see [Index parameters: Matryoshka reduction](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/#matryoshka-dimension-reduction).
- **`label`** (up to 255 characters) and **`comment`** (up to 2000) describe the index rather than configuring it — see Naming an index.
- Creating an index does not embed anything; the first [`refresh vector index`](#refresh-vector-index) does.

Important

Like other quad-map DDL, the SPARQL vector-index statements report each step as a `(STATE, MESSAGE)` row of their result, and a failure is such a row: an unknown option comes back as `VEC13 Unknown vector index option: …` while the statement itself completes with SQLSTATE `00000`. A client that checks only the SQLSTATE must also read the rows — or check `DB.DBA.SPARQL_VEC_INDEX` afterwards. A failed `create` leaves no index behind.

### CREATE VECTOR INDEX (general selector)

SPARQL

```
SPARQL CREATE VECTOR INDEX <iri>
  KEY ?key_var
  EMBEDDING ?text_var
  [ FROM <graph_iri> | FROM named <graph_iri> ]...
  WHERE { ... pattern ... }
  USING MODEL '<model_name>'
  WITH (dimensions = <INT>, distance = 'cosine', maintenance = 'manual' | 'async', reduce = 'none' | 'truncate')
```

The general selector form lets you define the key and embedding text with an arbitrary SPARQL `WHERE` pattern. Use it when the embeddable text is spread across multiple predicates or must be assembled from several triples. It takes the same options as the shorthand form.

**Scoping the pattern.** Triples can be scoped either by an explicit `GRAPH <iri>` inside the `WHERE`, or by one or more `FROM` clauses on the selector — which is the form a query lifted from a SPARQL endpoint usually already has:

SPARQL

```
SPARQL PREFIX schema: <http://schema.org/>
CREATE VECTOR INDEX <urn:docs:idx>
  KEY ?doc EMBEDDING ?name
  FROM <urn:openlink:faqs>
  WHERE { ?doc a schema:Question ; schema:name ?name }
  USING MODEL 'granite-384-local'
  WITH (dimensions = 384, distance = 'cosine', maintenance = 'async');
```

Important

When `maintenance = 'async'`, every triple pattern must be scoped to a named graph — by an explicit `GRAPH <iri>`, or by a `FROM <iri>` on the selector. The parser extracts `(graph, predicate)` dependency pairs and stores them in `DB.DBA.SPARQL_VEC_INDEX_TRIGGER`; a triple with no `GRAPH` takes its pairs from the `FROM` graphs, one per graph, since a change in any of them can alter what the selector enumerates. If no pairs can be extracted — a pattern with neither, or a variable graph such as `GRAPH ?g` — `VEC77` is signalled and the index is not created. See Maintenance: async scoping.

Note

`FROM NAMED` is accepted and carried into the enumeration, but it does not scope triples for async: it only makes a graph available to a `GRAPH ?g` pattern, and a variable graph is not a dependency the trigger extractor can pin down.

### REFRESH VECTOR INDEX

SPARQL

```
SPARQL refresh VECTOR INDEX <iri>
```

`refresh vector index` evaluates the selector and brings the index up to date: it embeds subjects that are new or whose text changed, and removes those that no longer match. Unchanged subjects are not embedded again. The first refresh after `create vector index` is the initial build; after that, run it after bulk loads or edits to an index with `maintenance = 'manual'`.

While a refresh runs, the index is in state `refreshing` and `bif:vector_search` on it fails with `VEC50` rather than returning partial results. A refresh embeds batches in parallel on the server's async-queue threads ([`__vec_embed_concurrency`](#registry-settings)); when none is free it retries once a second and, after 600 tries, fails with `VEC36` — *No free aq thread for &lt;index&gt; after 600 retries; raise aq_max_threads or lower __vec_embed_concurrency* — where `aq_max_threads` is the `[Parameters] AsyncQueueMaxThreads` setting in `virtuoso.ini`.

### DROP VECTOR INDEX

SPARQL

```
SPARQL DROP VECTOR INDEX <iri>
SPARQL DROP SILENT VECTOR INDEX <iri>
```

`drop vector index` removes the SPARQL vector index identified by `<iri>`: its catalog row, queue entries, backing table, and native index. The `silent` variant suppresses the error if the index does not exist.

---

## SPARQL query

### bif:vector_search

SPARQL

```
?subject bif:vector_search "query text"
option (
  INDEX <index_iri> | INDEX (<iri>, <iri>, ...) | INDEX *,
  ranking raw | relevance,
  score ?score_var,
  distance ?distance_var,
  score_limit <float>,
  distance_limit <float>,
  LIMIT <INT>,
  ef_search <INT>
)
```

`bif:vector_search` is the public RDF search interface. It performs HNSW ANN search over a SPARQL vector index, embedding the query text once with the index's bound model, and checks the caller's read permission on each hit's graph.

| Option | Type | Description |
| --- | --- | --- |
| `index` | IRI | The vector index to search. Omitted, exactly one active index must exist (`VEC58`, `VEC59`) |
| `index` | IRI list | `index (<a>, <b>)` searches all of them and returns one merged result |
| `index` | `*` | Every active index the caller may read, expanded when the query runs |
| `ranking` | `raw` / `relevance` | How a multi-index result is ordered. Default `raw` for a list, `relevance` for `*` |
| `score` | variable | Binds the normalized similarity score `[0, 1]` for each result — the value `X_SIMILAR` returns for the same distance |
| `distance` | variable | Binds the raw distance for each result |
| `score_limit` | float | Drops results scoring below this, from 0 to 1 (`VEC60`–`VEC62`) |
| `distance_limit` | float | Drops results with a raw distance above this; finite, at least 0 (`VEC64`, `VEC65`) |
| `limit` | int | Maximum number of results, 1–10000. Default 10 (`VEC55`) |
| `ef_search` | int | Search beam width, from `limit` to 100000. Default 100 (`VEC56`) |

Important

`ef_search` must be greater than or equal to `limit`. Its default is 100, so a query that asks for `limit 200` must also raise `ef_search`, or it fails with `VEC56`. See [Index parameters](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/) for tuning guidance.

Note

Name the `score` and `distance` variables anything but `?s`: in this version a variable called `?s` in those options receives the subject instead of the value.

Important

**One `index` option per search.** `option (index <a>, index <b>)` is a compile error (`SP031`); write several indexes as one list, `option (index (<a>, <b>))`, or all of them with `option (index *)`.

Over several indexes, `limit` means N results in total, a subject in two indexes comes back once, and `ranking raw` (and `score_limit` / `distance_limit`) require every index in the set to share a model and a distance metric — a mixed set raises `VEC68` naming both indexes and the difference. See [Searching several indexes](urn:osdi:sitevirtuoso/docs/vector-index/howto-sparql-vector-index/#searching-several-indexes).

### DB.DBA.VEC_INDEX_SEARCH_ROWS

SQL

```
DB.DBA.VEC_INDEX_SEARCH_ROWS (IN idx_iri VARCHAR,
                              IN query_text VARCHAR,
                              IN limit_count INTEGER := 10,
                              IN ef_search INTEGER := 100,
                              IN score_limit double precision := NULL,
                              IN distance_limit double precision := NULL,
                              IN required_graph_iri VARCHAR := NULL)
```

The row source a single-index `bif:vector_search` compiles to. A procedure view returning `(result_entity_iid, result_distance, result_score)`, nearest first, with the same option checks and per-hit graph-permission check as the SPARQL form. Executable by `SPARQL_SELECT`.

### DB.DBA.VEC_INDEX_SEARCH_ROWS_MULTI

SQL

```
DB.DBA.VEC_INDEX_SEARCH_ROWS_MULTI (IN idx_list any, IN ranking_mode VARCHAR,
                                    IN query_text VARCHAR,
                                    IN limit_count INTEGER := 10,
                                    IN ef_search INTEGER := 100,
                                    IN score_limit double precision := NULL,
                                    IN distance_limit double precision := NULL,
                                    IN required_graph_iri VARCHAR := NULL)
```

The row source behind a multi-index `bif:vector_search`. `idx_list` is a vector of index IRIs, or the string `'*'`; `ranking_mode` is `'raw'` or `'relevance'` (`VEC66` otherwise). Returns `(result_entity_iid, result_distance, result_score)`, deduplicated by subject and ordered by the ranking mode. Executable by `SPARQL_SELECT`.

The wildcard is expanded here, not by the SQL generator, because a compiled SPARQL plan is cached by query text — expanded at compile time, the first caller's set of indexes would be baked into the plan every other caller reuses.

### DB.DBA.VEC_INDEX_SEARCH

SQL

```
DB.DBA.VEC_INDEX_SEARCH (IN idx_iri VARCHAR, IN query_text VARCHAR,
                         IN limit_count INTEGER := 10,
                         IN ef_search INTEGER := 100) returns any
```

Searches one SPARQL index directly and returns a vector of `(row_id, distance)` pairs, nearest first. **DBA-only** (`VEC54`); it checks the index graph's read permission (`VEC57`) but not each hit's, so applications use `bif:vector_search`. Useful for diagnosing an index that returns no rows.

---

## Vector search over RDF literals

A second kind of RDF vector index embeds RDF **literals** rather than subjects: one index over `DB.DBA.RDF_OBJ`, searched with `knnSimilar` in SQL and `bif:knnSimilar` in SPARQL, the way `contains` / `bif:contains` search the free-text index. For a walkthrough, see [Vector search over RDF literals (knnSimilar)](urn:osdi:sitevirtuoso/docs/vector-index/knn-similar/).

The index embeds string literals — plain, language-tagged and `xsd:string`, never XML or geometry — that have a row in `DB.DBA.RDF_OBJ`. A literal stored inline in `RDF_QUAD.O` without such a row is not covered; string literals written by SPARQL `INSERT` and the RDF loaders get one, short ones included.

### knnSimilar (SQL)

SQL

```
knnSimilar (O, query_text [, index_name] [, k])
```

A predicate on the `O` column of `DB.DBA.RDF_QUAD` (`VEC94` elsewhere): true for the `k` literals nearest to `query_text` (default 100). `index_name` is needed only when more than one RDF literal index exists (`VEC96`); with none, the query fails to compile with `VEC95`. The virtual columns `SIMILARITY` and `DISTANCE` carry each match's score (on the `X_SIMILAR` scale) and raw distance.

SQL

```
SELECT TOP 5 id_to_iri (S), __ro2sq (O), SIMILARITY
  FROM DB.DBA.RDF_QUAD
 WHERE knnSimilar (O, 'reset customer password', 5)
 ORDER BY SIMILARITY DESC;
```

`k` counts literals, not rows: every quad whose object is one of the `k` literals matches, and other conditions on the quad are applied to those, so a selective pattern can return fewer rows than `k`. The search is approximate and `k` is also its breadth, so a small `k` can miss a close match — keep the default or more; see [How k works](urn:osdi:sitevirtuoso/docs/vector-index/knn-similar/#how-k-works).

### bif:knnSimilar (SPARQL)

SPARQL

```
?o bif:knnSimilar "query text"
option (INDEX <name>, LIMIT <k>, score ?score_var, distance ?distance_var)
```

Filters the triple pattern that binds `?o` to the `limit` (default 100) literals nearest to the query text. It takes one index (`SP031` for a list) and only these four options (`SP031` otherwise).

### DB.DBA.RDF_OBJ_VEC_INDEX_CREATE

SQL

```
DB.DBA.RDF_OBJ_VEC_INDEX_CREATE (IN _name VARCHAR,
                                 IN _model VARCHAR,
                                 IN _opts any := NULL,
                                 IN _min_length INTEGER := 0,
                                 IN _langs any := NULL,
                                 IN _build VARCHAR := 'bulk',
                                 IN _build_now INTEGER := 1)
```

Creates a vector index over the literals in `DB.DBA.RDF_OBJ` and, unless `_build_now = 0`, embeds them and builds the graph in the same call.

| Parameter | Description |
| --- | --- |
| `_name` | The index's name: an IRI or a plain name. The SQL key is `RDF_OBJ_` followed by the name with every character other than a letter or digit as `_`. An empty name fails with `VEC90` |
| `_model` | A model registered in `DB.DBA.ONNX_MODELS` |
| `_opts` | `WITH` options as a vector of name/value pairs, e.g. `vector ('distance_metric', 'cosine', 'hnsw_m', 16)` (`VEC93` if malformed) |
| `_min_length` | Skip literals shorter than this many characters |
| `_langs` | Language tags to embed, `''` for literals with none; `null` for any |
| `_build` | How a refresh builds the graph: `'bulk'` (default) or `'incremental'` (`VEC93` otherwise) |
| `_build_now` | `0` registers the index without embedding; then run `_EMBED` and `_BUILD` |

A name that is taken, or that maps to the same key as an existing index, fails with `VEC97`.

### DB.DBA.RDF_OBJ_VEC_INDEX_REFRESH / EMBED / BUILD / DROP

SQL

```
DB.DBA.RDF_OBJ_VEC_INDEX_REFRESH (IN _index VARCHAR)
DB.DBA.RDF_OBJ_VEC_INDEX_EMBED (IN _index VARCHAR)
DB.DBA.RDF_OBJ_VEC_INDEX_BUILD (IN _index VARCHAR)
DB.DBA.RDF_OBJ_VEC_INDEX_DROP (IN _index VARCHAR)
```

- `_REFRESH` embeds every eligible literal not yet embedded, removes ones no longer eligible, and builds the graph — what `_CREATE` does by default.
- `_EMBED` embeds without building the graph; run again after an interruption, it continues where it stopped. `_BUILD` then builds the graph from everything embedded, in one pass. Either fails with `VEC98` while the index is already being embedded or built.
- `_DROP` drops the index and its tables.

`_index` is the name given to `_CREATE`. An unknown index fails with `VEC91` (`SQ019` from `_DROP`).

### DB.DBA.RDF_OBJ_VEC_LOG_DRAIN

SQL

```
DB.DBA.RDF_OBJ_VEC_LOG_DRAIN (IN _max_rows INTEGER := 1000) returns INTEGER
```

Literals created after an index was built are logged in `DB.DBA.RDF_OBJ_VEC_LOG`. This embeds up to `_max_rows` of them into every index in state `ready` and returns the number of log rows consumed. Nothing is drained while any index is being embedded or built: the literals stay logged until the graph exists to take them. The SQL worker's tick also drains this log (see [Maintenance procedures (SQL)](#maintenance-procedures-sql)).

- **Privileges**: all `DB.DBA.RDF_OBJ_VEC_INDEX_*` procedures are DBA-only (`VEC92`).

---

## Embedding model management (SQL procedures)

The procedures below are DBA-only unless stated. For the model lifecycle, see [Embedding models](urn:osdi:sitevirtuoso/docs/vector-index/embedding-models/).

### DB.DBA.ONNX_API_KEY_SET

SQL

```
DB.DBA.ONNX_API_KEY_SET(key_name VARCHAR, api_key VARCHAR)
```

`ONNX_API_KEY_SET` stores an API key in the registry under the given `key_name`. You reference this name later when registering an HTTP embedding provider — the model row holds the **registry name**, never the key itself.

- **Privileges**: DBA-only.

### DB.DBA.ONNX_PROVIDER_API_KEY_SET

SQL

```
DB.DBA.ONNX_PROVIDER_API_KEY_SET(provider VARCHAR, api_key VARCHAR) RETURNS VARCHAR
```

Stores a key under the conventional registry name for a provider and returns that name: `ONNX_API_KEY_OPENAI`, `ONNX_API_KEY_OLLAMA`, `ONNX_API_KEY_LMSTUDIO` or `ONNX_API_KEY_OPENAI_COMPATIBLE`.

### DB.DBA.ONNX_REGISTER_HTTP_EMBED_MODEL

SQL

```
DB.DBA.ONNX_REGISTER_HTTP_EMBED_MODEL(
  _model_name VARCHAR,
  _provider VARCHAR,        -- 'openai', 'ollama', 'lmstudio', 'openai_compatible'
  _remote_model VARCHAR,
  _dimensions INTEGER,
  _endpoint VARCHAR := NULL,
  _api_key_name VARCHAR := NULL,  -- registry name, NOT the key itself
  _timeout INTEGER := 30,
  _description VARCHAR := NULL,
  _insecure INTEGER := 0
)
```

`ONNX_REGISTER_HTTP_EMBED_MODEL` registers a remote HTTP embedding provider in `DB.DBA.ONNX_MODELS` so that a vector index can bind to it. Registering an existing name replaces its row.

| Parameter | Description |
| --- | --- |
| `_model_name` | Unique model name to register |
| `_provider` | Provider kind: `'openai'`, `'ollama'`, `'lmstudio'`, or `'openai_compatible'` |
| `_remote_model` | The provider's model identifier (e.g. `text-embedding-3-small`) |
| `_dimensions` | Expected embedding dimension; every response is checked against it |
| `_endpoint` | HTTP endpoint URL (required for `openai_compatible`; the provider's default otherwise). Must be `https://` unless the host is loopback or a private network |
| `_api_key_name` | Registry key name from `ONNX_API_KEY_SET` — **not** the key itself. Defaults to `ONNX_API_KEY_OPENAI` for `openai` |
| `_timeout` | HTTP timeout in seconds, 1–300 (default `30`) |
| `_description` | Optional free-text description |
| `_insecure` | `0` (default) or `1`; stored as `provider_insecure` and passed to the HTTP client's `insecure` option on each request. It does not relax the `https://` rule above |

Caution

Pass the **registry name** in `_api_key_name`, never the raw API key. The value is looked up by that name at request time, so a key passed here finds nothing, and the provider rejects the request (`401`).

### DB.DBA.ONNX_EMBED_TEXT_FOR_MODEL

SQL

```
DB.DBA.ONNX_EMBED_TEXT_FOR_MODEL(model_name VARCHAR, text VARCHAR) RETURNS any
```

`ONNX_EMBED_TEXT_FOR_MODEL` returns the embedding vector for the given `text` using the named model. It works for **both** local ONNX models and remote HTTP providers — the dispatch is handled by the model registry. A local model with no handle is loaded first.

### DB.DBA.ONNX_EMBED_BATCH_FOR_MODEL

SQL

```
DB.DBA.ONNX_EMBED_BATCH_FOR_MODEL(model_name VARCHAR, texts ANY) RETURNS any
```

The batch counterpart: returns one embedding per text of the `texts` vector, in order. An HTTP provider gets one request per `provider_max_batch` texts.

### DB.DBA.ONNX_MODEL_REFRESH

SQL

```
DB.DBA.ONNX_MODEL_REFRESH(model_name VARCHAR) RETURNS INTEGER
```

`ONNX_MODEL_REFRESH` loads a local ONNX model with its row's path, thread counts and other load options, and stores the handle in the row. It returns the handle, `1` for an HTTP provider (whose handle it clears), and `0` on failure. A model already loaded with the same file and options keeps its handle, so a refresh does not pick up a file replaced on disk: unload the old handle with `ONNX_UNLOAD_MODEL` first. A change to the row's thread counts does load a new handle. `DB.DBA.ONNX_BOOTSTRAP_MODELS ()`, run at every start, registers the bundled model and refreshes every registered model this way.

### ONNX_EMBED_TEXT and ONNX_EMBED_BATCH (BIFs)

SQL

```
ONNX_EMBED_TEXT(handle INTEGER, text VARCHAR) RETURNS any
ONNX_EMBED_BATCH(handle INTEGER, texts ANY) RETURNS any
```

Lower-level plugin BIFs that take a model **handle**, not a name. Obtain the handle from the catalog:

SQL

```
SELECT handle FROM DB.DBA.ONNX_MODELS WHERE model_name = '...';
```

`ONNX_LOAD_MODEL (path, options)` and `ONNX_UNLOAD_MODEL (handle)` load and unload a model file and are DBA-only — see [Embedding models](urn:osdi:sitevirtuoso/docs/vector-index/embedding-models/).

Note

These are BIFs — call them **unqualified**, without the `DB.DBA.` prefix. Most application code should prefer `ONNX_EMBED_TEXT_FOR_MODEL`, which resolves the handle from a name and works for HTTP providers too.

---

## Maintenance procedures (SQL)

### DB.DBA.VEC_SQL_QUEUE_DRAIN

SQL

```
DB.DBA.VEC_SQL_QUEUE_DRAIN(max_items INTEGER := 100) RETURNS INTEGER
```

`VEC_SQL_QUEUE_DRAIN` applies up to `max_items` pending changes from `DB.DBA.VEC_SQL_QUEUE` to their SQL vector indexes and returns the number applied. Until a change is drained, the row it describes is not searchable in its new form.

### DB.DBA.VEC_SQL_WORKER_START / STOP / STATUS

SQL

```
DB.DBA.VEC_SQL_WORKER_START(interval INTEGER := 1)
DB.DBA.VEC_SQL_WORKER_STOP()
DB.DBA.VEC_SQL_WORKER_STATUS()  -- returns a name/value vector
```

The SQL worker is a scheduled event, not a thread:

- `VEC_SQL_WORKER_START` registers the event `VEC_SQL_WORKER` in `DB.DBA.SYS_SCHEDULED_EVENT`, which runs `DB.DBA.VEC_SQL_WORKER_TICK (100)`: `VEC_SQL_QUEUE_DRAIN (100)`, then [`RDF_OBJ_VEC_LOG_DRAIN (1000)`](#dbdbardf_obj_vec_log_drain). The argument becomes the event's interval, which the server's scheduler counts in **minutes** (the parameter is named `_interval_seconds`, but it is not seconds), and the scheduler itself wakes only every `[Parameters] SchedulerInterval` minutes — 10 in the shipped `virtuoso.ini`. Expect the queue to drain every few minutes at most; drain it yourself when a change has to be searchable at once.
- `VEC_SQL_WORKER_STOP` deletes the event.
- `VEC_SQL_WORKER_STATUS` returns a name/value vector — call it in a `SELECT`; as a bare statement it prints nothing:

SQL

```
SELECT obj2json (DB.DBA.VEC_SQL_WORKER_STATUS ());
-- ["pending",0,"error",0,"last_run",null,"last_count",0,"last_error",null]
```

---

## Maintenance procedures (SPARQL)

### DB.DBA.VEC_INDEX_QUEUE_DRAIN

SQL

```
DB.DBA.VEC_INDEX_QUEUE_DRAIN(max_items INTEGER := 1000) RETURNS INTEGER
```

`VEC_INDEX_QUEUE_DRAIN` processes up to `max_items` pending entries of `DB.DBA.SPARQL_VEC_QUEUE` — the subjects that `maintenance = 'async'` indexes queued — and returns the number processed. It processes nothing while the queue is suspended.

### DB.DBA.VEC_INDEX_QUEUE_SUSPEND / RESUME / IS_SUSPENDED

SQL

```
DB.DBA.VEC_INDEX_QUEUE_SUSPEND()
DB.DBA.VEC_INDEX_QUEUE_IS_SUSPENDED() RETURNS INTEGER
DB.DBA.VEC_INDEX_QUEUE_RESUME()
```

These procedures control the SPARQL index queue:

- `VEC_INDEX_QUEUE_SUSPEND` pauses processing of the queue. Changes are still queued, so nothing is lost; use it around a bulk load.
- `VEC_INDEX_QUEUE_IS_SUSPENDED` returns `1` if the queue is suspended, `0` otherwise.
- `VEC_INDEX_QUEUE_RESUME` resumes processing.

### DB.DBA.VEC_INDEX_WORKER_START / STOP / STATUS / CONFIGURE / RUN_ONCE

SQL

```
DB.DBA.VEC_INDEX_WORKER_CONFIGURE(batch_size INTEGER := 100, idle_delay INTEGER := 5)
DB.DBA.VEC_INDEX_WORKER_START()
DB.DBA.VEC_INDEX_WORKER_STATUS()
DB.DBA.VEC_INDEX_WORKER_RUN_ONCE() RETURNS INTEGER
DB.DBA.VEC_INDEX_WORKER_STOP()
```

The SPARQL worker is an enable flag and a single-pass procedure; the server does not run it on its own:

- `VEC_INDEX_WORKER_START` and `VEC_INDEX_WORKER_STOP` set and clear the flag.
- `VEC_INDEX_WORKER_RUN_ONCE` drains up to `batch_size` queue entries while the flag is set, and returns the number processed — `0` while it is clear. Call it from your own scheduled event or loop, or from the [VVec Console](urn:osdi:sitevirtuoso/docs/vector-index/vvec-console/)'s Maintenance page.
- `VEC_INDEX_WORKER_CONFIGURE` sets `batch_size` (1–10000, `VEC70`) and `idle_delay` (1–3600 seconds, `VEC71`). The server stores and reports `idle_delay` but does not use it.
- `VEC_INDEX_WORKER_STATUS` returns one row: `worker_enabled`, `worker_batch_size`, `worker_idle_delay`, `worker_last_run`, `worker_last_error`, `pending_count`, `error_count`, `worker_processed`.

### DB.DBA.VEC_INDEX_GENERATE_NAME

SQL

```
DB.DBA.VEC_INDEX_GENERATE_NAME (IN idx_iri VARCHAR) returns VARCHAR
```

The internal (SQL key) name of a SPARQL index, `VECIDX_` followed by the MD5 of the IRI — the name the `__VEC_*` BIFs take. It is also stored in `SPARQL_VEC_INDEX.SVI_INTERNAL_NAME`.

### DB.DBA.VEC_INDEX_SET_METADATA

SQL

```
DB.DBA.VEC_INDEX_SET_METADATA (IN idx_iri VARCHAR,
                               IN idx_label any := NULL,
                               IN idx_comment any := NULL) returns VARCHAR
```

Sets an existing index's `rdfs:label` and `rdfs:comment` without dropping and rebuilding it. `NULL` for an argument leaves that value alone; the empty string clears it. Returns `idx_iri`.

Callable from SPARQL:

SPARQL

```
SPARQL PREFIX sql: <sql:>
SELECT (sql:VEC_INDEX_SET_METADATA ('urn:docs:idx', 'Support articles') AS ?done)
WHERE { };
```

Two gates, both of which must pass: SQL `EXECUTE` on the procedure — granted to no one on a fresh install, `SR186` without it — and an owner-or-DBA check inside it, which raises `VEC28` for an index the caller does not own. Over-long values raise `VEC26`; an unknown index raises `VEC27`. See Naming an index.

### DB.DBA.VEC_INDEX_META_VIEW_CREATE / DROP

SQL

```
DB.DBA.VEC_INDEX_META_VIEW_CREATE () returns VARCHAR
DB.DBA.VEC_INDEX_META_VIEW_DROP () returns VARCHAR
```

Install or remove the RDF view that publishes `SVI_LABEL` and `SVI_COMMENT` in the graph `<urn:vvec:indexes>`. The view is installed at server start — on a brand-new database, by the first `create vector index` instead — and normally needs neither. Both are idempotent and return `''` on success, otherwise a `'SQLSTATE: message'` diagnostic — quad-map DDL reports a failed operation as a row in its result set while the statement itself still says `00000`, so a caller checking only the SQLSTATE cannot tell a half-created mapping from a successful install.

### DB.DBA.VEC_INDEX_SET_TRIGGERS

SQL

```
DB.DBA.VEC_INDEX_SET_TRIGGERS(idx_iri VARCHAR, pairs ANY) RETURNS any
```

`VEC_INDEX_SET_TRIGGERS` stores the `(graph, predicate)` dependency pairs for a general-selector vector index. It is called by the SPARQL parser during `CREATE VECTOR INDEX` after `VEC_INDEX_SET_SELECTOR`. `pairs` is a flat vector of `[graph_iri_1, pred_iri_1, graph_iri_2, pred_iri_2, ...]`; an empty predicate IRI (`''`) means graph-only fallback (match any predicate in that graph). An empty `pairs` means the `WHERE` pattern is not async-scopable; no rows are stored and `VEC_INDEX_SET_OPTIONS` later rejects `maintenance = 'async'` with `VEC77`.

- **Privileges**: DBA-only (called internally by the parser QM dispatch).

---

## Internal BIFs (DBA-only, no DB.DBA. prefix)

The `__VEC_*` functions are internal BIFs for inspecting and driving the HNSW graph directly. They are primarily intended for debugging, validation, and operational scripts. They take the index's SQL name; for a SPARQL index that is [`VEC_INDEX_GENERATE_NAME`](#dbdbavec_index_generate_name) of its IRI.

| BIF | Description |
| --- | --- |
| `__VEC_INDEX_METRICS(index_name)` | Name/value pairs: `dimension`, `distance_metric`, `hnsw_m`, `managed_rows`, `graph_nodes`, `deleted_nodes`, `insert_count`, `search_count`, `search_usec`, `bytes_written`, `layer0_hit_rate`, `state` |
| `__VEC_INDEX_PAGE_STATS(index_name)` | Name/value pairs: `metadata_pages`, `node_pages`, `deleted_pages`, `entry_point_dp`, `max_layer`, `inline_dim_limit`, `overflow_pages`, `deleted_overflow_pages`, `physical_node_pages`, and the page `format` (`legacy` or `packed`) |
| `__VEC_INDEX_VALIDATE(index_name)` | Returns name/value pairs: `recall_at_10` of the ANN search against an exact scan, and whether the graph agrees with the stored embeddings — see [Index parameters](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/#step-2-measure-recall). Not health-gated (runs on a `needs_rebuild` index) |
| `__VEC_INDEX_REBUILD(index_name [, method [, threads]])` | Rebuilds the HNSW graph from the stored embeddings and clears `needs_rebuild`. `method` is `'replay'`, `'fast'`, or `'auto'` (default is the index's stored `rebuild` option); `threads` (fast only) overrides the worker-thread count. An invalid method raises `VEC81`. Returns the number of vectors in the rebuilt graph. See Maintenance: rebuild methods |
| `__VEC_INDEX_HEALTH_RECHECK(index_name)` | Re-evaluates index health; returns `1 = ok`, `2 = needs_rebuild` |
| `__VEC_INDEX_SEARCH(index_name, query_vec, k, ef_search)` | Direct HNSW search; returns a vector of `(row_id, distance)` pairs, nearest first |
| `__VEC_INDEX_ROW_DISTANCE(index_name, row_id, query_vec [, metric])` | Distance from one row's stored vector to a query vector. `metric`, if given, must be the index's (`VEC46`) |
| `__VEC_INDEX_ROW_SIMILARITY(index_name, row_id, query_vec [, metric])` | The same as a similarity score (`VEC63` for a different metric) |
| `__VEC_INDEX_QUERY_TEXT_VECTOR(index_name, text)` | Embeds text using the index's bound model; `VEC88` for a `source_kind = 'vector'` index |
| `__VEC_INDEX_QUERY_TEXT_VECTOR_CALLS(reset)` | Returns the count of query-text embeddings; a non-zero `reset` also clears it |
| `__VEC_INDEX_EMBED_AND_INSERT(index_name, row_id, text)` | Embeds text and inserts into HNSW graph |
| `__VEC_INDEX_INSERT_EMBEDDING(index_name, row_id, vector)` | Inserts a pre-computed embedding vector for one row |
| `__VEC_INDEX_INSERT_BATCH(index_name, row_ids, vectors [, texts])` | Inserts a batch of pre-computed embeddings; `texts`, one per row, records each row's source hash so an unchanged text is not embedded again. Returns the count |
| `__VEC_INDEX_STAGE_BATCH(index_name, row_ids, vectors [, texts])` | Stores a batch of embeddings without linking them into the graph; a later `__VEC_INDEX_REBUILD` derives the graph. Returns the count |
| `__VEC_INDEX_DELETE_ROW(index_name, row_id)` | Removes a row from the HNSW graph |
| `__VEC_INDEX_DELETE_EMBEDDING(index_name, row_id)` | Another name for `__VEC_INDEX_DELETE_ROW` |
| `__VEC_INDEX_DELETE_BATCH(index_name, row_ids)` | Removes a batch of rows from the HNSW graph; returns the count deleted |
| `__vvec_ann_plan(index_name, query_vec [, k [, ef_search]])` | A development entry point to the same search as `__VEC_INDEX_SEARCH`, with `k` defaulting to 10 and `ef_search` to `k` |
| `__VEC_SIMD_INFO()` | The distance kernels in use: `(family, cpu_avx2_fma, build_family)` — `family` is `'neon'`, `'avx2'` or `'scalar'`; see [Distance kernels](#distance-kernels) |
| `__VEC_SIMD_SELFTEST(dim [, family])` | Runs the six kernels of `family` (`'auto'`, the default, for the ones in use) on seeded vectors of `dim` floats (1–65536) against a double-precision oracle; returns `(family, worst, e1 … e6)`, each a relative error. `22023`/`VEC49` for a family this machine cannot run |
| `VVEC_TO_FLOAT_VECTOR(vector)` | Returns the vector as a flat `DV_ARRAY_OF_FLOAT`, the form the index stores; `VEC30` if the argument is not a vector. Callable by any user |

The inspection BIFs return name/value vectors, which `isql` prints as bare pointers. Render one with `obj2json`, or read one field with `get_keyword`. On the quickstart's `DB.DBA.DOCS` with three more rows (4 "Resetting a forgotten account password", 5 "Configuring the HTTP listener port", 6 "Backing up the database with checkpoints"), just after `CREATE VECTOR INDEX DOCS_VEC`:

SQL

```
SELECT obj2json (__VEC_INDEX_METRICS ('DOCS_VEC'));
-- ["dimension",384,"distance_metric","cosine","hnsw_m",16,"managed_rows",6,"graph_nodes",6,
--  "deleted_nodes",0,"insert_count",6,"search_count",0,"search_usec",0,"bytes_written",98304,
--  "layer0_hit_rate",1,"state","READY_FOR_INTERNAL_LOAD"]

SELECT get_keyword ('graph_nodes', __VEC_INDEX_METRICS ('DOCS_VEC'));
-- 6

SELECT obj2json (__VEC_INDEX_SEARCH ('DOCS_VEC',
         __VEC_INDEX_QUERY_TEXT_VECTOR ('DOCS_VEC', 'reset password'), 3, 50));
-- [[4,0.09655309468507767],[1,0.5204340815544128],[6,0.520555317401886]]
```

Important

`__VEC_*` functions are BIFs — call them **UNQUALIFIED** (no `DB.DBA.` prefix). Qualifying a BIF makes the server look for a stored procedure and fail with "Undefined procedure". All `__VEC_*` BIFs are DBA-only **except** `__VEC_INDEX_ROW_DISTANCE`, `__VEC_INDEX_ROW_SIMILARITY`, and `__VEC_INDEX_QUERY_TEXT_VECTOR`, which are available to all users.

Note

The `__VEC_INDEX_INSERT_*`, `__VEC_INDEX_STAGE_BATCH`, `__VEC_INDEX_DELETE_*`, and `__VEC_INDEX_EMBED_AND_INSERT` BIFs mutate the HNSW graph directly. In normal operation you never call them — `CREATE VECTOR INDEX` backfill, the maintenance queue, and `REFRESH`/rebuild drive the graph for you. They exist for diagnostics, custom loaders, and the engine's own regression tests. The engine also registers test-only helpers (`__VEC_INDEX_TEST_EMBEDDING`, `__VEC_INDEX_INSERT_TEST_EMBEDDING`, `__VEC_INDEX_SEARCH_TEST_EMBEDDING`) that are not part of the supported surface.

### Distance kernels

Every distance the index computes — in searches, in builds, and in `L1_DISTANCE`, `L2_DISTANCE` and `DOT_PRODUCT` — runs a float32 kernel of one of three families: `neon` on arm64; on x86-64, `avx2` (AVX2 + FMA) when the CPU and the operating system support it, chosen at start-up, and `scalar` otherwise. A build made with `-mavx2 -mfma` uses `avx2` unconditionally, and one made with a compiler other than GCC or Clang uses `scalar`. The server log names the family when the server starts:

Output

```
17:01:50 Vector index distance kernels: neon
```

`__VEC_SIMD_INFO ()` returns the same, with what the CPU supports and what the build chose at compile time; `__VEC_SIMD_SELFTEST` checks a family against a double-precision oracle. On an arm64 server:

SQL

```
SQL> SELECT sprintf ('%s, %d, %s', aref (v, 0), aref (v, 1), aref (v, 2))
       FROM (SELECT __VEC_SIMD_INFO () AS v) x;
neon, 0, neon
SQL> SELECT sprintf ('%s worst %.3e', aref (v, 0), aref (v, 1))
       FROM (SELECT __VEC_SIMD_SELFTEST (384, 'scalar') AS v) x;
scalar worst 1.228e-07
SQL> SELECT __VEC_SIMD_SELFTEST (8, 'avx2');
*** Error 22023: [Virtuoso Driver][Virtuoso Server]VEC49: __VEC_SIMD_SELFTEST: no distance kernels named 'avx2' ON this machine, which has auto, scalar, neon
```

The test suite requires a worst error below 1e-5 from every family, at every dimension from 1 to 1,025.

### DB.DBA.VEC_INDEX_EMBEDDINGS_TO_FLOAT

SQL

```
DB.DBA.VEC_INDEX_EMBEDDINGS_TO_FLOAT (
  IN _hidden_table VARCHAR,          -- the index's embeddings table, e.g. 'DB.DBA.DOCS_VEC_vec_embeddings'
  IN _log_mode INTEGER := 2,         -- log_enable mode for the conversion
  IN _report_every INTEGER := 10000  -- rows between progress lines; 0 for none
) returns INTEGER                    -- rows converted
```

Rewrites every stored embedding of an index that is an array of boxed numbers in the flat float form. The server writes embeddings in the flat form, which a rebuild loads with one copy per row, so a table needs this only if embeddings reached it in the boxed form by other means. It is re-runnable, logs progress to the server log, and commits once at the end. The default `_log_mode` of 2 writes no transaction log — checkpoint afterwards.

## Registry settings

Server-wide tuning, set with `registry_set (key, 'value')` and read on every use, so a change needs no restart. A key cleared with `registry_set (key, '')` means "use the default".

| Key | Default | Meaning |
| --- | --- | --- |
| `__vec_embed_concurrency` | 4 | embedding batches a refresh runs at once, 1–32; see Embedding concurrency |
| `__vec_embed_batch_size` | 32 | texts per model call, 1–4096; see Batch size |
| `__vec_progress_every` | 2000 | embedded rows between refresh progress lines; `'0'` silences them |
| `__vec_bulk_delta_pct` | 10 | largest change, as a percentage of a `build = 'bulk'` graph's live nodes, that a refresh links in rather than rebuilding the graph, 0–100; `'0'` always rebuilds |
| `__vec_fast_rebuild_max_bytes` | 2 GB | the fast builder's memory cap; above it `auto` rebuilds with `replay`. Wins over the `VVEC_FAST_REBUILD_MAX_BYTES` environment variable |
| `__vec_rebuild_threads` | online CPUs, at most 8 | worker threads for a fast rebuild without an explicit thread count, at most 256 |
| `__vvec_passthrough_column` | off | `'on'` allows `source_kind = 'vector'` indexes |
| `__vec_queue_suspended` | `'0'` | `'1'` while the SPARQL queue is suspended; set by `VEC_INDEX_QUEUE_SUSPEND` / `_RESUME` |

One setting lives in `virtuoso.ini` instead and is read at start-up:

| `[Parameters]` key | Default | Meaning |
| --- | --- | --- |
| `VectorANNCostBias` | 1.0 | multiplies the optimizer's cost estimate for a leading ANN search; below 1 favours ANN plans, above 1 filter/rerank plans. 0 or below, or unparsable, is taken as 1.0 — see [Index parameters](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/#vectoranncostbias-server-setting) |

---

## Catalog tables

### DB.DBA.ONNX_MODELS

`DB.DBA.ONNX_MODELS` is the embedding model registry. Every vector index binds to a row in this table by `model_name`. `SPARQL_SELECT` may read `model_id`, `model_name`, `model_type` and `handle`.

| Column | Type | Description |
| --- | --- | --- |
| `model_id` | `INTEGER` | Identity; what an index stores |
| `model_name` | `VARCHAR` | Unique model name |
| `description` | `VARCHAR` | Free text |
| `model_type` | `VARCHAR` | `'text_embedding'`, `'openai'`, `'ollama'`, `'lmstudio'`, or `'openai_compatible'`; `'unavailable'` when a model's files are missing |
| `model_path` | `VARCHAR` | Path to the ONNX model file (local) or remote model name (HTTP) |
| `input_names` | `VARCHAR` | Comma-separated input tensor names; empty means `input_ids`, `attention_mask` |
| `output_name` | `VARCHAR` | The output tensor read for the embedding |
| `output_shape` | `VARCHAR` | Output shape, e.g. `"1,384"` |
| `vocab_path` | `VARCHAR` | Tokenizer vocabulary (local) |
| `max_seq_len` | `INTEGER` | Longest input in tokens; longer text is truncated |
| `handle` | `INTEGER` | Loaded model handle (null for HTTP providers) |
| `intra_threads`, `inter_threads` | `INTEGER` | ONNX Runtime threads per helper; null means one |
| `provider_endpoint` | `VARCHAR` | HTTP endpoint URL (for HTTP providers) |
| `provider_api_key_name` | `VARCHAR` | Registry key name (for HTTP providers) |
| `provider_timeout` | `INTEGER` | HTTP timeout in seconds |
| `provider_dimensions` | `INTEGER` | Expected embedding dimension (for HTTP providers) |
| `provider_insecure` | `INTEGER` | The `_insecure` value given at registration |
| `provider_max_batch` | `INTEGER` | Inputs per request; null uses the provider's default |
| `provider_consecutive_failures`, `provider_last_error`, `provider_last_error_at` |  | The provider's recent health |
| `created_at`, `updated_at` | `DATETIME` |  |

### DB.DBA.SPARQL_VEC_INDEX

`DB.DBA.SPARQL_VEC_INDEX` records the metadata for each SPARQL vector index.

| Column | Type | Description |
| --- | --- | --- |
| `SVI_IRI` | `VARCHAR` | Index IRI |
| `SVI_INTERNAL_NAME` | `VARCHAR` | The native index's name (`VECIDX_…`), which the `__VEC_*` BIFs take |
| `SVI_SOURCE_TABLE` | `VARCHAR` | The backing table (`DB.DBA.VECSRC_…`) |
| `SVI_STATE` | `VARCHAR` | `'creating'`, `'active'`, `'error'`, or an operation in progress: `'refreshing'`, `'dropping'`, `'draining'` |
| `SVI_LAST_ERROR` | `LONG VARCHAR` | Why the index is in `'error'` |
| `SVI_SELECTOR_TYPE` | `VARCHAR` | `'shorthand'` or `'general'` |
| `SVI_SELECTOR_GRAPH` | `VARCHAR` | Graph IRI (shorthand selector) |
| `SVI_SELECTOR_PRED` | `VARCHAR` | Predicate IRI (shorthand selector) |
| `SVI_KEY_VAR`, `SVI_EMBEDDING_VAR`, `SVI_WHERE_TEXT` |  | The general selector's variables and pattern |
| `SVI_DATASET_TEXT` | `VARCHAR` | The general selector's `FROM` / `FROM NAMED` clauses as written |
| `SVI_MODEL_NAME` | `VARCHAR` | Bound model name |
| `SVI_DIMENSIONS` | `INTEGER` | Stored vector dimension (reduced dim if `SVI_REDUCE = 'truncate'`) |
| `SVI_REDUCE` | `VARCHAR` | Dimension reduction mode: `'none'` (default) or `'truncate'` (Matryoshka) |
| `SVI_MODEL_DIMENSIONS` | `INTEGER` | Model native output dimension; equals `SVI_DIMENSIONS` when not reduced |
| `SVI_DISTANCE` | `VARCHAR` | Distance metric |
| `SVI_HNSW_M`, `SVI_EF_CONSTRUCTION` | `INTEGER` | Graph parameters |
| `SVI_MAINTENANCE` | `VARCHAR` | `'manual'` or `'async'` |
| `SVI_BUILD`, `SVI_REBUILD` | `VARCHAR` | The `build` and `rebuild` options; null is `'auto'` |
| `SVI_SOURCE_KIND` | `VARCHAR` | `'text'`, or `'vector'` as given |
| `SVI_OWNER` | `VARCHAR` | The numeric id, as a string, of the account that created the index; `'0'` is `dba`. Compared against `get_user_id (1)` by `VEC_INDEX_SET_METADATA` |
| `SVI_LABEL` | `VARCHAR` | Optional short name, up to 255 characters; published as `rdfs:label` in `<urn:vvec:indexes>` |
| `SVI_COMMENT` | `VARCHAR` | Optional description, up to 2000 characters; published as `rdfs:comment` |
| `SVI_CREATED`, `SVI_REFRESHED` | `DATETIME` |  |
| `SVI_GENERATION` | `INTEGER` | Incremented by each completed refresh |

No grants are shipped on this table, so a non-DBA reader of `<urn:vvec:indexes>` gets `SQ033` until one is given — see Naming an index.

### DB.DBA.SPARQL_VEC_INDEX_TRIGGER

`DB.DBA.SPARQL_VEC_INDEX_TRIGGER` stores the `(graph, predicate)` dependency pairs extracted from the `WHERE` pattern of a general-selector vector index at parse time. It drives predicate-precise async maintenance: a change to a triple in `(graph, predicate)` enqueues the changed subject for matching indexes. The shorthand selector does not populate this table — it matches via `SVI_SELECTOR_GRAPH`/`SVI_SELECTOR_PRED` directly.

| Column | Type | Description |
| --- | --- | --- |
| `SVT_INDEX_IRI` | `VARCHAR` | Index IRI (FK to `SPARQL_VEC_INDEX.SVI_IRI`) |
| `SVT_GRAPH_IRI` | `VARCHAR` | Graph IRI of the indexed triple pattern |
| `SVT_PRED_IRI` | `VARCHAR` | Predicate IRI; `''` means graph-only fallback (match any predicate in `SVT_GRAPH_IRI`) |

Primary key: `(SVT_INDEX_IRI, SVT_GRAPH_IRI, SVT_PRED_IRI)`. Rows are removed by `DROP VECTOR INDEX`.

### DB.DBA.RDF_OBJ_VEC_INDEX

One row per [RDF literal index](#vector-search-over-rdf-literals).

| Column | Type | Description |
| --- | --- | --- |
| `RVI_NAME` | `VARCHAR` | The SQL key name, `RDF_OBJ_…` |
| `RVI_IRI` | `VARCHAR` | The name it was created under |
| `RVI_STATE` | `VARCHAR` | `'new'`, `'embedding'`, `'embedded'`, `'building'`, `'ready'` or `'error'` |
| `RVI_LAST_ERROR` | `LONG VARCHAR` | Why it is in `'error'` |
| `RVI_ROWS` | `BIGINT` | Literals embedded, as of the last create, embed or refresh (a log drain does not update it) |
| `RVI_MIN_LENGTH`, `RVI_LANGS`, `RVI_BUILD` |  | The `_CREATE` arguments of the same names |
| `RVI_OWNER`, `RVI_CREATED`, `RVI_REFRESHED` |  |  |

### Other tables

| Table | Holds |
| --- | --- |
| `DB.DBA.VEC_SQL_QUEUE` | Changes to SQL-indexed tables waiting to be applied: index, primary key, `upsert`/`delete`, state (`pending`, `error`) and error |
| `DB.DBA.VEC_SQL_WORKER_STATE` | The SQL worker's last run, count and error |
| `DB.DBA.SPARQL_VEC_QUEUE` | Subjects that `async` SPARQL indexes queued, with state (`pending`, `processing`, `error`), retries and error |
| `DB.DBA.SPARQL_VEC_WORKER` | The SPARQL worker's flag, batch size, idle delay and last run |
| `DB.DBA.VEC_INDEX_EPOCH` | Each index's durability epoch and health (`ok` or `needs_rebuild`) |
| `DB.DBA.RDF_OBJ_VEC_LOG` | Literals created since an RDF literal index was built |

---

## Next steps

- **[SQL vector index how-to](urn:osdi:sitevirtuoso/docs/vector-index/howto-sql-vector-index/)** — End-to-end guide for creating, querying, and maintaining a relational SQL vector index
- **[SPARQL vector index how-to](urn:osdi:sitevirtuoso/docs/vector-index/howto-sparql-vector-index/)** — End-to-end guide for RDF vector indexes with `bif:vector_search`, including the `ef_search` option and graph ACL security
- **[Vector search over RDF literals](urn:osdi:sitevirtuoso/docs/vector-index/knn-similar/)** — `knnSimilar` and the RDF literal index
- **Maintenance** — Queue-based index updates, workers, and operational guidance for keeping your index current
- **[Embedding models](urn:osdi:sitevirtuoso/docs/vector-index/embedding-models/)** — Model lifecycle, the `ONNX_MODELS` registry, local ONNX and remote HTTP providers, and choosing a model

## Related content

**Reference:**

- [Index parameters](urn:osdi:sitevirtuoso/docs/vector-index/index-parameters/) — HNSW build-time and query-time parameters that control the accuracy, memory, and latency trade-off
- [Similarity metrics](urn:osdi:sitevirtuoso/docs/vector-index/similarity-metrics/) — Cosine, L2, and L1 distance functions, score derivation, and how to choose the right metric

[PreviousTroubleshooting the Virtuoso vector index](urn:osdi:sitevirtuoso/docs/vector-index/troubleshooting/)

On this page

1. [SQL DDL](#sql-ddl)
2. [SQL query functions](#sql-query-functions)
3. [Vector math functions](#vector-math-functions)
4. [SPARQL DDL](#sparql-ddl)
5. [SPARQL query](#sparql-query)
6. [Vector search over RDF literals](#vector-search-over-rdf-literals)
7. [Embedding model management (SQL procedures)](#embedding-model-management-sql-procedures)
8. [Maintenance procedures (SQL)](#maintenance-procedures-sql)
9. [Maintenance procedures (SPARQL)](#maintenance-procedures-sparql)
10. [Internal BIFs (DBA-only, no DB.DBA. prefix)](#internal-bifs-dba-only-no-dbdba-prefix)
11. [Registry settings](#registry-settings)
12. [Catalog tables](#catalog-tables)
13. [Next steps](#next-steps)
14. [Related content](#related-content)
