PHP code example of ankane / pgvector

1. Go to this page and download the library: Download ankane/pgvector library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ankane / pgvector example snippets


Schema::create('items', function (Blueprint $table) {
    $table->vector('embedding', 3);
});

use Pgvector\Laravel\Vector;

class Item extends Model
{
    use HasNeighbors;

    protected $casts = ['embedding' => Vector::class];
}

$item = new Item();
$item->embedding = [1, 2, 3];
$item->save();

use Pgvector\Laravel\Distance;

$neighbors = $item->nearestNeighbors('embedding', Distance::L2)->take(5)->get();

$neighbors = Item::query()->nearestNeighbors('embedding', [1, 2, 3], Distance::L2)->take(5)->get();

$neighbors->pluck('neighbor_distance');

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');
}

pg_query($db, 'CREATE EXTENSION IF NOT EXISTS vector');

pg_query($db, 'CREATE TABLE items (embedding vector(3))');

use Pgvector\Vector;

$embedding = new Vector([1, 2, 3]);
pg_query_params($db, 'INSERT INTO items (embedding) VALUES ($1)', [$embedding]);

$embedding = new Vector([1, 2, 3]);
$result = pg_query_params($db, 'SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5', [$embedding]);

pg_query($db, 'CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)');
// or
pg_query($db, 'CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)');
sh
php artisan vendor:publish --tag="pgvector-migrations"
php artisan migrate
sh
git clone https://github.com/pgvector/pgvector-php.git
cd pgvector-php
composer install
createdb pgvector_php_test
composer test
sh
cd examples/loading
composer install
createdb pgvector_example
php example.php