PHP code example of partitech / doctrine-pgvector

1. Go to this page and download the library: Download partitech/doctrine-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/ */

    

partitech / doctrine-pgvector example snippets


use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity()
  */
  class YourEntity
  {

    #[ORM\Column(type: 'vector', length: 1024, nullable: true)]
    private $vectors;
    
  }

$floatArray = array_map(function() {
    return mt_rand(0, 1000000) / 1000000;
}, array_fill(0, 1024, null));

$query = $this->entityManager->createQuery(
    "SELECT i FROM App\Entity\Embeddings i ORDER BY distance(i.vectors, :vector) ASC"
);
$query->setParameter('vector', $floatArray, 'vector');
$results = $query->setMaxResults(5)->getResult();
dump($results);

$qb = $this->entityManager->createQueryBuilder();
$qb->select('e')
    ->from('App:Embeddings', 'e')
    ->orderBy('distance(e.vectors, :vector)')
    ->setParameter('vector', $floatArray, 'vector')
    ->setMaxResults(5)
    ;
$result = $qb->getQuery()->getResult();
dump($result);

$floatArray = array_map(function() {
    return mt_rand(0, 1000000) / 1000000;
}, array_fill(0, 1024, null));

$query = $this->entityManager->createQuery(
    "SELECT inner_product(e.vectors, :vector) , e FROM App\Entity\Embeddings e"
);
$query->setParameter('vector', $floatArray, 'vector');
$results = $query->setMaxResults(5)->getResult();
dump($results);

$qb = $this->entityManager->createQueryBuilder();
$qb->select('e')
    ->addSelect('inner_product(e.vectors, :vector)')
    ->from('App:Embeddings', 'e')
    ->setParameter('vector', $floatArray, 'vector')
    ->setMaxResults(5)
    ;
$result = $qb->getQuery()->getResult();
dump($result);

$floatArray = array_map(function() {
return mt_rand(0, 1000000) / 1000000;
}, array_fill(0, 1024, null));

$query = $this->entityManager->createQuery(
    "SELECT cosine_similarity(e.vectors, :vector) , e FROM App\Entity\Embeddings e"
);
$query->setParameter('vector', $floatArray, 'vector');
$results = $query->setMaxResults(5)->getResult();
dump($results);

$qb = $this->entityManager->createQueryBuilder();
$qb->select('e')
    ->addSelect('cosine_similarity(e.vectors, :vector)')
    ->from('App:Embeddings', 'e')
    ->setParameter('vector', $floatArray, 'vector')
    ->setMaxResults(5)
    ;
$result = $qb->getQuery()->getResult();
dump($result);
sql
SELECT * FROM embeddings WHERE vectors <-> '[3,1,2]' < 5