Home

Awesome

NGT PHP

NGT - high-speed approximate nearest neighbors - for PHP

Build Status

Installation

Run:

composer require ankane/ngt

Add scripts to composer.json to download the shared library:

    "scripts": {
        "post-install-cmd": "Ngt\\Vendor::check",
        "post-update-cmd": "Ngt\\Vendor::check"
    }

And run:

composer install

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