Skip to main content

llama-index-vector-stores-ngt

LlamaIndex vector store integration for 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

pip install llama-index-vector-stores-ngt

This pulls in 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; manylinux wheels for cp39-cp313, x86_64 and aarch64)

ngtstore can also be built from source from the NGT-store project when you need a newer version than PyPI provides:

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

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:

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.

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

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

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

vector_store.persist()

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

vector_store.persist(persist_dir="ngt_store_copy")

Reopen the copy without repeating the dimension or distance type:

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:

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 TextNodes 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.

Metadata

Release files for llama-index-vector-stores-ngt 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for llama-index-vector-stores-ngt 0.2.0
File Size Uploaded Provenance Actions
llama_index_vector_stores_ngt-0.2.0.tar.gz 14.0 kB Without provenance Details for llama_index_vector_stores_ngt-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for llama-index-vector-stores-ngt 0.2.0
File Interpreter ABI Platform Actions
llama_index_vector_stores_ngt-0.2.0-py3-none-any.whl Python 3 none any Details for llama_index_vector_stores_ngt-0.2.0-py3-none-any.whl

Total release size: 29.0 kB

Release files / llama_index_vector_stores_ngt-0.2.0.tar.gz

Download URL llama_index_vector_stores_ngt-0.2.0.tar.gz
Size 14.0 kB
Tags Source
SHA-256 checksum
How to use checksums
011abbbdd0daf608d2a27c20bbcf1039ee740966ee18eca564d8753b79d581e7
BLAKE2b-256 checksum
How to use checksums
f3c31ca884178ca30161b289380b9768958e70015e52a51c2fb091ae5e75bc14
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Release files / llama_index_vector_stores_ngt-0.2.0-py3-none-any.whl

Download URL llama_index_vector_stores_ngt-0.2.0-py3-none-any.whl
Size 15.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
13272ca586d31e06f0d5e1b7d9e92b0114e6bce79d7168278e30c8e18a2bb988
BLAKE2b-256 checksum
How to use checksums
7f1d46dea99f74b9f8cd0b692a2cd6dd285770068e4b62fa54173f17e70f6c87
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Security for llama-index-vector-stores-ngt 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page