FalkorDB
haystack_integrations.components.retrievers.falkordb.cypher_retriever
FalkorDBCypherRetriever
A power-user retriever for executing arbitrary OpenCypher queries against FalkorDB.
This retriever allows you to leverage graph traversal and multi-hop queries in
GraphRAG pipelines. The query must return nodes or dictionaries that can be
mapped exactly to a Haystack Document.
Security Warning: Raw Cypher queries must only come from trusted sources. Do
not use un-sanitised user input directly in query strings. Use parameters instead.
Usage example:
from haystack_integrations.document_stores.falkordb import FalkorDBDocumentStore
from haystack_integrations.components.retrievers.falkordb import FalkorDBCypherRetriever
store = FalkorDBDocumentStore(host="localhost", port=6379)
retriever = FalkorDBCypherRetriever(
document_store=store,
custom_cypher_query="MATCH (d:Document)-[:RELATES_TO]->(:Concept {name: $concept}) RETURN d"
)
res = retriever.run(parameters={"concept": "GraphRAG"})
print(res["documents"])
init
__init__(
document_store: FalkorDBDocumentStore,
custom_cypher_query: str | None = None,
) -> None
Create a new FalkorDBCypherRetriever.
Parameters:
- document_store (
FalkorDBDocumentStore) – The FalkorDBDocumentStore instance. - custom_cypher_query (
str | None) – A static OpenCypher query to execute. Can be overridden at runtime by passingquerytorun().
Raises:
ValueError– If the provideddocument_storeis not aFalkorDBDocumentStore.
to_dict
Serialise the retriever to a dictionary.
Returns:
dict[str, Any]– Dictionary representation of the retriever.
from_dict
Deserialise a FalkorDBCypherRetriever produced by to_dict.
Parameters:
- data (
dict[str, Any]) – Serialised retriever dictionary.
Returns:
FalkorDBCypherRetriever– ReconstructedFalkorDBCypherRetrieverinstance.
run
run(
query: str | None = None, parameters: dict[str, Any] | None = None
) -> dict[str, list[Document]]
Retrieve documents by executing an OpenCypher query.
If a query is provided here, it overrides the custom_cypher_query
set during initialisation.
Parameters:
- query (
str | None) – Optional OpenCypher query string. - parameters (
dict[str, Any] | None) – Optional dictionary of query parameters (referenced as$param_namein the Cypher string).
Returns:
dict[str, list[Document]]– Dictionary containing a"documents"key with the retrieved documents.
Raises:
ValueError– If no query string is provided (both here and at init).
run_async
run_async(
query: str | None = None, parameters: dict[str, Any] | None = None
) -> dict[str, list[Document]]
Retrieve documents asynchronously by executing an OpenCypher query.
If a query is provided here, it overrides the custom_cypher_query
set during initialisation.
Parameters:
- query (
str | None) – Optional OpenCypher query string. - parameters (
dict[str, Any] | None) – Optional dictionary of query parameters (referenced as$param_namein the Cypher string).
Returns:
dict[str, list[Document]]– Dictionary containing a"documents"key with the retrieved documents.
Raises:
ValueError– If no query string is provided (both here and at init).
close
Release the synchronous resources of the underlying Document Store.
close_async
Release the asynchronous resources of the underlying Document Store.
haystack_integrations.components.retrievers.falkordb.embedding_retriever
FalkorDBEmbeddingRetriever
A component for retrieving documents from a FalkorDBDocumentStore using vector similarity.
The retriever uses FalkorDB's native vector search index to find documents whose embeddings are most similar to the provided query embedding.
Usage example:
from haystack.dataclasses import Document
from haystack_integrations.document_stores.falkordb import FalkorDBDocumentStore
from haystack_integrations.components.retrievers.falkordb import FalkorDBEmbeddingRetriever
store = FalkorDBDocumentStore(host="localhost", port=6379)
store.write_documents([
Document(content="GraphRAG is powerful.", embedding=[0.1, 0.2, 0.3]),
Document(content="FalkorDB is fast.", embedding=[0.8, 0.9, 0.1]),
])
retriever = FalkorDBEmbeddingRetriever(document_store=store)
res = retriever.run(query_embedding=[0.1, 0.2, 0.3])
print(res["documents"][0].content) # "GraphRAG is powerful."
init
__init__(
document_store: FalkorDBDocumentStore,
filters: dict[str, Any] | None = None,
top_k: int = 10,
filter_policy: FilterPolicy = FilterPolicy.REPLACE,
) -> None
Create a new FalkorDBEmbeddingRetriever.
Parameters:
- document_store (
FalkorDBDocumentStore) – The FalkorDBDocumentStore instance. - filters (
dict[str, Any] | None) – Optional Haystack filters to narrow down the search space. - top_k (
int) – Maximum number of documents to retrieve. - filter_policy (
FilterPolicy) – Policy to determine how runtime filters are combined with initialization filters.
Raises:
ValueError– If the provideddocument_storeis not aFalkorDBDocumentStore.
to_dict
Serialise the retriever to a dictionary.
Returns:
dict[str, Any]– Dictionary representation of the retriever.
from_dict
Deserialise a FalkorDBEmbeddingRetriever produced by to_dict.
Parameters:
- data (
dict[str, Any]) – Serialised retriever dictionary.
Returns:
FalkorDBEmbeddingRetriever– ReconstructedFalkorDBEmbeddingRetrieverinstance.
run
run(
query_embedding: list[float],
filters: dict[str, Any] | None = None,
top_k: int | None = None,
) -> dict[str, list[Document]]
Retrieve documents by vector similarity.
Parameters:
- query_embedding (
list[float]) – Query embedding vector. - filters (
dict[str, Any] | None) – Optional Haystack filters to be combined with the init filters based on the configured filter policy. - top_k (
int | None) – Maximum number of documents to return. If not provided, the default top_k from initialization is used.
Returns:
dict[str, list[Document]]– Dictionary containing a"documents"key with the retrieved documents.
run_async
run_async(
query_embedding: list[float],
filters: dict[str, Any] | None = None,
top_k: int | None = None,
) -> dict[str, list[Document]]
Retrieve documents asynchronously by vector similarity.
Parameters:
- query_embedding (
list[float]) – Query embedding vector. - filters (
dict[str, Any] | None) – Optional Haystack filters to be combined with the init filters based on the configured filter policy. - top_k (
int | None) – Maximum number of documents to return. If not provided, the default top_k from initialization is used.
Returns:
dict[str, list[Document]]– Dictionary containing a"documents"key with the retrieved documents.
close
Release the synchronous resources of the underlying Document Store.
close_async
Release the asynchronous resources of the underlying Document Store.
haystack_integrations.components.retrievers.falkordb.text_to_cypher_retriever
FalkorDBTextToCypherRetriever
Retrieve documents from FalkorDB using natural-language queries and a chat generator.
The generator translates the user query into read-only Cypher using a sampled graph schema
cached during warm-up. Configure it for structured output using RESPONSE_SCHEMA. Query results
must return document nodes or mappings in the first column.
Schema sampling may miss rare patterns; close and warm up again to refresh it after graph changes.
The user query and schema are sent to the generator's provider. Read-only queries can still expose
sensitive data or be expensive: use least-privilege access and recreate_graph=False for existing graphs.
Usage example
from haystack import Document
from haystack.components.generators.chat import OpenAIResponsesChatGenerator
from haystack_integrations.document_stores.falkordb import FalkorDBDocumentStore
from haystack_integrations.components.retrievers.falkordb import FalkorDBTextToCypherRetriever
store = FalkorDBDocumentStore()
store.write_documents([Document(content="Haystack supports GraphRAG")])
generator = OpenAIResponsesChatGenerator(generation_kwargs={
"text": {
"format": {
"type": "json_schema",
"name": "cypher_query",
"strict": True,
"schema": FalkorDBTextToCypherRetriever.RESPONSE_SCHEMA,
},
}
})
retriever = FalkorDBTextToCypherRetriever(
document_store=store,
chat_generator=generator,
schema_sample_size=100,
)
result = retriever.run(query="Find documents mentioning GraphRAG")
print(result["documents"]) # Documents matching the generated query
init
__init__(
document_store: FalkorDBDocumentStore,
chat_generator: ChatGenerator,
*,
schema_sample_size: int = 100,
top_k: int = 10,
timeout: int | None = None,
system_prompt: str | None = None
) -> None
Initialize the retriever without opening connections.
Parameters:
- document_store (
FalkorDBDocumentStore) – Store against which generated read-only queries are executed. - chat_generator (
ChatGenerator) – Haystack chat generator configured forRESPONSE_SCHEMAstructured output. - schema_sample_size (
int) – Positive number of nodes sampled per label and of relationships sampled per type at warm-up. - top_k (
int) – Positive maximum number of unique documents to return. The generator is asked to add a matchingLIMIT, and results are deduplicated by document ID and truncated in case it does not. - timeout (
int | None) – Positive maximum query runtime in milliseconds, enforced by the FalkorDB server;Noneuses the server default. Bounds the cost of expensive generated queries, whichtop_kalone cannot. - system_prompt (
str | None) – Template for the system prompt sent to the generator;NoneusesDEFAULT_SYSTEM_PROMPT. Must contain a{graph_schema}placeholder, which is replaced with the sampled graph schema as JSON at warm-up. Other braces are kept as-is, so Cypher examples need no escaping. ALIMITinstruction based ontop_kis appended on every run.
Raises:
ValueError–document_storeis not aFalkorDBDocumentStore,schema_sample_size,top_k, ortimeoutis not positive, orsystem_promptlacks the{graph_schema}placeholder.
warm_up
Warm up the chat generator, then discover the sampled graph schema and cache the system prompt once.
Called lazily by run().
warm_up_async
Warm up the chat generator, then discover the sampled graph schema asynchronously and cache the prompt once.
Called lazily by run_async(). Uses the generator's warm_up_async() when available, otherwise
its warm_up(). Concurrent async calls share a single schema discovery.
close
Clear the cached prompt and release the document store's synchronous resources.
The next warm-up discovers the schema again. The caller owns the generator's lifecycle.
close_async
Clear the cached prompt and release the document store's asynchronous resources.
The next warm-up discovers the schema again. The caller owns the generator's lifecycle.
to_dict
Serialize the retriever and its nested components.
Returns:
dict[str, Any]– Dictionary containing the component type and constructor parameters.
from_dict
Deserialize the retriever using Haystack's generator deserialization allowlist.
Parameters:
- data (
dict[str, Any]) – Serialized component dictionary.
Returns:
FalkorDBTextToCypherRetriever– Reconstructed retriever.
run
Generate a Cypher query and execute it through FalkorDB's read-only command.
Graph traversal can be expensive even when the query returns few documents.
Parameters:
- query (
str) – Natural-language retrieval request. - top_k (
int | None) – Positive maximum number of unique documents to return; overrides the init value.
Returns:
dict[str, list[Document]]– Mapping withdocuments(list of at mosttop_kunique retrieved Documents).
Raises:
ValueError–top_kis not positive, or the generator reply violates the structured-output contract.DocumentStoreError– Database retrieval or document conversion fails, or the query exceedstimeout.
run_async
Generate and execute a read-only Cypher query asynchronously.
Warms up lazily and reuses the cached schema. Database operations use native async I/O. Generators
without run_async() run in a worker thread; cancelling the await does not stop that thread.
Graph traversal can be expensive even when few documents are returned.
Parameters:
- query (
str) – Natural-language retrieval request. - top_k (
int | None) – Positive maximum number of unique documents to return; overrides the init value.
Returns:
dict[str, list[Document]]– Mapping withdocuments(list of at mosttop_kunique retrieved Documents).
Raises:
ValueError–top_kis not positive, or the generator reply violates the structured-output contract.DocumentStoreError– Database retrieval or document conversion fails, or the query exceedstimeout.
haystack_integrations.document_stores.falkordb.document_store
FalkorDBDocumentStore
Bases: DocumentStore
A Haystack DocumentStore backed by FalkorDB — a high-performance graph database.
Optimised for GraphRAG workloads.
Documents are stored as graph nodes (labelled Document by default) in a named
FalkorDB graph. Document properties, including meta fields, are stored
flat at the same level as id and content — exactly the same layout as
the neo4j-haystack reference integration.
Vector search is performed via FalkorDB's native vector index —
no APOC is required. All bulk writes use UNWIND + MERGE for safe,
idiomatic OpenCypher upserts.
Usage example:
from haystack_integrations.document_stores.falkordb import FalkorDBDocumentStore
from haystack.dataclasses import Document
store = FalkorDBDocumentStore(host="localhost", port=6379)
store.write_documents([
Document(content="Hello, GraphRAG!", meta={"year": 2024}),
])
print(store.count_documents()) # 1
init
__init__(
*,
host: str = "localhost",
port: int = 6379,
graph_name: str = "haystack",
username: str | None = None,
password: Secret | None = None,
node_label: str = "Document",
embedding_dim: int = 768,
embedding_field: str = "embedding",
similarity: SimilarityFunction = "cosine",
write_batch_size: int = 100,
recreate_graph: bool = False,
verify_connectivity: bool = False
) -> None
Create a new FalkorDBDocumentStore.
Parameters:
- host (
str) – Hostname of the FalkorDB server. - port (
int) – Port the FalkorDB server listens on. - graph_name (
str) – Name of the FalkorDB graph to use. Each graph is an isolated namespace. - username (
str | None) – Optional username for FalkorDB authentication. - password (
Secret | None) – Optional :class:haystack.utils.Secretholding the FalkorDB password. The secret value is resolved lazily on first connection. - node_label (
str) – Label used for document nodes in the graph. - embedding_dim (
int) – Dimensionality of the vector embeddings. Used when creating the vector index. - embedding_field (
str) – Name of the node property that stores the embedding vector. - similarity (
SimilarityFunction) – Similarity function for the vector index. Accepted values are"cosine"and"euclidean". - write_batch_size (
int) – Number of documents written perUNWINDbatch. - recreate_graph (
bool) – WhenTruethe existing graph (and all its data) is dropped and recreated on initialisation. Useful for tests. - verify_connectivity (
bool) – WhenTruea connectivity probe is run immediately in__init__— raises if the server is unreachable.
Raises:
ValueError– Ifsimilarityis not"cosine"or"euclidean".
to_dict
Serialise the store to a dictionary suitable for from_dict.
Returns:
dict[str, Any]– Dictionary representation of the store.
from_dict
Deserialise a FalkorDBDocumentStore produced by to_dict.
Parameters:
- data (
dict[str, Any]) – Serialised store dictionary.
Returns:
FalkorDBDocumentStore– ReconstructedFalkorDBDocumentStoreinstance.
close
Release the associated synchronous resources.
close_async
Release the associated asynchronous resources.
warm_up
Lazily open the FalkorDB connection and set up the graph schema.
Called at the start of every public method so the store remains serialisable without an active database connection.
warm_up_async
Lazily open the asynchronous FalkorDB connection and set up the graph schema.
Called at the start of every asynchronous public method so the store remains serialisable without an active database connection.
count_documents
Return the number of documents currently stored in the graph.
Returns:
int– Integer count of document nodes.
filter_documents
Retrieve all documents that match the provided Haystack filters.
Parameters:
- filters (
dict[str, Any] | None) – Optional Haystack filter dict. WhenNoneall documents are returned. For filter syntax see Metadata filtering
Returns:
list[Document]– List of matching :class:haystack.dataclasses.Documentobjects.
Raises:
FilterError– If the filter dict is malformed.
write_documents
write_documents(
documents: list[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE
) -> int
Write documents to the FalkorDB graph using UNWIND + MERGE for batching.
Document meta fields are stored flat at the same level as id and
content — no prefix is added. This matches the layout used by the
neo4j-haystack reference integration.
Parameters:
- documents (
list[Document]) – List of :class:haystack.dataclasses.Documentobjects. - policy (
DuplicatePolicy) – How to handle documents whoseidalready exists. Defaults to :attr:DuplicatePolicy.NONE(treated as FAIL).
Returns:
int– Number of documents written or updated.
Raises:
ValueError– Ifdocumentscontains non-Document elements.DuplicateDocumentError– Ifpolicyis FAIL / NONE and a duplicate ID is encountered.DocumentStoreError– If any other DB error occurs.
delete_documents
Delete documents by their IDs using a single UNWIND-based query.
Parameters:
- document_ids (
list[str]) – List of document IDs to remove from the graph.
delete_all_documents
Delete all documents from the graph.
delete_by_filter
Delete all documents that match the provided filters.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict.
Returns:
int– Number of documents deleted.
update_by_filter
Update metadata fields on all documents that match the provided filters.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict selecting which documents to update. - meta (
dict[str, Any]) – Metadata fields to set. Keys may include or omit themeta.prefix.
Returns:
int– Number of documents updated.
count_documents_by_filter
Return the number of documents that match the provided filters.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict.
Returns:
int– Integer count of matching document nodes.
count_unique_metadata_by_filter
count_unique_metadata_by_filter(
filters: dict[str, Any], metadata_fields: list[str]
) -> dict[str, int]
Return the number of unique values for each metadata field among matching documents.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict. Pass an empty dict to count across all documents. - metadata_fields (
list[str]) – List of metadata field names. May include or omit themeta.prefix.
Returns:
dict[str, int]– Dict mapping each field name (withoutmeta.prefix) to its unique value count.
get_metadata_fields_info
Return type information for each metadata field present on document nodes.
Returns:
dict[str, dict[str, str]]– Dict mapping field names to a{"type": <typename>}dict. Type names are"str","int","float", or"bool".
get_metadata_field_min_max
Return the minimum and maximum values for the given metadata field.
Parameters:
- metadata_field (
str) – Metadata field name. May include or omit themeta.prefix.
Returns:
dict[str, Any]– Dict with keys"min"and"max". Values areNonewhen no documents have a non-null value for the field.
get_metadata_field_unique_values
get_metadata_field_unique_values(
metadata_field: str,
search_term: str | None = None,
from_: int = 0,
size: int = 10,
filters: dict[str, Any] | None = None,
) -> tuple[list[Any], int]
Return distinct values for the given metadata field with optional filtering and pagination.
Note: values of different types are kept distinct even when they compare equal in Python
(e.g. the int 1, the bool True and the str "1" are returned as three separate values), with
one exception: Cypher's DISTINCT treats a whole-number float (e.g. 1.0) as identical to a
numerically equal int (1), so those two collapse into a single value. Floats with a fractional
part (e.g. 1.5) are unaffected.
Parameters:
- metadata_field (
str) – Metadata field name. May include or omit themeta.prefix. - search_term (
str | None) – Optional case-insensitive substring filter applied to the metadata field's own value. - from_ (
int) – The offset for pagination (0-based). - size (
int) – Maximum number of values to return per page. Defaults to 10. - filters (
dict[str, Any] | None) – Optional filters to restrict the documents considered.
Returns:
tuple[list[Any], int]– Tuple of(values, total_count). Values are returned in their original type.total_countis the number of distinct values matching the filter, independent of pagination.
count_documents_async
Return the number of documents currently stored in the graph asynchronously.
Returns:
int– Integer count of document nodes.
filter_documents_async
Retrieve all documents that match the provided Haystack filters asynchronously.
Parameters:
- filters (
dict[str, Any] | None) – Optional Haystack filter dict. WhenNoneall documents are returned. For filter syntax see Metadata filtering
Returns:
list[Document]– List of matching Documents.
Raises:
FilterError– If the filter dict is malformed.
write_documents_async
write_documents_async(
documents: list[Document], policy: DuplicatePolicy = DuplicatePolicy.NONE
) -> int
Write documents to the FalkorDB graph asynchronously using UNWIND + MERGE for batching.
Document meta fields are stored flat at the same level as id and
content — no prefix is added. This matches the layout used by the
neo4j-haystack reference integration.
Parameters:
- documents (
list[Document]) – List of :class:haystack.dataclasses.Documentobjects. - policy (
DuplicatePolicy) – How to handle documents whoseidalready exists. Defaults to :attr:DuplicatePolicy.NONE(treated as FAIL).
Returns:
int– Number of documents written or updated.
Raises:
ValueError– Ifdocumentscontains non-Document elements.DuplicateDocumentError– Ifpolicyis FAIL / NONE and a duplicate ID is encountered.DocumentStoreError– If any other DB error occurs.
delete_documents_async
Delete documents by their IDs asynchronously.
Parameters:
- document_ids (
list[str]) – List of document IDs to remove from the graph.
delete_all_documents_async
Delete all documents from the graph asynchronously.
delete_by_filter_async
Delete all documents that match the provided filters asynchronously.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict.
Returns:
int– Number of documents deleted.
update_by_filter_async
Update metadata fields on matching documents asynchronously.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict selecting which documents to update. - meta (
dict[str, Any]) – Metadata fields to set. Keys may include or omit themeta.prefix.
Returns:
int– Number of documents updated.
count_documents_by_filter_async
Return the number of documents that match the provided filters asynchronously.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict.
Returns:
int– Integer count of matching document nodes.
count_unique_metadata_by_filter_async
count_unique_metadata_by_filter_async(
filters: dict[str, Any], metadata_fields: list[str]
) -> dict[str, int]
Return the number of unique values for each metadata field among matching documents asynchronously.
Parameters:
- filters (
dict[str, Any]) – Haystack filter dict. Pass an empty dict to count across all documents. - metadata_fields (
list[str]) – List of metadata field names. May include or omit themeta.prefix.
Returns:
dict[str, int]– Dict mapping each field name (withoutmeta.prefix) to its unique value count.
get_metadata_fields_info_async
Return type information for each metadata field present on document nodes asynchronously.
Returns:
dict[str, dict[str, str]]– Dict mapping field names to a{"type": <typename>}dict. Type names are"str","int","float", or"bool".
get_metadata_field_min_max_async
Return the minimum and maximum values for the given metadata field asynchronously.
Parameters:
- metadata_field (
str) – Metadata field name. May include or omit themeta.prefix.
Returns:
dict[str, Any]– Dict with keys"min"and"max". Values areNonewhen no documents have a non-null value for the field.
get_metadata_field_unique_values_async
get_metadata_field_unique_values_async(
metadata_field: str,
search_term: str | None = None,
from_: int = 0,
size: int = 10,
filters: dict[str, Any] | None = None,
) -> tuple[list[Any], int]
Return distinct values for the given metadata field with optional filtering and pagination asynchronously.
Note: values of different types are kept distinct even when they compare equal in Python
(e.g. the int 1, the bool True and the str "1" are returned as three separate values), with
one exception: Cypher's DISTINCT treats a whole-number float (e.g. 1.0) as identical to a
numerically equal int (1), so those two collapse into a single value. Floats with a fractional
part (e.g. 1.5) are unaffected.
Parameters:
- metadata_field (
str) – Metadata field name. May include or omit themeta.prefix. - search_term (
str | None) – Optional case-insensitive substring filter applied to the metadata field's own value. - from_ (
int) – The offset for pagination (0-based). - size (
int) – Maximum number of values to return per page. Defaults to 10. - filters (
dict[str, Any] | None) – Optional filters to restrict the documents considered.
Returns:
tuple[list[Any], int]– Tuple of(values, total_count). Values are returned in their original type.total_countis the number of distinct values matching the filter, independent of pagination.