ankane/ngt

High-speed approximate nearest neighbors for PHP

v0.1.1 2023-02-11 18:53 UTC

This package is not auto-updated.

Last update: 2024-05-19 00:43:39 UTC


README

NGT - high-speed approximate nearest neighbors - for PHP

Build Status

Installation

Run:

composer require ankane/ngt

And download the shared library:

composer exec -- php -r "require 'vendor/autoload.php'; Ngt\Vendor::check();"

On Mac, also install OpenMP:

brew install libomp

NGT is not available for Windows

Getting Started

Prep your data

$objects = [
    [1, 1, 2, 1],
    [5, 4, 6, 5],
    [1, 2, 1, 2]
];

Create an index

$index = new Ngt\Index($dimensions);

Insert objects

$index->batchInsert($objects);

Search the index

$index->search($query, size: 3);

Save the index

$index->save($path);

Load an index

$index = Ngt\Index::load($path);

Get an object by id

$index->object($id);

Insert a single object

$index->insert($object);

Remove an object by id

$index->remove($id);

Build the index

$index->buildIndex();

Full Example

$dim = 10;
$objects = [];
for ($i = 0; $i < 100; $i++) {
    $object = [];
    for ($j = 0; $j < $dim; $j++) {
        $object[] = rand(0, 100);
    }
    $objects[] = $object;
}

$index = new Ngt\Index($dim);
$index->batchInsert($objects);

$query = $objects[0];
$result = $index->search($query, size: 3);

foreach ($result as $res) {
    print($res['id'] . ', ' . $res['distance'] . "\n");
}

Index Options

Defaults shown below

use Ngt\DistanceType;
use Ngt\ObjectType;

new Ngt\Index(
    $dimensions,
    edgeSizeForCreation: 10,
    edgeSizeForSearch: 40,
    distanceType: DistanceType::L2,  // L1, L2, Hamming, Angle, Cosine, NormalizedAngle, NormalizedCosine, Jaccard
    objectType: ObjectType::Float    // Float, Float16, Integer
);

Credits

This library is modeled after NGT’s Python API.

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development:

git clone https://github.com/ankane/ngt-php.git
cd ngt-php
composer install
composer test