PHP code example of inm39 / mariadb-vector-bundle

1. Go to this page and download the library: Download inm39/mariadb-vector-bundle 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/ */

    

inm39 / mariadb-vector-bundle example snippets


// config/bundles.php
return [
    // ...
    INM39\MariadbVectorBundle\MariadbVectorBundle::class => ['all' => true],
];

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: DocumentRepository::class)]
class Document
{
    #[ORM\Id, ORM\GeneratedValue, ORM\Column]
    private ?int $id = null;

    #[ORM\Column(type: 'text')]
    private string $content;

    /** @var list<float> — `length` is the vector dimension */
    #[ORM\Column(type: 'vector', length: 768)]
    private array $embedding = [];

    // getters/setters...
}

public function up(Schema $schema): void
{
    $this->addSql('ALTER TABLE document ADD VECTOR INDEX (embedding) DISTANCE=cosine M=8');
}

use INM39\MariadbVectorBundle\Repository\VectorSearchTrait;

class DocumentRepository extends ServiceEntityRepository
{
    use VectorSearchTrait;
}

// $queryVector: float[] from your embedding model (Ollama, TEI, OpenAI...)
$results = $documentRepository->findNearest('embedding', $queryVector, limit: 5);

// With distances:
foreach ($documentRepository->findNearestWithDistance('embedding', $queryVector) as $row) {
    $document = $row[0];
    $distance = $row['distance'];
}

$documents = $em->createQuery(
    'SELECT d, VEC_DISTANCE_COSINE(d.embedding, VEC_FROMTEXT(:vec)) AS HIDDEN dist
     FROM App\Entity\Document d
     ORDER BY dist ASC'
)
->setParameter('vec', json_encode($queryVector))
->setMaxResults(10)
->getResult();

$response = $httpClient->request('POST', 'http://localhost:11434/api/embeddings', [
    'json' => [
        'model' => 'nomic-embed-text:v1.5',
        'prompt' => 'search_document: ' . $content,
    ],
]);
$embedding = $response->toArray()['embedding']; // float[768]