laravel-manticore-sync maintained by renatomaldonado
Laravel Manticore Sync
Keep Manticore Search indexes in sync with your Eloquent models. Add one trait to a model
and every create, update, delete and restore reaches the index through a queued (or
synchronous) job, using the cheapest statement that leaves the document correct, so
editing a price or a tag never triggers a full REPLACE that regenerates an embedding.
It builds on renatomaldonado/laravel-manticore-eloquent,
the driver that exposes Manticore as a Laravel database connection; that driver is how the
package talks to Manticore, and how you query the index afterwards (Model::manticore()).
Why not just REPLACE everything?
Manticore's UPDATE is in-place and fast, but cannot change full-text or columnar fields.
REPLACE can change anything, but rewrites the whole document, and on a table with an
auto-embedding (MODEL_NAME / FROM) a full REPLACE that omits the vector column
regenerates it: a model inference per write. This package looks at what actually changed
and the schema of the index, and picks the operation per document.
Requirements
| Dependency | Version |
|---|---|
| PHP | ^8.1 (with pdo_mysql) |
| Laravel | ^10.0 | ^11.0 | ^12.0 | ^13.0 |
renatomaldonado/laravel-manticore-eloquent |
^4.1 |
| Manticore Search | MySQL protocol enabled; Buddy for partial REPLACE (see below) |
Installation
composer require renatomaldonado/laravel-manticore-sync
php artisan vendor:publish --provider="ManticoreSync\ManticoreSyncServiceProvider" --tag=config
Configure the Manticore connection as described in the driver's README
(config/manticore-eloquent.php: host, port 9306, ...). The index must already exist;
this package writes documents, it does not create tables.
Usage
Add the SyncsToManticore trait. By default the index is the model's table and the document
is every attribute except the primary key.
use Illuminate\Database\Eloquent\Model;
use ManticoreEloquent\Concerns\HasManticore;
use ManticoreSync\Concerns\SyncsToManticore;
class Post extends Model
{
use SyncsToManticore;
use HasManticore; // optional: Post::manticore() queries the index
}
$post = Post::create(['title' => 'Hello', 'body' => '...']); // REPLACE (whole document)
$post->update(['price' => 20]); // UPDATE (in place)
$post->update(['body' => 'New body']); // partial REPLACE
$post->delete(); // DELETE
Post::manticore()->match('hello')->get();
Soft deletes are followed: delete() removes the document, restore() writes it back, and
forceDelete() removes it.
Overridable methods
| Method | Default | Purpose |
|---|---|---|
searchableAs() |
getTable() |
Index name (same convention as HasManticore). |
toManticoreDocument() |
attributesToArray() without the primary key |
The document sent to the index. |
manticoreKey() |
getKey() |
The Manticore document id: a positive integer, or a UUID for an index declared with id uuid (see UUID keys). Anything else throws InvalidManticoreKey, which tells you to override it. |
shouldSyncToManticore() |
true |
When it returns false on save, the document is removed. |
manticoreVectors() |
[] |
Vectors computed by the app (see Embeddings). |
Fields in the document that the index does not have are ignored (logged at debug level).
public function toManticoreDocument(): array
{
return [
'title' => $this->title,
'body' => $this->body,
'price' => $this->price,
];
}
public function shouldSyncToManticore(): bool
{
return $this->published_at !== null;
}
Manual control
$post->syncToManticore(); // write this model now (or queue it)
$post->removeFromManticore(); // remove its document
Post::withoutSyncingToManticore(function () {
Post::create([...]); // not indexed
});
Configuration
config/manticore-sync.php:
| Key | Env | Default | Meaning |
|---|---|---|---|
enabled |
MANTICORE_SYNC_ENABLED |
true |
Master switch for the observer. Explicit calls like syncToManticore() are not affected. |
queue |
MANTICORE_SYNC_QUEUE |
false |
false syncs inside the request; a string is the queue connection the jobs go to. |
queue_name |
MANTICORE_SYNC_QUEUE_NAME |
null |
Queue on that connection. |
chunk |
500 |
Batch size of bulk operations (import, builder macros). | |
after_commit |
true |
Wait for the surrounding transaction to commit; nothing is sent if it rolls back. | |
partial_replace |
MANTICORE_SYNC_PARTIAL_REPLACE |
'auto' |
'auto' detects Buddy with SHOW VERSION; true always tries it; false never uses it. |
reuse_vectors |
true |
When a full REPLACE is unavoidable, resend the vector already stored in Manticore instead of regenerating it. |
How a write is chosen
The observer records which document fields changed, and the writer reads the index schema
(DESC and SHOW CREATE TABLE) once to classify every column: full-text, row-wise
attribute, columnar attribute, or vector. For each document it picks, cheapest first:
| Situation | Statement |
|---|---|
| New model, restored model, or the document is missing from the index | REPLACE (whole document) |
| Only row-wise attributes changed (int, float, bool, timestamp, multi, json, ...) | UPDATE with just those fields |
| A full-text or columnar field changed, no embedding source changed | partial REPLACE with just those fields |
An embedding source changed, embedding done by Manticore (MODEL_NAME) |
REPLACE without the vector column, so Manticore regenerates it |
| An embedding source changed, embedding done by your app | vector computed once, partial REPLACE with the new vector |
| Partial REPLACE unavailable (no Buddy, a non-stored field, or a UUID id) | REPLACE resending the vector read back from the index |
Before writing a change, one SELECT id FROM index WHERE id IN (...) checks which documents
exist: a partial REPLACE on a missing id would create a half-empty document, and an UPDATE
on a missing id silently does nothing, so a missing document is written whole instead.
If a partial REPLACE fails, the writer logs a warning, remembers that it failed, and falls
back to the full REPLACE.
UPDATE and full REPLACE are batched per index. A partial REPLACE is one statement per
document, because Manticore filters it by id only.
What this is based on
Measured against Manticore 29.9.0 (Buddy v4.4.3) with a table created with
MODEL_NAME='sentence-transformers/all-MiniLM-L6-v2' FROM='title,body', starting from a
document with a recognisable explicit vector. These are the facts the strategy relies on, and
tests/Integration/ManticoreBehaviourTest.php re-checks every one of them against a live
server:
| Operation | Vector |
|---|---|
UPDATE of an attribute |
kept |
partial REPLACE of a full-text field outside FROM |
kept |
| partial REPLACE of an attribute | kept |
partial REPLACE of a field in FROM |
kept, so the embedding is now stale |
full REPLACE with an explicit vector |
kept (nothing is generated) |
full REPLACE without the vector column |
regenerated |
partial REPLACE with an explicit emb=(...) |
the vector you passed |
Other behaviour of Manticore that shaped the design:
UPDATEof a full-text field fails (can not be updated (full-text field)), and so doesUPDATEof a columnar attribute. A partial REPLACE changes both.- A partial REPLACE on a table with a non-stored field fails
(
Field title doesn't have stored property). - A partial REPLACE on an id that does not exist creates a document holding only the fields
passed, and reports nothing.
UPDATEon a missing id does nothing, also silently. DESCdoes not showMODEL_NAME/FROM;SHOW CREATE TABLEdoes.
UUID keys
A model with UUID keys (Laravel's HasUuids) can keep the same id in Manticore, on
Manticore 28.6.6 or later and an index created with a UUID id, as the
driver documents:
CREATE TABLE posts (id uuid, title text, body text, price int);
manticoreKey() returns the UUID in lowercase, the form Manticore reads it back in. The nil
UUID and UUIDs outside versions 1 to 8 are rejected, as Manticore rejects them. UPDATE,
full REPLACE and DELETE work as with integer ids, but Buddy's partial REPLACE only takes
numeric ids (REPLACE ... SET ... WHERE id = '<uuid>' is a syntax error on 28.6.6 and 29.9.0),
so a text change on a UUID document is a full REPLACE resending the stored vector.
Embeddings
Generated by Manticore (MODEL_NAME)
Declare the vector with MODEL_NAME and FROM in the table and do nothing in the model:
CREATE TABLE posts (
title text, body text, tag text, price int,
emb float_vector knn_type='hnsw' hnsw_similarity='L2'
model_name='sentence-transformers/all-MiniLM-L6-v2' from='title,body'
);
The package reads MODEL_NAME / FROM from the index. Changing title or body sends a
REPLACE without emb, and Manticore regenerates it. Changing price or tag never does.
Computed by your app (OpenAI, a local model, ...)
Return the vectors from manticoreVectors(). The closure runs only when one of its sources
changed (or on create), once per sync:
public function manticoreVectors(): array
{
return [
'embedding' => [
'sources' => ['title', 'body'],
'using' => fn () => app(Embedder::class)->embed($this->title . "\n" . $this->body),
],
];
}
Requirements of the cheap paths
Partial REPLACE needs Manticore Buddy and every field of the table stored. Buddy ships
inside the manticore package from 25.0.0 on; before that it was the separate
manticore-extra package. With partial_replace set to auto, the package runs
SHOW VERSION and looks for a Buddy row. Without Buddy, or on a table with a non-stored
field, the writer uses the full REPLACE that resends the current vector (the last row of the
table above).
Gotchas
- Vectors re-sent from the index come back with Manticore's 6-decimal precision. In the full-REPLACE fallback (no Buddy) the stored vector is read back as text and written again, so its floats are rounded to six decimals. A vector Manticore generated is not bit-identical after such a round trip. The difference is below 1e-5 per component, and the same was measured after a partial REPLACE that never touched the vector.
- Manticore rejects
NULLin writes. A null or missing value is written as the empty value of the column:''for text,0for numbers,()for multi-value and vector columns. - Numbers are written unquoted. Manticore's
UPDATEsilently ignores a quoted number for a numeric column, so the package inlines them. - With timestamps on, the default
toManticoreDocument()includesupdated_at, so most updates carry it. It is a cheap attributeUPDATE, but if you do not need the column in the index, overridetoManticoreDocument()to send only what the index needs. withoutSyncingToManticore()mutes the exact class only, not its subclasses.- A save with no changes dispatches nothing, even if
shouldSyncToManticore()would now returnfalse. A predicate that depends on external state takes effect on the next real change of the model. - Changes that bypass model events are not synced: mass
update()/delete()on a query,DB::statement, and other systems writing to the database. See below.
Bulk sync and writes that bypass events
Eloquent only fires events for models it loads and saves one at a time. For everything else:
php artisan manticore:import "App\Models\Post" # sync every row, in chunks
php artisan manticore:import "App\Models\Post" --chunk=1000
php artisan manticore:import "App\Models\Post" --fresh # TRUNCATE the index first
The command checks that the model uses SyncsToManticore, reads it with chunkById (chunk
size from --chunk, or manticore-sync.chunk), writes through the same writer
synchronously and reports Imported N records. A model with SoftDeletes imports only the
non-deleted rows, and rows for which shouldSyncToManticore() is false are skipped.
The same operations are available on the Eloquent builder, to resync or clean up after a mass change:
Post::where('tenant_id', 5)->syncToManticore(); // optional chunk: ->syncToManticore(1000)
Post::where('tenant_id', 5)->removeFromManticore();
They throw if the model does not use the trait, and go through the queue when queue is
configured.
For full coverage of external writers (other applications, SQL scripts, migrations), keep the database as the source of truth and stream its changes instead: change data capture with Debezium into Kafka, and Manticore's Kafka source to ingest them. That is outside this package.
Queues
With queue set to a connection name, sync and remove jobs are dispatched to it (optionally
to queue_name), after the transaction commits when after_commit is on. The jobs carry the
list of changed fields, so the queued worker picks the same cheap statement the request
would have.
Testing
composer test # everything; integration tests need Manticore on 127.0.0.1:9306
composer test:unit
composer test:integration
composer test:coverage-min # fails below 95%
CI runs the integration tests against Manticore 28.6.6 (the oldest with UUID ids), 29.9.0 (where the
measurements above were taken) and the latest release. Integration tests create t5_* / t7_* tables, drop them afterwards, and skip themselves
when Manticore is not reachable or, for the auto-embedding ones, has no Embeddings
component.
License
MIT