### Basic Setup Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example showing the basic setup by calling registerTypes and enabling the pgvector extension. ```php use Doctrine\ORM\EntityManager; use Pgvector\Doctrine\PgvectorSetup; // Assuming $entityManager is configured PgvectorSetup::registerTypes($entityManager); // Enable pgvector extension $entityManager->getConnection()->executeStatement('CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Running an Example Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Steps to set up and run a loading example, including dependency installation and database creation. ```sh cd examples/loading composer install createdb pgvector_example php example.php ``` -------------------------------- ### Example Usage of registerTypes Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example demonstrating how to call the registerTypes method during application setup. ```php use Pgvector\Doctrine\PgvectorSetup; // Call once during application setup PgvectorSetup::registerTypes($entityManager); ``` -------------------------------- ### Development Setup and Testing Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Instructions for cloning the repository, installing dependencies, setting up the test database, and running tests. ```sh git clone https://github.com/pgvector/pgvector-php.git cd pgvector-php composer install createdb pgvector_php_test composer test ``` -------------------------------- ### Complete Doctrine Setup and Usage Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md This snippet demonstrates how to register pgvector types with Doctrine, create the necessary PostgreSQL extension, define an entity with a vector column, and perform a query using a distance function. ```php use Doctrine\ORM\EntityManager; use Doctrine\ORM\Mapping as ORM; use Pgvector\Doctrine\PgvectorSetup; use Pgvector\Vector; // Setup PgvectorSetup::registerTypes($entityManager); $entityManager->getConnection()->executeStatement('CREATE EXTENSION IF NOT EXISTS vector'); // Entity #[ORM\Entity] class Article { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column(type: 'integer')] private int $id; #[ORM\Column(type: 'string')] private string $title; #[ORM\Column(type: 'vector', length: 1536)] private Vector $embedding; // Getters and setters } // Usage $embedding = new Vector([1.0, 2.0, 3.0, /* ... */]); $query = $entityManager->createQuery( 'SELECT a FROM App\Entity\Article a ORDER BY l2_distance(a.embedding, ?1)' ) ->setParameter(1, $embedding) ->setMaxResults(10); $results = $query->getResult(); ``` -------------------------------- ### Constructor Examples Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/halfvector.md Examples of creating a HalfVector instance from different data types. ```php use Pgvector\HalfVector; $vector = new HalfVector([1, 2, 3]); ``` ```php $vector = new HalfVector('[1.5, 2.5, 3.5]'); ``` ```php $arr = new SplFixedArray(3); $arr[0] = 1.1; $arr[1] = 2.2; $arr[2] = 3.3; $vector = new HalfVector($arr); ``` -------------------------------- ### values Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example usage of the values method. ```php $vector = new SparseVector([1, 0, 2, 0, 3]); $values = $vector->values(); // $values === [1, 2, 3] ``` -------------------------------- ### indices Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example usage of the indices method. ```php $vector = new SparseVector([1, 0, 2, 0, 3]); $indices = $vector->indices(); // $indices === [0, 2, 4] ``` -------------------------------- ### Laravel Full Setup Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Complete setup instructions for integrating pgvector with Laravel, including service provider registration, schema setup, and model configuration. ```php // config/app.php - Service providers 'providers' => [ // ... other providers Pgvector\Laravel\PgvectorServiceProvider::class, ], // app/Providers/AppServiceProvider.php use Pgvector\Laravel\Schema; class AppServiceProvider extends ServiceProvider { public function boot(): void { Schema::register(); } } // database/migrations/2024_01_01_000000_create_vector_extension.php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\DB; return new class extends Migration { public function up(): void { DB::statement('CREATE EXTENSION IF NOT EXISTS vector'); } }; // database/migrations/2024_01_01_000001_create_documents_table.php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('documents', function (Blueprint $table) { $table->id(); $table->string('title'); $table->vector('embedding', 1536); $table->timestamps(); $table->raw('CREATE INDEX ON documents USING hnsw (embedding vector_l2_ops)'); }); } }; // app/Models/Document.php use Pgvector\Laravel\Vector; use Pgvector\Laravel\HasNeighbors; class Document extends Model { use HasNeighbors; protected $casts = [ 'embedding' => Vector::class, ]; } ``` -------------------------------- ### dimensions Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example usage of the dimensions method. ```php $vector = new SparseVector([1, 0, 2, 0, 3], 5); echo $vector->dimensions(); // 5 ``` -------------------------------- ### Installation Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Command to install the pgvector-php package using Composer. ```bash composer require pgvector/pgvector ``` -------------------------------- ### __toString Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example usage of the __toString magic method, including database insertion. ```php $vector = new SparseVector([1, 0, 2, 0, 3], 5); echo $vector; // outputs: {1:1,3:2,5:3}/5 // Useful for database insertion pg_query_params($db, 'INSERT INTO items (embedding) VALUES ($1)', [$vector]); ``` -------------------------------- ### toArray Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example usage of the toArray method. ```php $vector = new SparseVector([0 => 1, 2 => 2, 4 => 3], 6); $arr = $vector->toArray(); // $arr === [1, 0, 2, 0, 3, 0] ``` -------------------------------- ### Bit Column Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Example of adding a bit string column for binary vectors. ```php Schema::create('items', function (Blueprint $table) { $table->id(); $table->bit('binary_vector', 256); // 256-bit binary vector $table->timestamps(); }); ``` -------------------------------- ### Complete Migration Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Example of a Laravel migration file demonstrating the creation of a table with various pgvector column types and indexes. ```php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up(): void { Schema::create('embeddings', function (Blueprint $table) { $table->id(); $table->string('text', 1000); $table->vector('embedding', 1536); // OpenAI embeddings $table->halfvec('lite_embedding', 384); $table->bit('binary_hash', 256); $table->sparsevec('sparse_embedding', 10000); $table->timestamps(); // Add indexes for vector search $table->raw('CREATE INDEX embedding_idx ON embeddings USING hnsw (embedding vector_l2_ops)'); $table->raw('CREATE INDEX sparse_idx ON embeddings USING hnsw (sparse_embedding vector_l2_ops)'); }); } public function down(): void { Schema::dropIfExists('embeddings'); } }; ``` -------------------------------- ### __toString Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/halfvector.md Example of converting a HalfVector to a JSON string. ```php $vector = new HalfVector([1.1, 2.2, 3.3]); echo $vector; // outputs: [1.1,2.2,3.3] ``` -------------------------------- ### Sparsevec Column Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Example of adding a sparse vector column. ```php Schema::create('items', function (Blueprint $table) { $table->id(); $table->sparsevec('embedding', 10000); // 10k-dimensional sparse vector $table->timestamps(); }); ``` -------------------------------- ### toArray Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/halfvector.md Example of converting a HalfVector to a PHP array. ```php $vector = new HalfVector([1, 2, 3]); $arr = $vector->toArray(); // $arr === [1, 2, 3] ``` -------------------------------- ### Example with Index Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Example of creating a HNSW index for faster L2 similarity searches and then performing a query that utilizes it. ```php // Create index for faster L2 searches $entityManager->getConnection()->executeStatement( 'CREATE INDEX embedding_idx ON embeddings USING hnsw (embedding vector_l2_ops)' ); // Query will now use the index $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY l2_distance(e.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(10); ``` -------------------------------- ### Halfvec Column Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Example of adding a half-precision vector column. ```php Schema::create('items', function (Blueprint $table) { $table->id(); $table->halfvec('embedding', 768); $table->timestamps(); }); ``` -------------------------------- ### Database Errors (PostgreSQL) - Extension Not Installed Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Laravel migration and Doctrine example for creating the pgvector extension in a PostgreSQL database. ```php // Laravel migration use Illuminate\Database\Migrations\Migration; return new class extends Migration { public function up() { DB::statement('CREATE EXTENSION IF NOT EXISTS vector'); } }; // Doctrine $entityManager->getConnection()->executeStatement( 'CREATE EXTENSION IF NOT EXISTS vector' ); ``` -------------------------------- ### Laravel Eloquent Cast Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/types.md Example of how to use the Vector castable in a Laravel model. ```php protected $casts = ['embedding' => Vector::class]; ``` -------------------------------- ### Laravel Integration Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/halfvector.md Example of using the Laravel castable version for model attribute casting. ```php use Pgvector\Laravel\HalfVector; class Item extends Model { protected $casts = ['embedding' => HalfVector::class]; } $item = new Item(); $item->embedding = [1, 2, 3]; $item->save(); ``` -------------------------------- ### Doctrine Integration Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/halfvector.md Example of registering HalfVector types with Doctrine ORM and using it in entity mappings. ```php use Pgvector\Doctrine\PgvectorSetup; use Pgvector\HalfVector; // Register types PgvectorSetup::registerTypes($entityManager); // In entity class #[ORM\Column(type: 'halfvec', length: 3)] private HalfVector $embedding; ``` -------------------------------- ### Using Cosine and Inner Product Distance Metrics Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Examples demonstrating how to use cosine_distance and max_inner_product functions in DQL queries. ```php // Cosine distance $query = $entityManager->createQuery( 'SELECT d FROM App\Entity\Document d ORDER BY cosine_distance(d.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(5); // Inner product $query = $entityManager->createQuery( 'SELECT d FROM App\Entity\Document d ORDER BY max_inner_product(d.embedding, ?1) DESC' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(5); ``` -------------------------------- ### Doctrine Full Setup Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Instructions for setting up pgvector with Doctrine ORM, including entity definition, type registration, extension creation, and query usage. ```php // src/Entity/Document.php use Doctrine\ORM\Mapping as ORM; use Pgvector\Vector; use Pgvector\Doctrine\PgvectorSetup; #[ORM\Entity] class Document { #[ORM\Column(type: 'vector', length: 1536)] private Vector $embedding; } // bootstrap code use Doctrine\ORM\EntityManager; $entityManager = // ... create entity manager // Register pgvector types PgvectorSetup::registerTypes($entityManager); // Create extension $entityManager->getConnection()->executeStatement( 'CREATE EXTENSION IF NOT EXISTS vector' ); // Usage $embedding = new Vector([/* ... */]); $query = $entityManager->createQuery( 'SELECT d FROM Document d ORDER BY l2_distance(d.embedding, ?1)' ) ->setParameter(1, $embedding) ->setMaxResults(10); ``` -------------------------------- ### Vector Column Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Example of adding a pgvector column with a specified dimension size. ```php Schema::create('items', function (Blueprint $table) { $table->id(); $table->vector('embedding', 1536); // 1536-dimensional vector $table->timestamps(); }); ``` -------------------------------- ### Sparse Vectors in Entity and Queries Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example demonstrating the 'sparsevec' type in an entity and its use with jaccard_distance in queries. ```php #[ORM\Column(type: 'sparsevec')] private SparseVector $sparseEmbedding; // In queries with Jaccard distance $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY jaccard_distance(e.sparseEmbedding, ?1)' ) ->setParameter(1, new SparseVector([1, 0, 2, 0, 3])); ``` -------------------------------- ### Create from SplFixedArray Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example of creating a SparseVector from a SplFixedArray. ```php $arr = new SplFixedArray(6); $arr[0] = 1; $arr[1] = 0; $arr[2] = 2; $arr[3] = 0; $arr[4] = 3; $arr[5] = 0; $vector = new SparseVector($arr); ``` -------------------------------- ### MissingAttributeException: Workaround Examples Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Examples showing how to work around MissingAttributeException by ensuring the 'embedding' column is loaded. ```php // Ensure the column is loaded $item = Item::find(1); // loads all columns $neighbors = $item->nearestNeighbors('embedding', Distance::L2); // Or explicitly select it $item = Item::select('id', 'name', 'embedding')->first(); $neighbors = $item->nearestNeighbors('embedding', Distance::L2); ``` -------------------------------- ### Binary Vectors (Bit) in Entity and Queries Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example showing the 'bit' type in an entity and its use with hamming_distance in queries. ```php #[ORM\Column(type: 'bit', length: 256)] private string $binaryVector; // In queries with Hamming distance $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY hamming_distance(e.binaryVector, ?1)' ) ->setParameter(1, '1010101010...'); ``` -------------------------------- ### PgvectorSetup Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of registering pgvector types and functions with Doctrine ORM. ```php use Pgvector\Doctrine\PgvectorSetup; PgvectorSetup::registerTypes($entityManager); ``` -------------------------------- ### scopeNearestNeighbors Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-hasneighbors.md Examples of using the scopeNearestNeighbors static scope to find nearest neighbors. ```php use Pgvector\Laravel\Distance; // Static scope call on query builder $neighbors = Item::query() ->nearestNeighbors('embedding', [1.0, 2.0, 3.0], Distance::L2) ->take(5) ->get(); // With existing query conditions $neighbors = Item::query() ->where('status', 'active') ->nearestNeighbors('embedding', [1.0, 2.0, 3.0], Distance::Cosine) ->take(10) ->get(); // Using Vector object $searchVector = new Vector([1.0, 2.0, 3.0]); $neighbors = Item::query() ->nearestNeighbors('embedding', $searchVector, Distance::InnerProduct) ->limit(5) ->get(); ``` -------------------------------- ### Combining with Other Query Methods Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-hasneighbors.md Example showing how to combine nearestNeighbors with other Eloquent query methods. ```php $neighbors = Item::where('category', 'electronics') ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->whereBetween('price', [10, 100]) ->orderBy('rating', 'desc') ->take(10) ->get(); ``` -------------------------------- ### Half Vectors in Entity and Queries Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example showing the 'halfvec' type in an entity definition and its usage in queries with l2_distance. ```php #[ORM\Column(type: 'halfvec', length: 768)] private HalfVector $halfEmbedding; // In queries $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY l2_distance(e.halfEmbedding, ?1)' ) ->setParameter(1, new HalfVector([1.0, 2.0, 3.0])); ``` -------------------------------- ### MaxInnerProduct Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Calculates maximum inner product (dot product). Higher values indicate more similarity. ```php $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY max_inner_product(e.embedding, ?1) DESC' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(10); ``` -------------------------------- ### Create from dense array Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example of creating a SparseVector from a dense array. ```php use Pgvector\SparseVector; $vector = new SparseVector([1, 0, 2, 0, 3, 0]); // Dimensions: 6, non-zero: 3 ``` -------------------------------- ### Example Usage Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Demonstrates how to register the pgvector schema and use its types in a Laravel migration. ```php use Pgvector\Laravel\Schema; // In a service provider or bootstrap file Schema::register(); // Now migrations can use pgvector types Schema::create('items', function (Blueprint $table) { $table->vector('embedding', 3); $table->halfvec('half_embedding', 3); $table->bit('binary_vector', 64); $table->sparsevec('sparse_embedding', 1000); }); ``` -------------------------------- ### Doctrine Configuration Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-types.md Shows how to configure various pgvector Doctrine types (vector, halfvec, bit, sparsevec) in a Symfony application's doctrine.yaml file. ```yaml doctrine: dbal: types: vector: Pgvector\Doctrine\VectorType halfvec: Pgvector\Doctrine\HalfVectorType bit: Pgvector\Doctrine\BitType sparsevec: Pgvector\Doctrine\SparseVectorType ``` -------------------------------- ### Vector Class Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of creating a dense vector. ```php $vector = new Vector([1.0, 2.0, 3.0]); ``` -------------------------------- ### Create from pgvector string format Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example of creating a SparseVector from the pgvector string format. ```php $vector = new SparseVector('{1:1,3:2,5:3}/6'); // Dimensions: 6, indices: [0, 2, 4] (1-indexed in string), values: [1, 2, 3] ``` -------------------------------- ### Compare Multiple Distance Metrics Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Example demonstrating how to compare L2 distance, cosine distance, and max inner product in a single query. ```php $vector = new Vector([1.0, 2.0, 3.0]); $query = 'SELECT e, l2_distance(e.embedding, ?1) as l2, cosine_distance(e.embedding, ?1) as cosine, max_inner_product(e.embedding, ?1) as ip FROM App\Entity\Embedding e ORDER BY l2'; $results = $entityManager->createQuery($query) ->setParameter(1, $vector) ->setMaxResults(10) ->getResult(); ``` -------------------------------- ### SparseVector Class Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of creating a sparse vector. ```php $vector = new SparseVector([1, 0, 2, 0, 3]); ``` -------------------------------- ### Using L2 Distance in Queries Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example of a DQL query using the l2_distance function to order documents by embedding similarity. ```php $query = $entityManager->createQuery( 'SELECT d FROM App\Entity\Document d ORDER BY l2_distance(d.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(10); $results = $query->getResult(); ``` -------------------------------- ### BitType Example Usage Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-types.md Shows how to use the BitType for storing binary vectors as strings in an ORM entity. ```php #[ORM\Column(type: 'bit', length: 256)] private string $binaryVector; // Store binary string $article->binaryVector = '1010101010...'; // 256 bits $entityManager->persist($article); $entityManager->flush(); // On retrieval $loaded = $entityManager->find(Article::class, 1); echo $loaded->binaryVector; // string, not converted ``` -------------------------------- ### nearestNeighbors Instance Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-hasneighbors.md Example of using the nearestNeighbors instance method to find items similar to the current model instance. ```php use Pgvector\Laravel\Distance; // Get an item from database $item = Item::find(1); // Find 5 similar items $similar = $item->nearestNeighbors('embedding', Distance::Cosine) ->take(5) ->get(); foreach ($similar as $neighbor) { echo "ID: {$neighbor->id}, Distance: {$neighbor->neighbor_distance}\n"; } ``` -------------------------------- ### Entity Definition with Vector Type Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-pgvectorsetup.md Example of an entity definition using the 'vector' type for an embedding field. ```php use Doctrine\ORM\Mapping as ORM; use Pgvector\Vector; #[ORM\Entity] class Document { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column(type: 'integer')] private int $id; #[ORM\Column(type: 'string', length: 255)] private string $title; #[ORM\Column(type: 'vector', length: 1536)] private Vector $embedding; // Getters and setters } ``` -------------------------------- ### Find Nearest Neighbors Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Example of finding the 10 nearest neighbors using L2 distance. ```php $searchVector = new Vector([1.5, 2.5, 3.5]); $nearest = $entityManager->createQuery( 'SELECT e, l2_distance(e.embedding, ?1) as distance FROM App\Entity\Embedding e ORDER BY distance' ) ->setParameter(1, $searchVector) ->setMaxResults(10) ->getResult(); foreach ($nearest as $result) { echo "ID: {$result[0]->id}, Distance: {$result['distance']}\n"; } ``` -------------------------------- ### __toString Magic Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/vector.md Converts the vector to JSON string representation for database storage. ```php $vector = new Vector([1.1, 2.2, 3.3]); echo $vector; // outputs: [1.1,2.2,3.3] // Automatically called when used as string pg_query_params($db, 'INSERT INTO items (embedding) VALUES ($1)', [$vector]); ``` -------------------------------- ### HalfVector Class Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of creating a half-precision vector. ```php $vector = new HalfVector([1.0, 2.0, 3.0]); ``` -------------------------------- ### MissingAttributeException: HasNeighbors::nearestNeighbors Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Example demonstrating how MissingAttributeException is thrown when the 'embedding' attribute is missing from a model instance. ```php use Pgvector\Laravel\HasNeighbors; use Illuminate\Database\Eloquent\Model; class Item extends Model { use HasNeighbors; } // Model loaded without the column $item = Item::select('id', 'name')->first(); // MissingAttributeException: App\Models\Item is missing the "embedding" attribute $neighbors = $item->nearestNeighbors('embedding', Distance::L2); ``` -------------------------------- ### InvalidArgumentException: Vector Constructor Examples Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Examples demonstrating how InvalidArgumentException is thrown by the Vector constructor with invalid inputs. ```php use Pgvector\Vector; // InvalidArgumentException: Expected array $v = new Vector(123); // InvalidArgumentException: Expected array to be a list $v = new Vector(['key' => 1, 'key2' => 2]); // InvalidArgumentException: Invalid text representation $v = new Vector('not valid json'); ``` -------------------------------- ### HalfVectorType Example Usage Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-types.md Illustrates the usage of HalfVectorType, which functions identically to VectorType but for half-precision vectors. ```php #[ORM\Column(type: 'halfvec', length: 768)] private HalfVector $embedding; // Works identically to VectorType $article->embedding = new HalfVector([1.0, 2.0, 3.0]); ``` -------------------------------- ### HammingDistance Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Calculates Hamming distance for binary vectors. Counts differing bits. ```php $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY hamming_distance(e.binaryVector, ?1)' ) ->setParameter(1, '101010...') // 256-bit string ->setMaxResults(10); ``` -------------------------------- ### Create from sparse map with explicit dimensions Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example of creating a SparseVector from a sparse map with explicit dimensions. ```php $elements = [0 => 1, 2 => 2, 4 => 3]; $vector = new SparseVector($elements, 6); // Same result as dense array above ``` -------------------------------- ### Doctrine ORM Integration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example of registering the SparseVector type with Doctrine ORM. ```php use Pgvector\Doctrine\PgvectorSetup; use Pgvector\SparseVector; // Register types PgvectorSetup::registerTypes($entityManager); // In entity class #[ORM\Column(type: 'sparsevec')] private SparseVector $embedding; ``` -------------------------------- ### Insert Vector in Laravel Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Example of inserting a vector into a Laravel model. ```php $item = new Item(); $item->embedding = [1, 2, 3]; $item->save(); ``` -------------------------------- ### Schema Helper Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of using schema helpers for pgvector column types in Laravel migrations. ```php Schema::register(); Schema::create('items', function (Blueprint $table) { $table->vector('embedding', 1536); $table->halfvec('lite_embedding', 768); $table->bit('binary_hash', 256); $table->sparsevec('sparse_embedding', 10000); }); ``` -------------------------------- ### Sparse Vectors for Text Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of creating and using Sparse Vectors for text embeddings in queries. ```php $sparsevec = new SparseVector([1, 0, 0, 2, 0, 3, 0, 0, 4]); // Stores only indices [0, 3, 5, 8] with values [1, 2, 3, 4] // In queries $query->nearestNeighbors('embedding', $sparsevec, Distance::Jaccard); ``` -------------------------------- ### Laravel with OpenAI Embeddings Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of finding similar articles using Laravel, pgvector, and OpenAI embeddings. ```php use Pgvector\Laravel\Vector; use Pgvector\Laravel\Distance; class Article extends Model { use HasNeighbors; protected $casts = ['embedding' => Vector::class]; } // Find similar articles $query = 'Find articles similar to this one'; $embedding = $openai->embeddings($query); $similar = Article::query() ->nearestNeighbors('embedding', $embedding, Distance::Cosine) ->take(5) ->get(); ``` -------------------------------- ### Define Vector Column in Laravel Migration Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Example of defining a vector column in a Laravel migration. ```php Schema::create('items', function (Blueprint $table) { $table->vector('embedding', 3); }); ``` -------------------------------- ### toArray Method Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/vector.md Converts the vector to a PHP array of numeric values. ```php $vector = new Vector([1, 2, 3]); $arr = $vector->toArray(); // $arr === [1, 2, 3] ``` -------------------------------- ### Laravel Schema Registration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Example of registering pgvector schema types in a Laravel application. ```php use Pgvector\Laravel\Schema; // Call once during application bootstrap Schema::register(); ``` -------------------------------- ### L2Distance Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Calculates Euclidean distance (L2 norm). Lower values indicate more similarity. ```php $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY l2_distance(e.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(10); ``` -------------------------------- ### Getting All Columns Plus Distance Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-hasneighbors.md Illustrates that the scope resets the select clause, including all model columns and neighbor_distance. ```php $neighbors = Item::query() ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->get(); // Available: $neighbors[0]->id, $neighbors[0]->name, $neighbors[0]->embedding, $neighbors[0]->neighbor_distance ``` -------------------------------- ### Laravel Integration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md Example of using the Laravel castable version for model attribute casting. ```php use Pgvector\Laravel\SparseVector; class Item extends Model { protected $casts = ['embedding' => SparseVector::class]; } $item = new Item(); $item->embedding = [1, 0, 2, 0, 3]; $item->save(); ``` -------------------------------- ### Distance Enum Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of using the Distance enum for nearest-neighbor queries. ```php use Pgvector\Laravel\Distance; Distance::L2 // Euclidean distance Distance::InnerProduct // Dot product similarity Distance::Cosine // Cosine distance Distance::L1 // Manhattan distance Distance::Hamming // Binary vector distance Distance::Jaccard // Sparse vector distance ``` -------------------------------- ### SparseVector Example Usage Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-types.md Demonstrates how to use the sparsevec Doctrine type in an ORM entity, including storing and retrieving sparse vectors. ```php @ORM\Column(type: 'sparsevec') private SparseVector $embedding; // Store sparse vector $article->embedding = new SparseVector([1, 0, 0, 2, 0, 3]); $entityManager->persist($article); $entityManager->flush(); // Stored as '{1:1,4:2,6:3}/6' // On retrieval $loaded = $entityManager->find(Article::class, 1); // $loaded->embedding is SparseVector object echo $loaded->embedding->dimensions(); // 6 ``` -------------------------------- ### VectorType Example Usage Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-types.md Demonstrates how to use the VectorType in an ORM entity, including automatic conversion on save and retrieval. ```php #[ORM\Column(type: 'vector', length: 1536)] private Vector $embedding; // Automatic conversion on save/load $article->embedding = new Vector([1.0, 2.0, 3.0]); $entityManager->persist($article); $entityManager->flush(); // Stored in database as JSON string // On retrieval $loaded = $entityManager->find(Article::class, 1); // $loaded->embedding is automatically a Vector object ``` -------------------------------- ### L1Distance Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Calculates Manhattan distance (L1 norm). Sum of absolute differences between elements. ```php $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY l1_distance(e.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(10); ``` -------------------------------- ### JaccardDistance Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Calculates Jaccard distance for sparse vectors. Measures set similarity. ```php $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY jaccard_distance(e.sparseEmbedding, ?1)' ) ->setParameter(1, new SparseVector([1, 0, 2, 0, 3])) ->setMaxResults(10); ``` -------------------------------- ### HasNeighbors Trait Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of using the HasNeighbors trait to find nearest neighbors in Laravel. ```php $neighbors = Item::query() ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->take(5) ->get(); $item = Item::find(1); $similar = $item->nearestNeighbors('embedding', Distance::Cosine) ->take(5) ->get(); ``` -------------------------------- ### Laravel Model Attribute Casting Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Example of configuring vector attribute casting in a Laravel Eloquent model. ```php use Pgvector\Laravel\Vector; use Pgvector\Laravel\HalfVector; use Pgvector\Laravel\SparseVector; class Item extends Model { protected $casts = [ 'embedding' => Vector::class, 'lite_embedding' => HalfVector::class, 'sparse_embedding' => SparseVector::class, ]; } ``` -------------------------------- ### CosineDistance Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Calculates cosine distance (inverse of cosine similarity). Works best with normalized vectors. ```php $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e ORDER BY cosine_distance(e.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(10); ``` -------------------------------- ### Filtering and Ordering with Different Metrics Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/doctrine-distance-functions.md Example of filtering embeddings by an 'active' status and ordering them by cosine distance. ```php // Find active embeddings, order by cosine distance $query = $entityManager->createQuery( 'SELECT e FROM App\Entity\Embedding e WHERE e.active = true ORDER BY cosine_distance(e.embedding, ?1)' ) ->setParameter(1, new Vector([1.0, 2.0, 3.0])) ->setMaxResults(5); ``` -------------------------------- ### Reference - Get Vector as Array Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Get the array representation of a Vector object. ```php $arr = $vec->toArray(); ``` -------------------------------- ### Doctrine Distance Functions Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md Example of using custom DQL functions for distance calculations in Doctrine ORM. ```php $query = $entityManager->createQuery( 'SELECT e FROM Embedding e ORDER BY l2_distance(e.embedding, ?1)' ) ->setParameter(1, new Vector([1, 2, 3])) ->setMaxResults(10); ``` -------------------------------- ### Exception Handling Pattern: Vector Construction Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Example of how to handle InvalidArgumentException during Vector construction using a try-catch block. ```php use Pgvector\Vector; try { $vector = new Vector($value); } catch (\InvalidArgumentException $e) { // Handle invalid input echo "Invalid vector data: " . $e->getMessage(); } ``` -------------------------------- ### Add Approximate Index in Laravel Migration Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Example of adding an approximate nearest neighbor (ANN) index using HNSW or IVFFlat in a Laravel migration. ```php public function up() { DB::statement('CREATE INDEX my_index ON items USING hnsw (embedding vector_l2_ops)'); // or DB::statement('CREATE INDEX my_index ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)'); } public function down() { DB::statement('DROP INDEX my_index'); } ``` -------------------------------- ### SparseVector Constructor Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Shows how to create SparseVector instances using dense arrays, sparse maps with dimensions, or sparse string formats. ```php use Pgvector\SparseVector; // Dense array - automatically extracts non-zero $v1 = new SparseVector([1, 0, 2, 0, 3, 0]); // Sparse map with explicit dimensions $sparse = [0 => 1, 2 => 2, 4 => 3]; $v2 = new SparseVector($sparse, 6); // Sparse string format $v3 = new SparseVector('{1:1,3:2,5:3}/6'); ``` -------------------------------- ### Results Structure Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-hasneighbors.md Demonstrates how to access model attributes and the neighbor_distance attribute after a nearest neighbors query. ```php $neighbors = Item::query() ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->take(5) ->get(); foreach ($neighbors as $item) { echo $item->id; // Model ID echo $item->neighbor_distance; // Float distance value } // Extract distances without models $distances = $neighbors->pluck('neighbor_distance'); ``` -------------------------------- ### Vector and HalfVector Constructor Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Demonstrates the different ways to instantiate Vector and HalfVector classes using arrays, JSON strings, or SplFixedArray. ```php use Pgvector\Vector; // Array $v1 = new Vector([1, 2, 3]); // JSON string $v2 = new Vector('[1.0, 2.0, 3.0]'); // SplFixedArray $arr = new \SplFixedArray(3); $arr[0] = 1; $arr[1] = 2; $arr[2] = 3; $v3 = new Vector($arr); ``` -------------------------------- ### InvalidArgumentException: SparseVector Constructor Examples Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Examples demonstrating how InvalidArgumentException is thrown by the SparseVector constructor with invalid inputs. ```php use Pgvector\SparseVector; // InvalidArgumentException: Expected array $v = new SparseVector(123); // InvalidArgumentException: Extra argument $v = new SparseVector('{1:1,3:2}/6', 6); // InvalidArgumentException when parsing $v = new SparseVector('invalid format'); ``` -------------------------------- ### InvalidArgumentException: HalfVector Constructor Examples Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Examples demonstrating how InvalidArgumentException is thrown by the HalfVector constructor with invalid inputs. ```php use Pgvector\HalfVector; // InvalidArgumentException: Expected array $v = new HalfVector(123); // InvalidArgumentException: Expected array to be a list $v = new HalfVector(['key' => 1]); ``` -------------------------------- ### Bootstrap File Registration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Demonstrates registering the pgvector schema directly in the `bootstrap/app.php` file. ```php // bootstrap/app.php use Pgvector\Laravel\Schema; Schema::register(); return Application::configure(basePath: dirname(__DIR__)) ->withRouting(/* ... */) ->withMiddleware(/* ... */) ->withExceptionHandling() ->create(); ``` -------------------------------- ### InvalidArgumentException: HasNeighbors::scopeNearestNeighbors Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Example illustrating the condition that would trigger InvalidArgumentException in HasNeighbors::scopeNearestNeighbors, though type hinting prevents it in practice. ```php use Pgvector\Laravel\HasNeighbors; // Won't actually throw with enum type checking, but guards against: class MockBuilder { use HasNeighbors; } ``` -------------------------------- ### IVFFlat Index Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md SQL statement to create an IVFFlat index for vector similarity searches. ```sql CREATE INDEX embedding_idx ON documents USING ivfflat (embedding vector_l2_ops) WITH (lists = 100) ``` -------------------------------- ### Get Number of Dimensions Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Retrieves the total number of dimensions of a sparse vector. ```php $dim = $vec->dimensions(); ``` -------------------------------- ### Enable pgvector Extension - Doctrine Migration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Doctrine migration snippet to create the pgvector extension. ```php public function up(Schema $schema): void { $this->addSql('CREATE EXTENSION IF NOT EXISTS vector'); } public function down(Schema $schema): void { $this->addSql('DROP EXTENSION vector'); } ``` -------------------------------- ### Get Distances in Laravel Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Extract the distances from the nearest neighbors query results. ```php $neighbors->pluck('neighbor_distance'); ``` -------------------------------- ### Inner Product Index Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md SQL statement to create an Inner Product index for vector similarity searches. ```sql CREATE INDEX embedding_idx ON documents USING hnsw (embedding vector_ip_ops) ``` -------------------------------- ### Symfony - Migrate Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Run Doctrine migrations to apply the changes. ```sh php bin/console doctrine:migrations:migrate ``` -------------------------------- ### Get Indices of Non-Zero Elements Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Extracts the indices where the sparse vector has non-zero values. ```php $indices = $vec->indices(); ``` -------------------------------- ### PgSql - Get nearest neighbors Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Query for nearest neighbors using the '<->' operator in PostgreSQL. ```php $embedding = new Vector([1, 2, 3]); $result = pg_query_params($db, 'SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5', [$embedding]); ``` -------------------------------- ### Enable pgvector Extension - Laravel Migration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Laravel migration to create the pgvector extension. ```php use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\DB; return new class extends Migration { public function up(): void { DB::statement('CREATE EXTENSION IF NOT EXISTS vector'); } public function down(): void { DB::statement('DROP EXTENSION vector'); } }; ``` -------------------------------- ### Get Values of Non-Zero Elements Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Retrieves the actual values of the non-zero elements in the sparse vector. ```php $values = $vec->values(); ``` -------------------------------- ### Get Nearest Neighbors to a Vector in Laravel Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Query for nearest neighbors based on a provided vector. ```php $neighbors = Item::query()->nearestNeighbors('embedding', [1, 2, 3], Distance::L2)->take(5)->get(); ``` -------------------------------- ### L2 Distance Index Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md SQL statement to create an L2 distance index for vector similarity searches. ```sql CREATE INDEX embedding_idx ON documents USING hnsw (embedding vector_l2_ops) ``` -------------------------------- ### Constructor Signature Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md The signature for the SparseVector constructor. ```php public function __construct(mixed $value, mixed $dimensions = null) ``` -------------------------------- ### Enable pgvector Migrations for Laravel Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Publish and run pgvector migrations to enable vector types. ```sh php artisan vendor:publish --tag="pgvector-migrations" php artisan migrate ``` -------------------------------- ### Doctrine - Get nearest neighbors Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Query for the nearest neighbors to a given vector using L2 distance. ```php $neighbors = $entityManager->createQuery('SELECT i FROM Item i ORDER BY l2_distance(i.embedding, ?1)') ->setParameter(1, new Vector([1, 2, 3])) ->setMaxResults(5) ->getResult(); ``` -------------------------------- ### Symfony - Get nearest neighbors Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Query for the nearest neighbors to a given vector using L2 distance. ```php $neighbors = $entityManager->createQuery('SELECT i FROM App\Entity\Item i ORDER BY l2_distance(i.embedding, ?1)') ->setParameter(1, new Vector([1, 2, 3])) ->setMaxResults(5) ->getResult(); ``` -------------------------------- ### Create Sparse Vector from Indexed Array Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Demonstrates creating a sparse vector using an indexed array where zero values are implicitly understood. ```php $vec = new SparseVector([1, 0, 2, 0, 3, 0]); ``` -------------------------------- ### Project Structure Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/index.md The directory structure of the pgvector-php project. ```tree src/ ├── Vector.php # Core Vector class ├── HalfVector.php # Half-precision Vector ├── SparseVector.php # Sparse Vector ├── laravel/ │ ├── Vector.php # Laravel castable Vector │ ├── HalfVector.php # Laravel castable HalfVector │ ├── SparseVector.php # Laravel castable SparseVector │ ├── Distance.php # Distance metric enum │ ├── HasNeighbors.php # Query scope trait │ ├── Schema.php # Migration helpers │ ├── PgvectorServiceProvider.php │ └── migrations/ │ └── 2022_08_03_000000_create_vector_extension.php └── doctrine/ ├── PgvectorSetup.php # Setup helper ├── VectorType.php # DBAL Vector type ├── HalfVectorType.php # DBAL HalfVector type ├── BitType.php # DBAL Bit type ├── SparseVectorType.php # DBAL SparseVector type ├── DistanceNode.php # Base distance function ├── L2Distance.php ├── MaxInnerProduct.php ├── CosineDistance.php ├── L1Distance.php ├── HammingDistance.php └── JaccardDistance.php ``` -------------------------------- ### PgSql - Create a table Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Create a table with a vector column in PostgreSQL. ```php pg_query($db, 'CREATE TABLE items (embedding vector(3))'); ``` -------------------------------- ### Service Provider Registration Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-schema.md Shows how to register the pgvector schema in the `boot` method of a Laravel service provider. ```php use Pgvector\Laravel\Schema; class AppServiceProvider extends ServiceProvider { public function boot(): void { Schema::register(); } } ``` -------------------------------- ### Distance Metric Usage Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md Demonstrates how to use the Distance enum for nearest neighbor queries in Laravel. ```php use Pgvector\Laravel\Distance; // Scope usage Item::query() ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->take(5) ->get(); // Instance method usage $item->nearestNeighbors('embedding', Distance::Cosine) ->take(5) ->get(); ``` -------------------------------- ### Cosine Distance Index Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/configuration.md SQL statement to create a Cosine distance index for vector similarity searches. ```sql CREATE INDEX embedding_idx ON documents USING hnsw (embedding vector_cosine_ops) ``` -------------------------------- ### Get Nearest Neighbors to a Record in Laravel Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Retrieve the nearest neighbors to a specific record using the HasNeighbors trait. ```php use Pgvector\Laravel\Distance; $neighbors = $item->nearestNeighbors('embedding', Distance::L2)->take(5)->get(); ``` -------------------------------- ### Symfony - Create a migration to enable the extension Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Generate a Doctrine migration to enable the pgvector extension. ```sh php bin/console doctrine:migrations:generate ``` -------------------------------- ### __toString Method Signature Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/sparsevector.md The signature for the __toString magic method. ```php public function __toString(): string ``` -------------------------------- ### Casting Distance Attribute Example Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/api-reference/laravel-hasneighbors.md Demonstrates that the neighbor_distance attribute is automatically cast to a double (float). ```php $neighbors = Item::query() ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->get(); // $neighbors[0]->neighbor_distance is a float, not string echo gettype($neighbors[0]->neighbor_distance); // double ``` -------------------------------- ### PgSql - Enable the extension Source: https://github.com/pgvector/pgvector-php/blob/master/README.md Enable the pgvector extension in the PostgreSQL database. ```php pg_query($db, 'CREATE EXTENSION IF NOT EXISTS vector'); ``` -------------------------------- ### Laravel Model Queries Source: https://github.com/pgvector/pgvector-php/blob/master/_autodocs/errors.md Demonstrates how to perform nearest neighbor searches using Laravel Eloquent models, including error handling for invalid arguments and missing attributes. ```php use Pgvector\Laravel\Distance; use Pgvector\Laravel\Vector; try { // Scope call - may throw InvalidArgumentException $neighbors = Item::query() ->nearestNeighbors('embedding', [1, 2, 3], Distance::L2) ->get(); } catch (\InvalidArgumentException $e) { echo "Query error: " . $e->getMessage(); } try { // Instance method - may throw MissingAttributeException $item = Item::find(1); $neighbors = $item->nearestNeighbors('embedding', Distance::L2) ->get(); } catch (\Illuminate\Database\Eloquent\MissingAttributeException $e) { echo "Attribute missing: " . $e->getMessage(); } ```