PHPackages                             allanpichardo/mysql-vector - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. allanpichardo/mysql-vector

ActiveLibrary[Database &amp; ORM](/categories/database)

allanpichardo/mysql-vector
==========================

Perform vector operations natively on MySQL

2.0.4(1y ago)8316.8k↑80.2%11[2 PRs](https://github.com/allanpichardo/mysql-vector/pulls)MITPHPPHP &gt;=8.0

Since Jan 2Pushed 1y ago6 watchersCompare

[ Source](https://github.com/allanpichardo/mysql-vector)[ Packagist](https://packagist.org/packages/allanpichardo/mysql-vector)[ RSS](/packages/allanpichardo-mysql-vector/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (7)Versions (8)Used By (0)

A Library for MySQL Vector Operations and Text Embeddings
=========================================================

[](#a-library-for-mysql-vector-operations-and-text-embeddings)

Overview
--------

[](#overview)

The `VectorTable` class is a PHP implementation designed to facilitate the storage, retrieval, and comparison of high-dimensional vectors in a MySQL database. This class utilizes MySQL JSON data types and a custom cosine similarity function (`COSIM`) to perform vector comparisons efficiently.

### Search Performance

[](#search-performance)

Vectors are binary quantized upon insertion into the database to optimize search speed and reranked to improve accuracy. However, this library is only suitable for small datasets (less than 1,000,000 vectors). For large datasets, it is recommended that you use a dedicated vector database such as [Qdrant](https://qdrant.tech/).

Search Benchmarks (384-dimensional vectors):

VectorsTime (seconds)1000.0210000.02100000.031000000.0610000000.48Features
--------

[](#features)

- Store vectors in a MySQL database using JSON data types.
- Calculate cosine similarity between vectors using a custom MySQL function.
- Normalize vectors and handle vector operations such as insertion, deletion, and searching.
- Support for vector quantization for optimized search operations.
- Native PHP support for generating for text embeddings using the [BGE embedding model](https://huggingface.co/BAAI/bge-base-en-v1.5).

Requirements
------------

[](#requirements)

- PHP 8.0 or higher.
- MySQL 5.7 or higher with support for JSON data types and stored functions.
- A MySQLi extension for PHP.

Installation
------------

[](#installation)

1. Ensure that PHP and MySQL are installed and properly configured on your system.
2. Install the library using [Composer](https://getcomposer.org/).

    ```
    composer require allanpichardo/mysql-vector
    ```

Usage
-----

[](#usage)

### Initializing the Vector Table

[](#initializing-the-vector-table)

Import the `VectorTable` class and create a new instance using the MySQLi connection, table name, and vector dimension.

```
use MHz\MysqlVector\VectorTable;

$mysqli = new mysqli("hostname", "username", "password", "database");
$tableName = "my_vector_table";
$dimension = 384;
$engine = 'InnoDB';

$vectorTable = new VectorTable($mysqli, $tableName, $dimension, $engine);
```

### Setting Up the Vector Table in MySQL

[](#setting-up-the-vector-table-in-mysql)

The `initialize` method will create the vector table in MySQL if it does not already exist. This method will also create the `COSIM` function in MySQL if it does not already exist.

```
$vectorTable->initialize();
```

### Inserting and Managing Vectors

[](#inserting-and-managing-vectors)

```
// Insert a new vector
$vector = [0.1, 0.2, 0.3, ..., 0.384];
$vectorId = $vectorTable->upsert($vector);

// Update an existing vector
$vectorTable->upsert($vector, $vectorId);

// Delete a vector
$vectorTable->delete($vectorId);
```

### Calculating Cosine Similarity

[](#calculating-cosine-similarity)

```
// Calculate cosine similarity between two vectors
$similarity = $vectorTable->cosim($vector1, $vector2);
```

### Searching for Similar Vectors

[](#searching-for-similar-vectors)

Perform a search for vectors similar to a given vector using the cosine similarity criteria. The `topN` parameter specifies the maximum number of similar vectors to return.

```
// Find vectors similar to a given vector
$similarVectors = $vectorTable->search($vector, $topN);
```

Text Embeddings
---------------

[](#text-embeddings)

The `Embedder` class calculates 384-dimensional text embeddings using the [BGE embedding model](https://huggingface.co/BAAI/bge-base-en-v1.5). The first time you instanciate the `Embedder` class, the ONNX runtime will be installed automatically. The maximum length of the input text is 512 characters. The `Embedder` class will automatically truncate the input text to 512 characters if it is longer than 512 characters.

```
use MHz\MysqlVector\Nlp\Embedder;

$embedder = new Embedder();

// Calculate the embeddings for a batch of text
$texts = ["Hello world!", "This is a test."];
$embeddings = $embedder->embed($texts);

print_r($embeddings[0][0]); // [0.1, 0.2, 0.3, ..., 0.384]
print_r($embeddings[1][0]); // [0.1, 0.2, 0.3, ..., 0.384]
```

Contributions
-------------

[](#contributions)

Contributions to this project are welcome. Please ensure that your code adheres to the existing coding standards and includes appropriate tests.

Development
-----------

[](#development)

This project uses DDEV, a Docker-based development environment. To get started, install DDEV and run the following commands:

```
ddev start
ddev composer install
```

To run the tests, use the following command:

```
ddev composer test
```

License
-------

[](#license)

MIT License

###  Health Score

41

—

FairBetter than 89% of packages

Maintenance42

Moderate activity, may be stable

Popularity42

Moderate usage in the ecosystem

Community15

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 91.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~95 days

Total

5

Last Release

483d ago

Major Versions

v1.0 → v2.02024-07-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/d9266afb1c1dd14055e836856b0ef6f4d072dd59ab5aea2aab29780d3cd03b4c?d=identicon)[allanpichardo](/maintainers/allanpichardo)

---

Top Contributors

[![allanpichardo](https://avatars.githubusercontent.com/u/5606153?v=4)](https://github.com/allanpichardo "allanpichardo (34 commits)")[![scotteuser](https://avatars.githubusercontent.com/u/7620946?v=4)](https://github.com/scotteuser "scotteuser (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/allanpichardo-mysql-vector/health.svg)

```
[![Health](https://phpackages.com/badges/allanpichardo-mysql-vector/health.svg)](https://phpackages.com/packages/allanpichardo-mysql-vector)
```

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.3k86.3M2.2k](/packages/symfony-symfony)[symfony/string

Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way

1.8k724.1M827](/packages/symfony-string)[twig/twig

Twig, the flexible, fast, and secure template language for PHP

8.4k443.2M5.8k](/packages/twig-twig)[symfony/filesystem

Provides basic utilities for the filesystem

4.6k669.1M3.2k](/packages/symfony-filesystem)[symfony/dom-crawler

Eases DOM navigation for HTML and XML documents

4.0k379.0M2.2k](/packages/symfony-dom-crawler)[symfony/validator

Provides tools to validate values

2.7k287.3M3.3k](/packages/symfony-validator)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
