Skip to main content

Adding a New Vector Store to cognee

This guide describes how to integrate a new vector database engine into cognee, following the same pattern used for existing engines (e.g., Weaviate, Qdrant, Milvus, PGVector, LanceDB).

Repository Options

Cognee used both the core and the community repositories to host vector-database adapters. 🚨 From now on every vector-database adapter – except LanceDB – will live in the cognee-community repository. Qdrant have already been migrated from the core library and the remaining adapters will follow shortly. You can find Redis, OpenSearch, and Azure AI Search integrations available in the community repo. Therefore all new adapter contributions must target the community repository.
The core repository will keep only the built-in LanceDB integration.

For Community Repository

To add a new adapter to cognee-community:
  1. Fork and clone the cognee-community repository, and branch from main — unlike the core Cognee repo, cognee-community has no dev branch.
  2. Create your adapter in packages/vector/<engine_name>/cognee_community_vector_adapter_<engine_name>/
  3. Inside that directory add __init__.py, <engine_name>_adapter.py, and register.py (see the Redis implementation as an example).
  4. At the package root packages/<engine_name>/ add __init__.py, pyproject.toml, and README.md.
  5. Run the shared vector conformance suite in packages/shared/contract_suite/vector_contract.py against your adapter.
  6. Submit a pull request to the community repository
Below are the recommended steps in more detail.

Why cognee-community?

cognee-community is the extension hub for Cognee.
Anything that is not part of the core lives here—adapters for third-party databases, pipelines, community contributed additional tasks, etc.
Placing your adapter in this repository means:
  • Your code is released under the community license and can evolve independently of the core.
  • It can be installed with pip install cognee-community-vector-adapter-(engine_name) without pulling in heavyweight drivers for users who don’t need them. For example, for Qdrant it is pip install cognee-community-vector-adapter-qdrant
  • These packages can be called with the cognee core package using the registration step described below.
If you are unfamiliar with the layout, have a look at the existing folders under packages/* in the community repo—each sub-folder represents a separate provider implemented in exactly the way you are about to do.

1. Implement the Adapter

File: packages/vector/<engine_name>/cognee_community_vector_adapter_<engine_name>/<engine_name>_adapter.py Your adapter must implement the VectorDBInterface protocol, implementing all required methods for collection management, data point operations, and search functionality. Here is a sample skeleton with placeholders:
Keep the method signatures consistent with VectorDBInterface. Reference the existing adapters like QDrantAdapter for more comprehensive examples.

What Cognee passes your constructor

Cognee never instantiates your adapter directly — the vector engine factory (create_vector_engine) does, resolving your class out of the registry by the provider name you passed to use_vector_adapter. It calls your __init__ with these keyword arguments, all by keyword, never positionally: Apart from embedding_engine, every value above comes from user configuration — set through config.set_vector_db_config({...}) or the matching VECTOR_DB_* environment variables. See the community adapters overview. Two normalization details to code against:
  • vector_db_port arrives as a string, not an int. Numeric values are stringified before forwarding. It also defaults to 1234 in VectorConfig, so you receive vector_db_port="1234" even when the user never configured a port — don’t treat a truthy port as proof the user chose one.
  • None never reaches you for these parameters. Any of them left as None is replaced by the factory’s own default, an empty string. So an unset host, username, or password arrives as "".
Accept **kwargs. Cognee may forward additional keywords to registry adapters over time, and an adapter with a closed signature fails at construction with TypeError: __init__() got an unexpected keyword argument. A trailing **kwargs (as in the skeleton above) keeps your adapter working across Cognee versions — ignore what you don’t need rather than declaring it.
If you store the credentials on the instance, keep them out of your logs and error messages — see Security below.

Returning stored vectors from retrieve

retrieve takes a keyword-only include_vector flag (default False). When it is True, each returned ScoredResult carries the row’s stored embedding as payload["vector"], a plain list of floats (convert numpy arrays or driver types before returning). The default result is the payload alone. The built-in LanceDB, PGVector and Turso adapters support it; Neptune Analytics raises NotImplementedError when it is True. Accept the keyword even if your store cannot return vectors, and raise NotImplementedError in that case.

Optional: upsert_raw_vectors

VectorDBInterface declares a non-abstract upsert_raw_vectors whose default implementation raises NotImplementedError:
It writes vectors that were already computed, so a row can be copied from one store to another without re-embedding its text: read it with retrieve(..., include_vector=True), drop "vector" from the payload, and pass {"id", "vector", "payload"} to upsert_raw_vectors on the destination store. The built-in LanceDB, PGVector and Turso adapters implement it; Neptune Analytics does not. The contract, if you implement it:
  • Never call the embedding engine. Each point is {"id": ..., "vector": [...], "payload": {...}}.
  • A conflicting id replaces both the payload and the vector. This differs from create_data_points in the PGVector and Turso adapters, which keeps the stored vector on conflict. The exception is belongs_to_set: union the stored row’s tags with the incoming ones, so a copy never drops tags the destination already gave the row.
  • Validate everything before writing. Call validate_raw_vector_points(points, vector_size) (exported from cognee.infrastructure.databases.vector.vector_db_interface) with your embedding engine’s vector size before creating the collection. A missing id, a vector that is not a list of that width, or a payload that is not a dict raises ValueError and leaves the store untouched. The helper also collapses duplicate ids in one call: the last point wins, with the two belongs_to_set lists unioned.
  • Store the payload in the shape an ingested row of payload_schema would have, so a copied row is indistinguishable from one written by create_data_points. When payload_schema is None, treat the rows as your adapter’s index rows (IndexSchema, the shape of every <Type>_<field> collection), so a row read from one of those collections lands unchanged. The LanceDB adapter does this; PGVector and Turso store the payload JSON as given.
  • An empty points list is a no-op.
Not implementing it is supported: the inherited method raises NotImplementedError.

Optional: score_by_ids

VectorDBInterface declares score_by_ids as a method that is not abstract, so your adapter may leave it alone:
Cognee calls it when graph completion projects a neighborhood memory fragment (neighborhood_depth): the nodes reached by graph traversal were never scored by the seed vector search, so Cognee hands their ids to score_by_ids and they are ranked on their real distance to the query instead of a default penalty. Cognee also calls it for an explicit typed scope: graph completion with a non-NodeSet node_type and a node_name (no neighborhood_depth, no supplied memory fragment). Cognee projects that scope from the graph first, then passes only its node ids (and its edge ids, for the edge-type collection) to score_by_ids, so vectors outside the scope are never scored. A batch of queries goes through score_by_ids_batch instead. Scoped nodes without a stored vector keep the default distance penalty. The built-in LanceDB (including subprocess mode), PGVector, Turso and Neptune Analytics adapters implement it; Neptune Analytics computes exact CosineDistance on the server (neptune.algo.vectors.distance.byEmbedding) instead of its approximate top-k search. Cognee also needs it for a CHUNKS or RAG_COMPLETION search scoped by a graph type, for example node_type=TextDocument with node_name=[...] (see search()). The graph supplies the DocumentChunk ids in scope. Cognee scores them against DocumentChunk_text with score_by_ids, then loads their payloads with retrieve. Cognee does not fall back to scanning the collection here. If your adapter keeps the inherited stub, these searches raise CogneeConfigurationError (ScopedChunkSearchUnsupported). Node-set scopes (node_type=NodeSet) do not need score_by_ids. The contract, if you implement it:
  • Return raw distances for the ids that exist, with no top-k cutoff — one ScoredResult per found id, score set to the cosine distance and payload left None (Cognee only wants the number, so don’t pay to load payloads).
  • Empty data_point_ids returns []. Ids that aren’t in the collection are simply omitted, and the order of the returned list is unspecified.
  • Filter by id before scoring, and bound your batches — do not search the whole collection and filter afterwards. The built-in adapters deduplicate the ids (coercing each to str) and then issue one query per batch of at most 1,000 ids.
  • If your store answers vector queries through an approximate index, make sure a requested id is still scored when it falls outside the approximate neighborhood. The LanceDB adapter calls bypass_vector_index() for exactly this reason: a requested row far from the query must come back even when closer unrelated rows exist.
Not implementing it is supported, with one exception. Inheriting the base method (which raises NotImplementedError) and not defining the method at all are both handled, differently per caller:
  • Neighborhood expansion falls back to the previous behavior: expansion nodes keep the default distance penalty.
  • Typed scopes on graph completion scan your collections unfiltered (no node_name filter, since that filter selects node-set membership, which a typed scope never has) and map the distances onto the projected scope. The triplets are ranked the same as with score_by_ids, only more slowly, because the whole collection is searched.
  • Typed scopes on CHUNKS / RAG_COMPLETION are the exception: they raise ScopedChunkSearchUnsupported (see above).
Everything else about retrieval on your adapter is unchanged.

Optional: score_by_ids_batch

VectorDBInterface also has a non-abstract score_by_ids_batch hook, the batch form of score_by_ids for several query vectors over the same ids:
It returns one result list per query vector, in the vectors’ order, and each list follows the score_by_ids contract above: raw cosine distances, payload left None, missing ids omitted, no top-k cutoff. Empty data_point_ids returns one empty list per query vector. Cognee calls it when graph retrieval scores a query batch over an explicit typed graph scope (GRAPH_COMPLETION with a node_type other than NodeSet and a node_name, no neighborhood_depth, and no supplied memory fragment): one call per collection scores the whole batch. A single query still goes through score_by_ids. The default implementation calls score_by_ids once per query vector, concurrently, so an adapter that implements only score_by_ids keeps working. Override it when the cost of scoring is reaching the rows rather than computing the distances, so the rows are visited once per batch instead of once per query. Cognee only takes this path when your adapter also implements score_by_ids, so an override of score_by_ids_batch alone is never called. The built-in adapters are examples:
  • LanceDB fetches each id batch’s id and vector columns with one filtered scan and computes every query’s cosine distance locally.
  • PGVector and Turso run one statement per id batch with one distance column per query vector, so the distances are computed in the database and no vector leaves it.
  • Neptune Analytics keeps the default.
Like score_by_ids, deduplicate the ids and issue one scan or statement per batch of at most 1,000 ids, as the built-in adapters do.

Optional: compact

VectorDBInterface also has a non-abstract compact hook whose default implementation does nothing:
Implement it only if your store keeps storage that it never reclaims on its own, such as small fragments or old table versions left behind by upserts. The built-in LanceDB adapter implements it; stores that manage their own storage can leave the default. Cognee calls it with no arguments once per dataset at the end of every successful cognify() run (and so after every remember() that cognifies), inside the dataset’s vector context. The contract:
  • Cheap when there is nothing to do. It runs after every cognify run, including runs that wrote little or nothing.
  • Bounded in work. Do a limited amount of work per call and leave the rest for later calls, so one call never stalls the run. See LanceDB storage compaction for how the LanceDB adapter bounds each call.
  • Raises real failures. Cognee does not catch exceptions from compact(). A failure reaches the caller of cognify() as AfterRunHookError, after the run is recorded as completed and its data is stored. Return {"skipped": "<reason>"} for an intentional no-op, such as an unsupported store or a pass already in progress.
The return value is optional. If you return a dict mapping each collection name to a stats dict, Cognee logs a one-line summary of it. The summary reads the LanceDB adapter’s stat keys (executed_tasks, planned_tasks, fragments_removed, fragments_added, old_versions_removed, versions_pending), so other keys are not counted.

Optional: existing_collections

VectorDBInterface has a non-abstract existing_collections hook:
It returns the names in collection_names that exist, in their given order. Graph retrieval’s vector search calls it once per search with every collection it is about to search (the score_by_ids path does not), and skips the missing ones; they still contribute empty results, so the output shape does not change. The default implementation calls has_collection for every name concurrently, so an adapter that leaves it alone keeps working. Override it if your store can list its collections in one call, so the check costs one round trip instead of one per name. Return each existing name exactly as it was passed: a name your override leaves out is never searched and comes back empty. The built-in adapters are examples: PGVector reads the table list once on one connection (SQLAlchemy’s inspect(...).get_table_names(), which resolves against the connection’s search_path, so a schema-pinned adapter sees its own schema), and LanceDB reads table_names() once.

2. Test with a Dedicated Script

File: packages/vector/engine_name/examples/example.py Create a script that loads cognee, configures it to use your new <engine_name> provider, and runs basic usage checks. For example:
This script ensures a basic end-to-end test, verifying:
  • Your new adapter can be selected by cognee.
  • Data can be remembered into the vector database flow.
  • Recall functionality works correctly.
  • The database is empty after a prune operation.

3. Create a Test Workflow

File: .github/workflows/vector_db_tests.yml Add a new job to the existing vector database tests workflow:

5. Update pyproject.toml

Add your vector database client dependencies to the optional dependencies: pyproject.toml:
  • Run the shared conformance suite in packages/shared/contract_suite/vector_contract.py against your adapter — it is the common contract every community vector adapter is expected to satisfy.
  • Optionally implement score_by_ids if your store can score an explicit id list without a full-collection search — it improves triplet ranking for neighborhood retrieval, avoids a full-collection scan for typed node_type scopes on graph completion, and is required for typed scopes on CHUNKS / RAG_COMPLETION. Without it, those CHUNKS / RAG_COMPLETION searches raise ScopedChunkSearchUnsupported. Everything else works.
  • Optionally override score_by_ids_batch if your store can score several query vectors over the same ids in one pass — the default calls score_by_ids once per query vector and works unchanged.
  • Accept the keyword-only include_vector flag on retrieve, and optionally implement upsert_raw_vectors so rows can be copied into your store with their stored vectors, without re-embedding.
  • Optionally override existing_collections if your store can list its collections in one call — graph retrieval then checks which collections exist in one round trip instead of one has_collection call per name; the default works unchanged.
  • Optionally implement get_collection_names() (every collection in the store, and nothing else) and get_data_point_ids(collection_name) (every row id, without payloads or vectors) so datasets on your store can be moved to a new embedding model with reembed_dataset. Without them it raises NotImplementedError.
  • If your backend can isolate storage per user + dataset, register a dataset-database handler from the same register.py:
    Without a handler, your adapter can only be used with ENABLE_BACKEND_ACCESS_CONTROL=false.
  • Create a test or example script test_<engine_name>.py or example.py that you can use in your test workflow.
  • Create** a test workflow: .github/workflows/engine_name/test_<engine_name>.yml.
  • Add required dependencies to pyproject.toml optional dependencies.
  • Open a PR to verify that your new integration passes CI.

Additional Considerations

Error Handling

  • Implement proper error handling for connection failures, timeouts, and API errors.
  • Log meaningful error messages that help with debugging.
  • Handle graceful degradation when the vector database is unavailable.

Performance

  • Design for instance reuse: Cognee’s vector engine factory caches adapter instances keyed by their configuration parameters. Multiple calls with identical settings return the same adapter object. Design your adapter to be safe for reuse — avoid per-instance mutable state that cannot be safely shared across concurrent calls, and prefer lazy or thread-safe initialization patterns. When an entry is evicted (e.g. cache eviction or cache_clear), the factory calls your adapter’s close(). For capacity eviction the close is deferred until every leased reference to that instance is released, but the dataset-queue teardown and the idle reaper force-close immediately even while idle references are still held (holders transparently re-resolve to a fresh instance on next use) — so implement close() idempotently and safe to run while stale references remain; if it raises, the error is logged and swallowed rather than propagated to the caller.
  • Consider implementing connection pooling if your vector database supports it.
  • Never check out a second pooled connection while holding a session. If your adapter is pool-backed, resolve tables and metadata before opening the session that uses them — helpers like get_table() open their own connection, so calling one inside a session pins two connections per in-flight call and deadlocks a bounded pool once concurrency reaches its ceiling. Cognee’s own PGVectorAdapter follows this ordering in retrieve(), search(), and delete_data_points().
  • Never fetch the stored vector in search(). Select only the id, the payload (only when include_payload=True), and a distance computed by the database; accept with_vector for interface compatibility but ignore it. Cognee passes limit=None for node-set-filtered and batched triplet retrieval, which scans the whole collection, so fetching vectors there loads every stored embedding into application memory (several GB for tens of thousands of 3072-dimension rows). Cognee’s own PGVectorAdapter and LanceDBAdapter select only these columns.
  • Add proper async/await patterns to avoid blocking operations.
  • Implement batch operations efficiently where possible.

Security

  • Never log sensitive information like API keys or connection strings.
  • Validate inputs to prevent injection attacks.
  • Follow your vector database’s security best practices.

Documentation

  • Add docstrings to all public methods.
  • Document any specific configuration requirements.
  • Include examples of how to use your vector database with cognee.
That’s all! This approach keeps cognee’s architecture flexible, allowing you to swap in any vector database provider easily. If you need more advanced functionality (e.g., custom indexes, filters, or advanced search capabilities), simply implement them in your adapter class following the same patterns.

Join the Conversation!

Have questions about creating custom tasks? Join our community to discuss implementation strategies and best practices!