Metadata-Version: 2.2
Name: ngtstore
Version: 0.1.0
Summary: NGT-backed vector store with metadata filtering for LlamaIndex
Keywords: vector-store,ann,nearest-neighbor,ngt,llamaindex,metadata-filter
Author: Masajiro Iwasaki
License: Apache-2.0
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: C++
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Project-URL: Homepage, https://github.com/masajiro/NGT-store
Requires-Python: >=3.9
Provides-Extra: llama-index
Requires-Dist: llama-index-core; extra == "llama-index"
Description-Content-Type: text/markdown

# NGT-store

[English](README.md) | [日本語](README.ja.md)

A vector store with metadata filtering built on
[NGT](https://github.com/yahoojapan/NGT). It provides a C++17 library and
Python bindings through pybind11. It is designed to be used as a LlamaIndex
vector store.

- Choose among NGT's graph / quantized graph index types (Graph / QG / QBG).
- Metadata is stored in SQLite, and filter conditions are applied before the
  NGT search.
- Distance is selected at creation time from L2 / Cosine / NormalizedCosine /
  NormalizedL2.
- There is no C API and no generic vector-store abstraction. NGT-specific by
  design.

Design details and decisions are documented in
[DESIGN.md](DESIGN.md) (Japanese).

## Prerequisites

- A C++17 compiler and CMake 3.16 or newer
- SQLite3
- NGT (v2.8.3 or newer — the filter API is included in official upstream) and
  BLAS
  - Point `NGT_ROOT` at your NGT installation. Do not hardcode paths into the
    code. When `NGT_ROOT` is unset, NGT is built from the `third_party/ngt`
    submodule (the route `pip install .` takes).
  - For building NGT, see
    [「NGT の利用形態」in DESIGN.md](DESIGN.md#ngt-の利用形態) (Japanese).
- For the Python bindings only: Python 3.9 or newer and pybind11

## Building

Without NGT (metadata layer only):

```sh
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug
cmake --build build --parallel
ctest --test-dir build --output-on-failure
```

With NGT:

```sh
cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=Debug \
  -DNGTSTORE_WITH_NGT=ON \
  -DNGT_ROOT="$PWD/.deps/ngt-filter"
cmake --build build --parallel
ctest --test-dir build --output-on-failure
```

Including the Python bindings:

```sh
cmake -S . -B build \
  -DCMAKE_BUILD_TYPE=Debug \
  -DNGTSTORE_WITH_NGT=ON \
  -DNGT_ROOT="$PWD/.deps/ngt-filter" \
  -DNGTSTORE_BUILD_PYTHON=ON
cmake --build build --parallel
ctest --test-dir build --output-on-failure
```

From the build tree you can import with `PYTHONPATH=build/python`:

```sh
PYTHONPATH=build/python python3 -c 'import ngtstore; print(ngtstore.__version__)'
```

## Installation

The package can be installed as usual. NGT (v2.8.3) is built from the
`third_party/ngt` submodule and statically linked, so no system NGT is
required:

```sh
git clone --recursive https://github.com/masajiro/NGT-store
pip install .
```

Building needs a C++17 compiler, CMake 3.16 or newer, and BLAS/LAPACK
(cmake / ninja / pybind11 are fetched by pip automatically). The
`NGT_ROOT`-based developer flow above instead requires the system NGT shared
library at run time.

For the LlamaIndex integration:

```sh
pip install ".[llama-index]"
```

### Distributed wheels and variants

The wheels distributed on PyPI are prebuilt (generated by CI).

- **x86_64**: a single wheel bundles three extension modules
  (`_ngtstore_avx512`, `_ngtstore_avx2`, and the SIMD-disabled generic
  `_ngtstore_base`). At import time the CPU is probed and the best supported
  variant is chosen: AVX-512 only when the CPU covers the whole x86-64-v4
  set (AVX-512F/BW/CD/DQ/VL), otherwise AVX2, otherwise the generic build.
- **aarch64**: a single wheel (this NGT logically disables SIMD on ARM64, so
  one variant suffices).
- Every other environment builds from the sdist, where NGT compiles with the
  default `-march=native` and is therefore optimized for the build machine.

The wheel-build variant is selected with `NGTSTORE_SIMD_VARIANT`
(`single` / `base` / `avx2` / `avx512`, default `single`). `base`, `avx2`,
and `avx512` are fat-wheel build options that switch the vendored NGT's (when
`NGT_ROOT` is unset) compile flags and module name. The `avx512` variant
targets the x86-64-v4 baseline and lets the compiler auto-vectorize with
AVX-512 (upstream NGT has no AVX-512 kernels of its own).

## Python quick start

```python
from ngtstore import (
    DistanceType,
    IndexOptions,
    IndexType,
    NgtStore,
    all_of,
    eq,
    gt,
)

options = IndexOptions()
options.type = IndexType.GRAPH
options.distance_type = DistanceType.COSINE

store = NgtStore.create("./my-store", dimension=4, options=options)
try:
    store.add("n1", [1.0, 0.0, 0.0, 0.0], {"category": "book", "price": 1000})
    store.add_many(
        [
            ("n2", [0.9, 0.1, 0.0, 0.0], {"category": "book", "price": 2000}),
            ("n3", [0.0, 1.0, 0.0, 0.0], {"category": "music", "price": 1500}),
        ]
    )

    hits = store.search(
        [1.0, 0.0, 0.0, 0.0],
        5,
        filter=all_of([eq("category", "book"), gt("price", 500)]),
    )
    for hit in hits:
        print(hit.node_id, hit.distance, hit.metadata)

    store.save()
finally:
    store.close()
```

Reopening:

```python
with NgtStore.open("./my-store", read_only=True) as store:
    print(store.dimension, store.index_type, store.distance_type, store.live_count)
```

### Creation options

`IndexOptions` may only be specified at creation time and is stored in
`store_info`. `open()` takes no options.

```python
options = IndexOptions()
options.type = IndexType.QBG
options.distance_type = DistanceType.NORMALIZED_COSINE
options.qbg.number_of_blobs = 16
options.qbg.filter_expansion = 8
```

Options can also be created from JSON:

```python
from ngtstore import parse_index_options

options = parse_index_options(
    '{"type": "qbg", "distance_type": "cosine", '
    '"qbg": {"number_of_blobs": 16}}'
)
```

`options.type` is one of `GRAPH` / `QG` / `QBG`, and `options.distance_type`
is one of `L2` / `COSINE` / `NORMALIZED_COSINE` / `NORMALIZED_L2`. The
defaults are `GRAPH` and `L2`.

### Filters

Filters are assembled with Python functions.

```python
from ngtstore import all_of, any_of, contains, eq, ge, in_, is_empty, ne, not_

f = all_of(
    [
        eq("category", "book"),
        in_("language", ["ja", "en"]),
        not_(is_empty("tags")),
        any_of([contains("tags", "ai"), ne("status", "archived")]),
    ]
)
```

The operators are `==`, `!=`, `>`, `>=`, `<`, `<=`, `in`, `nin`, `contains`,
`text_match` (case-sensitive), `text_match_insensitive` (case-insensitive),
and `is_empty`. Nest them with `all_of` / `any_of` / `not_`.

- `not_` is the complement over the whole set, including rows that lack the
  key.
- `is_empty` matches missing keys, JSON `null`, empty arrays, and empty
  strings.
- Filters are applied before the search, so if fewer than `k` objects match,
  the result has fewer than `k` entries.

### Restricting the search targets

```python
hits = store.search([1.0, 0.0, 0.0, 0.0], 10, node_ids=["n1", "n2"])
```

`node_ids=[]` raises `ValueError`. To not restrict, pass `node_ids=None` (or
omit it). Unknown node IDs are ignored.

### Search strategies

A filtered search can choose how it runs via `strategy`.

```python
hits = store.search(query, 10, filter=filters, strategy="auto")
```

- `"auto"` (default): when the objects matching the filter (plus the
  `node_ids` restriction) number 10,000 or fewer, compute exact distances by
  brute force over the matches; otherwise run a filtered graph search. With
  low selectivity, graph traversal converges poorly and gets slow, so brute
  force is both faster and exact.
- `"inline"`: always the filtered graph search (bitmap checks during
  traversal).
- `"exact"`: always brute force.
- `"post"`: ignores the filter, gathers `post_candidates` (default 1000)
  candidates via graph search, and then matches them against the metadata.
  Skipping bitmap generation pays off the higher the match ratio is
  (1M benchmark: at a 15% match ratio, recall 0.996 and about 20x faster;
  at 1.4%, recall 0.71; at 0.015%, recall 0.015). Exactness is not
  guaranteed, and if fewer than `k` of the candidates match, the result has
  fewer than `k` entries. Use this only for queries known to have a high
  match ratio.

Unfiltered searches ignore the strategy and use the graph search. Brute-force
and graph search results agree except for the ordering of ties.

### Updates and fetches

```python
# Replace an existing node, or add a new one.
store.upsert("n1", [0.0, 0.0, 1.0, 0.0], {"category": "doc"})

# Replace multiple existing nodes. QG rebuilds at most once.
store.upsert_many(
    [
        ("n2", [0.0, 0.0, 0.0, 1.0], {"category": "doc"}),
        ("n4", [0.5, 0.5, 0.0, 0.0], {"category": "book"}),
    ]
)

node = store.get_node("n1")          # None if unknown
nodes = store.get_nodes(["n2", "n1", "missing"])  # input order, unknowns skipped
page = store.scan(eq("category", "book"), offset=0, limit=10)  # node ID order
```

`upsert_many` validates everything up front. However, if an insertion after a
removal fails, the pre-replacement data is not restored. Duplicate node IDs
within a batch are an error.

`Node` has `node_id` / `vector` / `metadata` / `metadata_json`. `vector` is
what NGT stores (normalized for normalized distances).

### Saving and clearing

```python
store.is_dirty          # whether unsaved changes or a pending build exist
store.flush()           # alias of save()
store.clear()           # delete all objects and persist the empty state
```

`clear()` keeps the dimension, index type, distance type, and creation
options.

### Removal

```python
store.remove_by_node_id("n1")          # unknown IDs are an error
removed = store.remove_by_node_ids(["n2", "n3"])  # unknown IDs are ignored
removed = store.remove_by_filter(eq("category", "book"))
```

QG rebuilds the whole index on removal; batch removals rebuild it only once.
QBG removals remain as tombstones, so `object_count` does not decrease.
Check `live_count` for the number of live entries.

### Index types

| Type | Characteristics |
| --- | --- |
| `Graph` | The standard NGT graph. The most straightforward for adds, removes, and filtered search. |
| `QG` | Quantized graph. Unfiltered search is quantized; filtered search uses the base graph. Removals rebuild everything. |
| `QBG` | Quantized blob graph. For large scales. Filters apply inside the two-step search. Removals are tombstones. |

### Distance types

| Value | `distance` in search results (smaller is closer) |
| --- | --- |
| `L2` | Euclidean distance |
| `Cosine` | `1 - cos(a, b)` |
| `NormalizedCosine` | `1 - dot(a, b)` (L2-normalized at insert and search) |
| `NormalizedL2` | `sqrt(2 - 2 * dot(a, b))` (L2-normalized at insert and search) |

`Cosine` / `NormalizedCosine` / `NormalizedL2` reject zero vectors. QBG's
`Cosine` is stored internally as `NormalizedCosine`.

## LlamaIndex integration

`ngtstore` itself does not depend on `llama_index`. Two optional modules for
LlamaIndex are provided.

- `ngtstore.llama_index` — filter translation and score conversion (no
  `llama_index` required)
- `ngtstore.llama_index_store` — an adapter implementing
  `BasePydanticVectorStore` (requires `llama-index-core`)

### Using the adapter

```python
from llama_index.core import StorageContext, VectorStoreIndex
from ngtstore import NgtStore
from ngtstore.llama_index_store import NgtVectorStore

store = NgtStore.open("./my-store")
adapter = NgtVectorStore(store)

storage = StorageContext.from_defaults(vector_store=adapter)
index = VectorStoreIndex(nodes, storage_context=storage)
```

Use `StorageContext.from_defaults(vector_store=adapter)`. The
`VectorStoreIndex(..., vector_store=adapter)` keyword is ignored.

The adapter stores `ref_doc_id` as the `doc_id` metadata key, so
`query.doc_ids` is searched as an `in` condition on `doc_id`, and
`delete(ref_doc_id)` removes by the same key. The key can be changed with
`NgtVectorStore(store, doc_id_key="source_id")`.

Because `stores_text=False`, node text is not stored in NGT-store.
Persistence is delegated to `adapter.persist()` (which calls `store.save()`).

### Using only the helpers

```python
from ngtstore.llama_index import distance_to_score, filters_from_llama_index

filters = filters_from_llama_index(
    metadata_filters,
    doc_ids=query.doc_ids,  # optional; empty means no restriction
)
hits = store.search(query_embedding, top_k, filter=filters)
similarities = [
    distance_to_score(hit.distance, store.distance_type) for hit in hits
]
```

`filters_from_llama_index()` reads `MetadataFilters` / `MetadataFilter` by
duck typing. It supports `==`, `!=`, `>`, `>=`, `<`, `<=`, `in`, `nin`,
`contains`, `text_match`, `text_match_insensitive`, `any`, `all`, and
`is_empty`; unknown operators raise `NotImplementedError`.

## C++ quick start

```cpp
#include <iostream>

#include "ngtstore/ngt_store.h"

int main() {
  using namespace ngtstore;

  IndexOptions options;
  options.type = IndexType::Graph;
  options.distanceType = DistanceType::Cosine;

  NgtStore::create("./my-store", 4, options);

  NgtStore store;
  store.open("./my-store", false);
  store.add("n1", {1.0f, 0.0f, 0.0f, 0.0f}, R"({"category":"book","price":1000})");
  store.add("n2", {0.0f, 1.0f, 0.0f, 0.0f}, R"({"category":"music","price":1500})");

  const Filter filter = allOf({eq("category", Value("book"))});
  for (const SearchHit& hit : store.search({1.0f, 0.0f, 0.0f, 0.0f}, 5, filter)) {
    std::cout << hit.nodeId << " " << hit.distance << "\n";
  }

  store.save();
  store.close();
}
```

Using it from CMake:

```cmake
add_subdirectory(path/to/NGT-store)
target_link_libraries(your_target PRIVATE ngtstore_ngt)
```

`ngtstore` is the metadata layer only; `ngtstore_ngt` includes the NGT
connection layer. Using the connection layer requires
`-DNGTSTORE_WITH_NGT=ON -DNGT_ROOT=...`.

The public API centers on `include/ngtstore/ngt_store.h` and
`include/ngtstore/filter.h`. `NgtIndex` / `SqliteMetadataStore` are internal.

## Tests

```sh
ctest --test-dir build --output-on-failure
```

To run only the Python tests:

```sh
PYTHONPATH=build/python python3 -m unittest discover -s tests/python -v
```

Tests against a real `llama-index-core` run in an environment with LlamaIndex
installed:

```sh
PYTHONPATH=build/python /path/to/venv/bin/python \
  -m unittest tests.python.test_llama_index -v
```

## Constraints

- A directory cannot be opened by multiple `NgtStore` instances at the same
  time.
- Concurrent searches on a single instance are not supported. Different
  stores can be used concurrently.
- Call `save()` explicitly. `close()` does not save.
- `add()` does not return the NGT Object ID. The user-facing key is
  `node_id`.
- `add()` errors on a duplicate `node_id`. Use `upsert()` / `upsert_many()`
  to replace.
- QBG only reranks the candidates found by quantized search, so recall
  depends on the quantized search.

## License

Apache License 2.0 — see [LICENSE](LICENSE). The vendored NGT
(`third_party/ngt` submodule) is also licensed under the Apache License 2.0.
