Search by

atwx / silverstripe-vector-search

adiwidjaja

Adds support for vector embeddings to your MariaDB 11.8+ database.

Package info

github.com/atwx/silverstripe-vector-search

Type:silverstripe-vendormodule

pkg:composer/atwx/silverstripe-vector-search

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

dev-main 2026-11-01 23:13 UTC

This package is auto-updated.

Last update: 2026-11-23 17:14:58 UTC


README

CI

Vector embeddings and similarity search for the Silverstripe ORM, using MariaDB's native VECTOR type.

Silverstripe Vector Search adds a Vector field type, turns text into embeddings through a pluggable provider (any OpenAI-compatible API by default), and orders DataList by vector distance. It is a good fit for semantic search, "related content", and retrieval for RAG setups.

Requirements

  • PHP 8.4
  • Silverstripe Framework 6
  • MariaDB 11.8 or newer (the first release with VEC_DISTANCE())
  • An API key for an OpenAI-compatible embeddings API — OpenAI, OpenRouter, Requesty, Azure OpenAI, a local Ollama/LM Studio server — or your own embeddings provider (see Using a different embeddings provider)

Installation

composer require atwx/silverstripe-vector-search

Add your API key to .env:

OPENAI_API_KEY="sk-..."

The default endpoint is OpenAI's. To use a different service, see Configuration.

Usage

1. Add a vector field

use Atwx\VectorSearch\ORM\Func\SupportsVFuncs;
use SilverStripe\ORM\DataObject;

class Document extends DataObject
{
    use SupportsVFuncs;

    private static string $table_name = 'Document';

    private static array $db = [
        'Content' => 'Text',
        'Embedding' => 'Vector',
    ];
}

A vector field asks for its own vector index, so it needs no entry in $indexes. Adding one replaces the vector index with a plain index, and VEC_DISTANCE() then fails with index is not found.

The field takes a distance and a size, in that order: 'Vector("cosine", 768)'. Both are optional — the distance defaults to euclidean, and the size to the dimensions of the configured embeddings provider (1536). Pass the size whenever your model produces a different one:

Spec Distance Size
'Vector' euclidean provider's dimensions
'Vector("cosine")' cosine provider's dimensions
'Vector("cosine", 768)' cosine 768

Run sake db:build --flush to create the column and index.

2. Store an embedding

use Atwx\VectorSearch\ORM\Func\VectorFrom;

$doc = Document::create();
$doc->Content = $text;
$doc->Embedding = VectorFrom::single($text);
$doc->write();

The column is NOT NULL, so every record needs an embedding before it is written.

To embed many texts with one API call, use VectorFrom::batch(). It returns one VectorFrom per input, in the same order:

$vectors = VectorFrom::batch($texts);

foreach ($texts as $i => $text) {
    $doc = Document::create();
    $doc->Content = $text;
    $doc->Embedding = $vectors[$i];
    $doc->write();
}

3. Search by similarity

use Atwx\VectorSearch\ORM\Helpers\VSearch;

$results = VSearch::sortByDistance(Document::get(), 'Embedding', $userInput)->limit(5);

foreach ($results as $doc) {
    echo $doc->embedding_distance; // lower is more similar
}

sortByDistance() embeds the search text, adds the distance to each row as embedding_distance, and sorts ascending. Pass a sort direction and an annotation name as the 4th and 5th arguments to change either.

Custom distance queries

VSearch::annotateQuery() adds any SQL function expression to the query as a named field. The distance functions live in Atwx\VectorSearch\ORM\Func\Distance:

Class SQL function
VecDistance VEC_DISTANCE (uses the metric stored on the column's index)
VecDistanceCosine VEC_DISTANCE_COSINE
VecDistanceEuclidean VEC_DISTANCE_EUCLIDEAN

These classes are abstract: the Injector binds each to the backend for the current database, so build them with ::create() rather than new.

use Atwx\VectorSearch\ORM\Func\Column;
use Atwx\VectorSearch\ORM\Func\Distance\VecDistanceEuclidean;
use Atwx\VectorSearch\ORM\Func\VectorFrom;
use Atwx\VectorSearch\ORM\Helpers\VSearch;

$list = VSearch::annotateQuery(
    Document::get(),
    'distance',
    VecDistanceEuclidean::create(Column::create('Embedding'), VectorFrom::single($userInput))
)->sort('distance', 'ASC');

Column::create() escapes its argument as a column name. A plain string argument is sent as a bound parameter instead, so use Column for column references.

Configuration

The default provider calls any OpenAI-compatible /embeddings endpoint through openai-php/client. Defaults ship in _config/embeddings.yml; override them in your project's config:

Atwx\VectorSearch\Embedding\OpenAIEmbeddingsProvider:
  model: 'text-embedding-3-small'
  dimensions: 1536
Option Default Purpose
base_uri https://api.openai.com/v1 Base URI of the API, including the version segment. /embeddings is appended. A URI without a scheme is treated as https.
api_key_env OPENAI_API_KEY Name of the .env variable holding the API key. The key itself is never read from YAML.
model text-embedding-3-small Model identifier, in whatever form the service expects.
dimensions 1536 Expected output size. Also the default size of Vector columns.
send_dimensions false Send dimensions as a request parameter to shorten the vectors. Only some models support it; others reject the request.
validate_dimensions true Throw if the API returns a different vector size, instead of letting MariaDB reject the write with a less obvious error.
batch_size 0 Largest number of texts per request; 0 sends them all in one call. Set it when your provider caps the batch size.
organization null Sent as OpenAI-Organization. OpenAI only.
project null Sent as OpenAI-Project. OpenAI only.
http_headers [] Extra HTTP headers, e.g. OpenRouter's attribution headers.
query_params [] Extra query string parameters, e.g. Azure OpenAI's api-version.
extra_parameters [] Extra parameters merged into the request body, e.g. encoding_format. model and input always win over these.
timeout 30 Request timeout in seconds.
connect_timeout 10 Connection timeout in seconds.

If you switch to a model with a different output size, update dimensions and the Vector(<size>) field to match. MariaDB will reject vectors whose length doesn't match the column.

Examples

OpenRouter

Atwx\VectorSearch\Embedding\OpenAIEmbeddingsProvider:
  base_uri: 'https://openrouter.ai/api/v1'
  api_key_env: 'OPENROUTER_API_KEY'
  model: 'openai/text-embedding-3-small'
  dimensions: 1536
  http_headers:
    HTTP-Referer: 'https://example.com'
    X-Title: 'My Site'

Requesty

Atwx\VectorSearch\Embedding\OpenAIEmbeddingsProvider:
  base_uri: 'https://router.requesty.ai/v1'
  api_key_env: 'REQUESTY_API_KEY'
  model: 'openai/text-embedding-3-small'
  dimensions: 1536

Azure OpenAI

Atwx\VectorSearch\Embedding\OpenAIEmbeddingsProvider:
  base_uri: 'https://my-resource.openai.azure.com/openai/deployments/my-embedding-deployment'
  api_key_env: 'AZURE_OPENAI_API_KEY'
  model: 'text-embedding-3-small'
  dimensions: 1536
  query_params:
    api-version: '2024-02-01'

Ollama, running locally

Atwx\VectorSearch\Embedding\OpenAIEmbeddingsProvider:
  base_uri: 'http://localhost:11434/v1'
  api_key_env: 'OLLAMA_API_KEY'   # any non-empty value; Ollama ignores it
  model: 'nomic-embed-text'
  dimensions: 768
  batch_size: 1

Using a different embeddings provider

Implement Atwx\VectorSearch\Embedding\EmbeddingsProvider and bind it with the Injector:

use Atwx\VectorSearch\Embedding\EmbeddingsProvider;

class LocalEmbeddingsProvider implements EmbeddingsProvider
{
    public function embed(string $text): array
    {
        return $this->embedBatch([$text])[0];
    }

    public function embedBatch(array $texts): array
    {
        // Return one float[] per input text, in the same order.
    }

    public function getDimensions(): int
    {
        // The size of the vectors this provider returns.
        return 768;
    }
}
SilverStripe\Core\Injector\Injector:
  Atwx\VectorSearch\Embedding\EmbeddingsProvider:
    class: App\Embedding\LocalEmbeddingsProvider

Tests

composer install
SS_DATABASE_CLASS=MySQLDatabase SS_DATABASE_SERVER=127.0.0.1 \
SS_DATABASE_USERNAME=root SS_DATABASE_PASSWORD=root \
SS_DATABASE_NAME=ss_vector_search vendor/bin/phpunit

The suite runs against a real MariaDB server and never calls an embeddings API. See tests/README.md for the details, including how to run the CI workflow locally with act.

Supported databases

Only MariaDB is supported at the moment. To support another database, add SQL function wrappers under Atwx\VectorSearch\ORM\Func\Backend (subclasses of Func) that map to that database's vector functions, and bind them to the abstract classes in Atwx\VectorSearch\ORM\Func with the Injector.

Example project

silverstripe-embed-demo imports the Silverstripe developer docs and answers questions about them with vector search.

Contributors

Sebi Apilonius64
Sebi Apilonius64

See also silverstripe-vector-showcase.