-
Type:
New Feature
-
Resolution: Fixed
-
Priority:
Major - P3
-
Affects Version/s: None
-
Component/s: Laravel
-
None
In Laravel, the Schema Facade and Schema\Builder class are used to manipulate the database schema (create/drop table, add/remove/rename column, add/remove index).
Proposed syntax to add a search index to a collection uses the same signature as createSearchIndex command (from the doc)
use MongoDB\Laravel\Schema\Blueprint; Schema::table('locations', function (Blueprint $table) { $table->searchIndex( /* The index definition requires a mapping * See: https://www.mongodb.com/docs/atlas/atlas-search/define-field-mappings/ */ definition: ['mapping' => ['dynamic' => true]]], // "default" is the default index name, this config can be omitted. name: 'default', ); });
Another method is added for vector search. Having 2 distinct methods allows us to remove the “type” parameter and specify the array shape type for $definition.
use MongoDB\Laravel\Schema\Blueprint; Schema::table('locations', function (Blueprint $table) { $table->vectorSearchIndex( definition: ['fields' => ['type' => 'vector', 'numDimensions' => 1536, 'path' => 'plot_embedding', 'similarity' => 'euclidean']], // "default" is be the default name, this config can be omitted name: 'default' ); });
Method signature. The array shape will be defined from Search Index Definition Syntax and Vector Search Index Definition Syntax
/** * @param array{ * analyzer: string, * searchAnalyzer: string, * mappings: array{ * dynamic: bool, * fields: list<string, array{ * type: string, * analyzer?: string, * searchAnalyzer?: string * }> * }, * analyzers: string[], * storedSource: bool|array<string, mixed>, * synonyms: array<array{ * name: string, * source: array{collection: string}, * analyzer: string * }> * } $definition * @param non-empty-string $name Name of the search index to create. */ function searchIndex(array $definition, string $name = 'default'): void /** * @param array{ * fields: list<array{ * type: 'vector'|'filter', * path: string, * numDimensions: int, * similarity: 'euclidean'|'cosine'|'dotProduct' * }> * } $definition * @param non-empty-string $name Name of the vector search index to create. */ function vectorSearchIndex(array $definition, string $name = 'default'): void
Behavior
- If search indexes are not supported by the cluster, this operation will fail with the server error because using this method is intentional. The message from the server is clear enough to let the user understand that they need an Atlas cluster to use search indexes.
- If the search index already exists, we updated its definition.