PHPackages                             mindfulcoder49/mysql-vector-openai - 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. mindfulcoder49/mysql-vector-openai

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

mindfulcoder49/mysql-vector-openai
==================================

Perform vector operations natively on MySQL using openAI embeddings

1.0.2(1y ago)016MITPHPPHP &gt;=8.0

Since Sep 10Pushed 1y agoCompare

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

READMEChangelogDependencies (6)Versions (4)Used By (0)

Here's a `README.md` file that reflects the current functionality of your `VectorTable` class.

```
# MySQL Vector Table

This repository provides an implementation for storing, searching, and manipulating vectors in a MySQL database using cosine similarity and binary codes for efficient search. The main class `VectorTable` provides a variety of functions to handle vector data, including inserting, updating, searching, and computing similarity between vectors.

## Features

- **Cosine Similarity Search (COSIM)**: Efficiently compute the cosine similarity between vectors stored as JSON in MySQL.
- **Binary Code Representation**: Vectors are stored in binary form for efficient querying and similarity computation.
- **Hamming Distance Search (Optional)**: A method for searching vectors based on Hamming distance is also available, though not the primary method.
- **Vector Normalization**: Automatically normalizes vectors before inserting and computing similarity.
- **Batch Insertion**: Support for inserting multiple vectors at once.
- **Vector Management**: Functions to insert, update, delete, and retrieve vectors.

## Table Structure

The vectors are stored in a MySQL table with the following structure:
```sql
CREATE TABLE `your_table_name_vectors` (
    `id` INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    `vector` JSON,                  -- The original vector
    `normalized_vector` JSON,        -- The normalized vector
    `magnitude` DOUBLE,              -- The magnitude of the vector
    `binary_code` BLOB,              -- Binary representation of the vector for efficient searching
    `created` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB;
```

MySQL Function: `COSIM`
-----------------------

[](#mysql-function-cosim)

The class defines a custom MySQL function `COSIM` to compute cosine similarity between two vectors stored as JSON.

```
CREATE FUNCTION COSIM(v1 JSON, v2 JSON) RETURNS FLOAT DETERMINISTIC
BEGIN
    DECLARE sim FLOAT DEFAULT 0;
    DECLARE i INT DEFAULT 0;
    DECLARE len INT DEFAULT JSON_LENGTH(v1);

    IF JSON_LENGTH(v1) != JSON_LENGTH(v2) THEN RETURN NULL; END IF;

    WHILE i search($inputVector, $n = 10);
```

- **$inputVector**: The vector to compare against the stored vectors.
- **$n**: The number of results to return (default is 10).

The function returns an array of the most similar vectors sorted by cosine similarity.

### `searchWithHamming()`

[](#searchwithhamming)

Search for vectors in the table based on Hamming distance between binary representations of vectors.

#### Usage:

[](#usage-1)

```
$results = $vectorTable->searchWithHamming($inputVector, $n = 10);
```

### `upsert()`

[](#upsert)

Insert or update a vector in the table. If the vector already exists (based on ID), it will be updated. Otherwise, a new vector will be inserted.

#### Usage:

[](#usage-2)

```
$id = $vectorTable->upsert($vector, $id = null);
```

- **$vector**: The vector to insert or update.
- **$id**: The optional ID of the vector to update. If not provided, a new vector is inserted.

### `batchInsert()`

[](#batchinsert)

Insert multiple vectors into the table in a single transaction.

#### Usage:

[](#usage-3)

```
$ids = $vectorTable->batchInsert($vectorArray);
```

- **$vectorArray**: An array of vectors to be inserted.

### `select()`

[](#select)

Retrieve vectors from the table by their IDs.

#### Usage:

[](#usage-4)

```
$vectors = $vectorTable->select($ids);
```

- **$ids**: An array of vector IDs to retrieve.

### `selectAll()`

[](#selectall)

Retrieve all vectors from the table.

#### Usage:

[](#usage-5)

```
$vectors = $vectorTable->selectAll();
```

### `delete()`

[](#delete)

Remove a vector from the table by its ID.

#### Usage:

[](#usage-6)

```
$vectorTable->delete($id);
```

- **$id**: The ID of the vector to remove.

### `normalize()`

[](#normalize)

Normalize a vector by its magnitude.

#### Usage:

[](#usage-7)

```
$normalizedVector = $vectorTable->normalize($vector);
```

- **$vector**: The vector to normalize.

### `cosim()`

[](#cosim)

Compute the cosine similarity between two vectors.

#### Usage:

[](#usage-8)

```
$similarity = $vectorTable->cosim($v1, $v2);
```

- **$v1**: The first vector.
- **$v2**: The second vector.

### `count()`

[](#count)

Get the total number of vectors stored in the database.

#### Usage:

[](#usage-9)

```
$totalVectors = $vectorTable->count();
```

### `vectorToBinary()`

[](#vectortobinary)

Convert an n-dimensional vector into a binary code.

#### Usage:

[](#usage-10)

```
$binaryCode = $vectorTable->vectorToBinary($vector);
```

Initialization
--------------

[](#initialization)

To create the necessary tables and functions, you need to call the `initialize()` method.

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

This will create the vectors table and the cosine similarity function (`COSIM`) in your database.

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

[](#installation)

1. Set up a MySQL database.
2. Create an instance of the `VectorTable` class.
3. Call `initialize()` to set up the table and functions.
4. Start inserting, updating, and searching for vectors!

### Example:

[](#example)

```
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');

$vectorTable = new \MHz\MysqlVector\VectorTable($mysqli, 'example_table', 384);
$vectorTable->initialize();

$vector = [1, 2, 3, 4, 5];
$vectorTable->upsert($vector);

$similarVectors = $vectorTable->search($vector);
```

License
-------

[](#license)

This project is licensed under the MIT License.

```

This `README.md` outlines the features, core functionalities, usage examples, and setup instructions for your `VectorTable` class. It reflects the current state of your code, including both cosine similarity and Hamming distance-based searches, and explains how to initialize, insert, search, and manage vectors in the MySQL database.

```

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 84.4% 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 ~3 days

Total

3

Last Release

609d ago

### Community

Maintainers

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

---

Top Contributors

[![allanpichardo](https://avatars.githubusercontent.com/u/5606153?v=4)](https://github.com/allanpichardo "allanpichardo (27 commits)")[![mindfulcoder49](https://avatars.githubusercontent.com/u/132383684?v=4)](https://github.com/mindfulcoder49 "mindfulcoder49 (5 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  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)
