valerianmemsk / laravel-semantic-search
Semantic & hybrid search with native vector embeddings for Laravel on MariaDB and MySQL
Package info
github.com/ValerianMemsk/laravel-mysql-semantic-search
pkg:composer/valerianmemsk/laravel-semantic-search
Requires
- php: ^8.2|^8.3|^8.4
- illuminate/contracts: ^12.0|^13.0
- illuminate/database: ^12.0|^13.0
- illuminate/http: ^12.0|^13.0
- illuminate/support: ^12.0|^13.0
Requires (Dev)
- laravel/scout: ^11.0|^12.0
- orchestra/testbench: ^10.0|^11.0
- phpunit/phpunit: ^10.0|^11.0|^12.0
Suggests
- laravel/scout: Required to use SemanticSearchEngine as a Scout driver (^11.0|^12.0).
Provides
None
Conflicts
None
Replaces
None
README
Native vector search for Laravel — no external vector database needed. Uses MariaDB 11.7+ or MySQL 9.0+
VECTORcolumns with Ollama, OpenAI, or any embedder you register.
Why this package
Adding vector search to Laravel usually means running a separate vector database (Pinecone, Milvus, Qdrant, Weaviate) or PostgreSQL with pgvector.
MariaDB 11.7+ and MySQL 9.0+ now have native VECTOR columns and distance functions (VEC_DISTANCE_COSINE, VECTOR_DISTANCE). This package uses those, so you get semantic search inside the database you already run, with no extra infrastructure. It can also combine semantic results with regular keyword search using Reciprocal Rank Fusion (RRF).
Features
- Hybrid search: merges semantic similarity with keyword search (Scout or SQL
LIKE) using RRF. - Native SQL vector storage on MariaDB 11.7+ or MySQL 9.0+.
- Pluggable embedders: Ollama and OpenAI built in, plus any other API or model (Hugging Face, Cohere, Voyage, TEI, ...) through a driver.
- Scout engine: set
SCOUT_DRIVER=semanticand it falls back to your normal driver when the embedder is unavailable. - Synonym and acronym expansion: a preprocessor that expands abbreviations and domain terms before embedding. The dictionary is swappable.
- Background ingestion: queued jobs on a model's
savedevent.
Requirements
| Requirement | Minimum version | Note |
|---|---|---|
| PHP | 8.2+ | |
| Laravel | 12.0 - 13.0 | |
| MariaDB or MySQL | MariaDB 11.7+ or MySQL 9.0+ | Required for the native VECTOR type |
| Embedder | Ollama, OpenAI, or a custom API | Ollama/OpenAI built in; anything else via a driver |
Quick start
Install
composer require valerianmemsk/laravel-semantic-search
Publish config and migrations
php artisan vendor:publish --tag="semantic-search-config" php artisan vendor:publish --tag="semantic-search-migrations" php artisan migrate
Configure environment
Every value below is optional: the package ships defaults in config/semantic-search.php,
so set only what you want to change.
# Vector database dialect: 'mariadb' or 'mysql' SEMANTIC_SEARCH_DB_DRIVER=mariadb # Embedder driver: 'ollama' or 'openai' SEMANTIC_SEARCH_DRIVER=ollama # Vector dimensions (1024 for bge-m3, 1536 for text-embedding-3-small) SEMANTIC_SEARCH_DIMENSIONS=1024 # Ollama settings (if using Ollama) OLLAMA_URL=http://localhost:11434 OLLAMA_EMBED_MODEL=bge-m3 # Ollama request timeout in seconds. Defaults to 120, which covers a cold bge-m3 load # (~15s on CPU) plus inference on a long document. Raise it for very large inputs, or # lower it if you would rather have failures surface sooner. # OLLAMA_TIMEOUT=120 # OpenAI settings (if using OpenAI) # OPENAI_API_KEY=sk-... # OPENAI_API_KEY_FILE=/run/secrets/openai_key # preferred outside local dev # OPENAI_EMBED_MODEL=text-embedding-3-small # Cosine distance threshold (0.0 = exact match, ~0.45 - 0.55 recommended) SEMANTIC_SEARCH_THRESHOLD=0.49
Handling API keys
A local Ollama needs no credentials — OLLAMA_URL is the whole configuration. This section
only matters when SEMANTIC_SEARCH_DRIVER=openai or when you register a remote embedder.
For local development OPENAI_API_KEY in .env is fine; .env is gitignored. It is a poor
fit for deployed environments, for three reasons:
php artisan config:cacheresolvesenv()while building the cache and writes the literal key intobootstrap/cache/config.php.- Environment variables can be read back with
docker inspect, from/proc/<pid>/environ, and from most orchestrator APIs. - A Dockerfile that does
COPY . .without a.dockerignorecopies.envinto an image layer.
Prefer a mounted secret file, and point the package at it:
OPENAI_API_KEY_FILE=/run/secrets/openai_key
# docker-compose.yml services: app: secrets: - openai_key environment: OPENAI_API_KEY_FILE: /run/secrets/openai_key secrets: openai_key: file: ./secrets/openai_key.txt
The file is read at request time and its contents are trimmed, so a trailing newline is
harmless. If OPENAI_API_KEY_FILE is set, it wins over OPENAI_API_KEY. If it is set but
the file is missing or empty, the package throws rather than falling back — a broken secret
mount should not be papered over with a stale credential.
For anything beyond a file — Vault, AWS Secrets Manager, an OS keychain — register your own
embedder through EmbedderManager::extend() as shown in section 5. There is deliberately no
separate key-resolver interface, since that would be a second way to do the same job.
How to use
1. Prepare your model
Add the HasEmbeddings trait and define which fields become the embedding:
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Laravel\Scout\Searchable; use ValerianMemsk\SemanticSearch\Traits\HasEmbeddings; class Article extends Model { use Searchable, HasEmbeddings; public function toSemanticSearchArray(): array { return [ 'title' => $this->title, 'summary' => $this->summary, 'content' => strip_tags($this->body), ]; } }
Saving the model pushes an embedding job to your queue.
2. Search via Scout
Set SCOUT_DRIVER=semantic in .env (or config/scout.php):
// config/scout.php 'driver' => env('SCOUT_DRIVER', 'semantic'), 'fallback_driver' => 'database',
Search as usual:
$articles = Article::search('how to optimize database queries')->get();
Behind the scenes it embeds the query, runs a cosine-distance query, runs a lexical search through the fallback driver, then fuses both with RRF.
3. Direct facade usage
use ValerianMemsk\SemanticSearch\Facades\SemanticSearch; use App\Models\Article; $semanticIds = SemanticSearch::searchIds(Article::class, 'machine learning basics', limit: 20); $keywordIds = Article::where('title', 'like', '%machine learning%')->pluck('id')->toArray(); $finalRankedIds = SemanticSearch::combineRRF($semanticIds ?? [], $keywordIds);
4. Bulk-generate embeddings
# All models using HasEmbeddings php artisan semantic-search:embed # A specific model php artisan semantic-search:embed "App\Models\Article"
5. Custom embedders
Ollama and OpenAI are built in, but any API or model works (Hugging Face Inference API, Text Embeddings Inference, Cohere, Voyage, a custom Python service, ...).
Implement ValerianMemsk\SemanticSearch\Contracts\EmbedderContract:
namespace App\Search\Embedders; use Illuminate\Support\Facades\Http; use ValerianMemsk\SemanticSearch\Contracts\EmbedderContract; class HuggingFaceEmbedder implements EmbedderContract { public function __construct( protected string $apiKey, protected string $model = 'BAAI/bge-m3', protected int $dimensions = 1024 ) {} public function embed(string $text): array { $response = Http::withToken($this->apiKey) ->post("https://api-inference.huggingface.co/pipeline/feature-extraction/{$this->model}", [ 'inputs' => $text, ]); return $response->json(); } public function dimensions(): int { return $this->dimensions; } }
Register it in AppServiceProvider::boot():
use ValerianMemsk\SemanticSearch\Embedders\EmbedderManager; use App\Search\Embedders\HuggingFaceEmbedder; public function boot(): void { $this->app->make('semantic-search.embedder-manager')->extend('huggingface', function ($app) { return new HuggingFaceEmbedder( apiKey: config('services.huggingface.key'), model: 'BAAI/bge-m3', dimensions: 1024 ); }); }
Then set SEMANTIC_SEARCH_DRIVER=huggingface in .env.
6. Custom synonym dictionary
Synonyms map a term to a replacement (for example ФЛ → физическое лицо) and are applied to query and document text before embedding. By default they come from the semantic_dictionaries table (published migration) through the SemanticDictionary model, cached in memory.
To use your own source, bind DictionarySourceContract:
use ValerianMemsk\SemanticSearch\Contracts\DictionarySourceContract; public function register(): void { $this->app->bind(DictionarySourceContract::class, function () { return new class implements DictionarySourceContract { public function terms(): iterable { return [ (object) ['term' => 'ФЛ', 'replacement' => 'физическое лицо'], (object) ['term' => 'CEO', 'replacement' => 'Chief Executive Officer'], ]; } }; }); }
terms() can return any iterable of objects with term and replacement properties.
Local Ollama quickstart (Docker)
To run a self-hosted embedding model without sending data to external APIs:
services: ollama: image: ollama/ollama:latest restart: unless-stopped ports: - "11434:11434" volumes: - ollama_data:/root/.ollama ollama-init: image: ollama/ollama:latest depends_on: - ollama environment: - OLLAMA_HOST=ollama:11434 entrypoint: - /bin/sh - -c - | until ollama list >/dev/null 2>&1; do sleep 1; done ollama pull bge-m3 volumes: ollama_data:
Running tests
composer test
No local PHP/Composer? Build the bundled test image and run it in Docker:
docker build -f Dockerfile.test -t semantic-search-test . docker run --rm -v "$PWD":/app semantic-search-test composer test
Contributing
This is the first Laravel package I've seriously developed, and it came out of a "can this even be done?" experiment rather than a considered "should it be done?" design. Criticism and contributions are welcome:
- Report bugs and edge cases in the issue tracker.
- Send PRs for new embedder drivers, performance work, or test coverage.
- Tell me how MariaDB/MySQL native vectors behave in real workloads.
License
MIT. See LICENSE.md.