Metadata-Version: 2.4
Name: llama-index-vector-stores-ngt
Version: 0.2.0
Summary: LlamaIndex vector store integration for NGT (Neighborhood Graph and Tree)
Author-email: Masajiro Iwasaki <masajiro.iwasaki@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/NGT-labs/llama-index-vector-stores-ngt
Project-URL: Repository, https://github.com/NGT-labs/llama-index-vector-stores-ngt
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: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: llama-index-core>=0.10.0
Requires-Dist: ngtstore>=0.1.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

# llama-index-vector-stores-ngt

LlamaIndex vector store integration for [NGT](https://github.com/NGT-labs/NGT) (Neighborhood Graph and Tree), backed by **NGT-store**. NGT-store adds a metadata snapshot and pre-filtered search to NGT, so `MetadataFilters` are applied inside the vector search instead of being ignored.

## Installation

```bash
pip install llama-index-vector-stores-ngt
```

This pulls in [`ngtstore`](https://pypi.org/project/ngtstore/) (NGT with the filter API + metadata store) from PyPI automatically; no compiler, NGT source build, or `LD_LIBRARY_PATH` is needed.

## Requirements

- `llama-index-core>=0.10.0`
- `ngtstore>=0.1.0` ([PyPI](https://pypi.org/project/ngtstore/); manylinux wheels for cp39-cp313, x86_64 and aarch64)

`ngtstore` can also be built from source from the [NGT-store](https://github.com/masajiro/NGT-store) project when you need a newer version than PyPI provides:

```bash
git clone https://github.com/masajiro/NGT-store.git
cd NGT-store
cmake -S . -B build \
  -DNGTSTORE_WITH_NGT=ON \
  -DNGT_ROOT=/path/to/NGT \
  -DNGTSTORE_BUILD_PYTHON=ON
cmake --build build --parallel
export PYTHONPATH=/path/to/NGT-store/build/python:$PYTHONPATH
export LD_LIBRARY_PATH=/path/to/NGT/lib:$LD_LIBRARY_PATH
```

`NGT_ROOT` must point to an NGT build that includes the filter API; see the [NGT-store](https://github.com/masajiro/NGT-store) repository for the branch and build instructions.

`ngtpy` is **not** used. Existing `ngtpy` index directories cannot be opened by this version.

## Migration from 0.1

`0.2.0` replaces the `ngtpy` backend with NGT-store. This is a breaking change:

- The store layout is NGT-store's (`<index_path>/index` plus a metadata snapshot), not an `ngtpy` index directory.
- `distance_type` is limited to `L2`, `Cosine`, `NormalizedCosine`, and `NormalizedL2`.
- Metadata filters are now supported. Unsupported operators raise instead of being silently ignored.
- Adding an existing node ID replaces it (upsert), and `clear()`, `flush()`, `is_dirty`, and `get_nodes()` are available.
- The wrapper no longer writes `llamaindex_metadata.json`.

## Parameters

| Parameter | Default | Description |
| --- | --- | --- |
| `index_path` | required | Store directory. Created if it does not exist. |
| `dimension` | `None` | Embedding dimension. Required when creating; optional when opening. |
| `distance_type` | `"L2"` on create | `"L2"`, `"Cosine"`, `"NormalizedCosine"`, or `"NormalizedL2"`. Checked against the persisted value when opening. |
| `edge_size_for_creation` | `10` | NGT graph edge count used when building. Creation-time only. |
| `edge_size_for_search` | `40` | NGT graph edge count used when searching. Creation-time only. |
| `epsilon` | `0.1` | NGT search exploration range. `None` uses NGT's default. |
| `index_type` | `"graph"` on create | `"graph"`, `"qg"`, or `"qbg"`. |
| `filter_strategy` | `"auto"` | How filtered searches run: `"pre"`, `"inline"`, `"post"`, or `"auto"` (see below). |
| `post_candidates` | `1000` | Candidate count for `filter_strategy="post"`. |
| `stores_text` | `True` | Store node text/relationships and return nodes. Set `False` to return IDs only (see below). |
| `read_only` | `False` | Open the store read-only initially. NGT-store switches to writable on the first write. |

`add()` is an upsert: a node whose `id_` already exists is replaced. Adding the same ID twice in one call keeps the last node. Writes go through NGT-store's `upsert_many()`, `clear()`, and `flush()`, so the adapter does not manipulate the store directory.

## Usage

```python
from llama_index.core import StorageContext, VectorStoreIndex
from llama_index.core.schema import TextNode
from llama_index.vector_stores.ngt import NGTVectorStore

vector_store = NGTVectorStore(
    index_path="ngt_store",
    dimension=128,
    distance_type="L2",
)

storage_context = StorageContext.from_defaults(vector_store=vector_store)
nodes = [
    TextNode(text="apple is red and sweet", metadata={"category": "fruit"}),
    TextNode(text="banana is yellow and sweet", metadata={"category": "fruit"}),
]

index = VectorStoreIndex(nodes, storage_context=storage_context)
results = index.as_retriever(similarity_top_k=2).retrieve("yellow fruit")

for node in results:
    print(node.score, node.text)
```

The embedding is computed by `Settings.embed_model` when a node has no embedding.

## Metadata filtering

Filters are converted to NGT-store's filter AST and evaluated against the metadata snapshot before the graph search:

```python
from llama_index.core.vector_stores.types import (
    FilterCondition,
    FilterOperator,
    MetadataFilter,
    MetadataFilters,
)

filters = MetadataFilters(
    filters=[
        MetadataFilter(key="category", value="fruit"),
        MetadataFilter(key="price", value=100, operator=FilterOperator.LTE),
    ],
    condition=FilterCondition.AND,
)

results = index.as_retriever(
    similarity_top_k=5,
    filters=filters,
).retrieve("sweet yellow fruit")
```

Supported operators: `==`, `!=`, `>`, `>=`, `<`, `<=`, `in`, `nin`, `contains`, `any`, `all`, `text_match`, `text_match_insensitive`, `is_empty`. Supported conditions: `AND`, `OR`, `NOT`, and nested `MetadataFilters`.

`text_match` is case-sensitive. `text_match_insensitive` folds ASCII letters only; non-ASCII case folding is not supported.

Filters become a single SQL query against the metadata snapshot that produces the bitmap NGT uses to restrict graph traversal (pre-filtering, not post-filtering). If fewer than `similarity_top_k` nodes match, fewer results are returned.

Unsupported operators raise `NotImplementedError`; unsupported query modes raise `ValueError`. Filters are never silently dropped.

## Filtered-search strategies

`filter_strategy` selects how a filtered query runs (also available per query via `vector_store.query(query, filter_strategy=...)`):

| Strategy | How it works | When it wins |
| --- | --- | --- |
| `"pre"` (pre-filter) | Filter bitmap, then exact brute force over the matches | Low selectivity. In the 1M-vector benchmark the crossover against the graph search was around 10k-20k matches. Always exact. |
| `"inline"` (inline-filter) | Bitmap evaluated during the NGT graph traversal | High selectivity. The filtered graph traversal itself; approximate, but no extra candidates step. |
| `"post"` (post-filter) | Unfiltered graph search fetching `post_candidates` (default 1000) objects, then one batched metadata check | Highest selectivity. 1M benchmark: recall 0.996 at 15% matches, 0.71 at 1.4%, 0.015 at 0.015%. **Not exact** and may return fewer than `k` results; use only when the filter admits most objects. |
| `"auto"` (default) | `"pre"` when the filter (plus the `node_ids` restriction) admits at most 10,000 objects, `"inline"` otherwise | Sensible default. |

Aliases: `pre_filter`, `inline_filter`, `post_filter`, and ngtstore's `exact` (= `pre`) are accepted. Unfiltered searches ignore the strategy and always use the graph search. The exact scan and the graph search may order equal-distance ties differently.

```python
result = vector_store.query(query, filter_strategy="post", post_candidates=500)
```

## Query options

- `similarity_top_k`: passed to `as_retriever()` / `as_query_engine()`.
- `node_ids` and `doc_ids`: restrict the search to specific nodes or documents.
- `epsilon`: pass `epsilon=` directly to `vector_store.query()` to override the store default.
- `filter_strategy` / `post_candidates`: per-query overrides of the filtered-search strategy (see above).
- `edge_size`: per-query overrides are not supported; set `edge_size_for_search` when creating the store.

## Delete

```python
# Delete every node whose ref_doc_id is "doc-1".
vector_store.delete("doc-1")

# Delete by node ID or metadata filter.
vector_store.delete_nodes(node_ids=["node-1", "node-2"])
vector_store.delete_nodes(filters=MetadataFilters(
    filters=[MetadataFilter(key="category", value="fruit")]
))
```

`VectorStoreIndex.delete_ref_doc()` and `VectorStoreIndex.delete_nodes()` use these methods.

To remove every node while keeping the creation options and distance type, call `vector_store.clear()`. NGT-store saves the empty state before returning.

## Reading nodes back

`get_nodes()` maps to NGT-store's node access APIs:

```python
# By ID. Unknown IDs are skipped and the input order is preserved.
nodes = vector_store.get_nodes(node_ids=["node-1", "node-2"])

# By metadata filters.
filters = MetadataFilters(filters=[MetadataFilter(key="category", value="fruit")])
nodes = vector_store.get_nodes(filters=filters)

# Both: the intersection.
nodes = vector_store.get_nodes(node_ids=["node-1", "node-2"], filters=filters)

# No arguments: scan every node. This can be expensive.
all_nodes = vector_store.get_nodes()
```

With `stores_text=True` the returned nodes are fully restored. With `stores_text=False` they have empty text and only the stored metadata.

`live_count`, `object_count`, and `is_dirty` expose NGT-store's counters; `flush()` saves pending changes to `index_path`.

## Persistence

The store owns `index_path`. `persist()` with no argument saves in place:

```python
vector_store.persist()
```

`persist_dir` copies the saved store to another directory. The target must be empty or non-existent:

```python
vector_store.persist(persist_dir="ngt_store_copy")
```

Reopen the copy without repeating the dimension or distance type:

```python
vector_store = NGTVectorStore.from_persist_dir("ngt_store_copy")
```

`persist_path` follows LlamaIndex's `StorageContext.persist()` convention and is a `*.json` descriptor. The store data remains in `index_path`; only the descriptor is written. To persist a `StorageContext` together with the store data, copy the store first and pass the reopened store explicitly when loading:

```python
from llama_index.core import StorageContext

storage = StorageContext.from_defaults(vector_store=vector_store)
vector_store.persist(persist_dir="ngt_persist")
storage.persist(persist_dir="ngt_persist")

# Later:
vector_store = NGTVectorStore.from_persist_dir("ngt_persist")
storage = StorageContext.from_defaults(
    vector_store=vector_store,
    persist_dir="ngt_persist",
)
```

LlamaIndex does not auto-discover custom vector stores. `StorageContext.persist()` writes this store's descriptor to `default__vector_store.json`, and a naive `StorageContext.from_defaults(persist_dir=...)` will try to parse that file as a `SimpleVectorStore` and silently end up with an empty in-memory store. Always pass `vector_store=` explicitly when reloading. `NGTVectorStore.from_dict()` / `to_dict()` are available for custom loaders.

## `stores_text=False`

By default the adapter stores node text and relationships in the metadata snapshot and returns fully populated nodes. This allows `VectorStoreIndex.from_vector_store()` to work without a docstore.

Set `stores_text=False` to store only filterable metadata and `ref_doc_id`; queries then return `ids` and `similarities` only, and LlamaIndex hydrates nodes from its docstore. In that mode `VectorStoreIndex.from_vector_store()` raises because LlamaIndex requires `stores_text=True`; construct the index with a `StorageContext` instead. `get_nodes()` still works but returns `TextNode`s with empty text and the stored metadata.

## Notes and limitations

- Metadata must be JSON-serializable (`NaN`/`Infinity` are rejected).
- `a.b`-style nested metadata keys are treated as literal keys.
- `add()` accepts duplicate IDs (last wins), but a single `upsert_many()` chunk must not contain duplicates; the adapter deduplicates before writing.
- Deletes and upserts are not atomic: a failure part-way through a batch leaves earlier changes in place.
- A single NGT-store instance serializes writes and searches. For concurrent read services, open separate read-only instances.
- Filtering scans the metadata snapshot once per query; measure at your target scale. Selectivity helps the graph search, not the metadata scan.
