> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cognee.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Search

> Query your AI memory with vectors, graphs, and LLMs.

> [!NOTE]
>
> `search()` is a legacy operation. In Cognee v1.0, most users should use [recall()](https://docs.cognee.ai/core-concepts/main-operations/recall.md) instead. Legacy `search()` remains useful when you need explicit control over retrievers and lower-level retrieval parameters.

## What is search

`search` lets you ask questions over everything you've ingested and cognified.\
Under the hood, Cognee blends **vector similarity**, **graph structure**, and **LLM reasoning** to return answers with context and provenance.

## The big picture

* **Dataset-aware**: searches run against one or more datasets you can read *(requires `ENABLE_BACKEND_ACCESS_CONTROL=true`)*
* **Multiple modes**: from simple chunk lookup to graph-aware Q\&A
* **Hybrid retrieval**: vectors find relevant pieces; graphs provide structure; LLMs compose answers
* **Conversational memory**: for completion search types — GRAPH\_COMPLETION and its variants, RAG\_COMPLETION, HYBRID\_COMPLETION, TEMPORAL, and AGENTIC\_COMPLETION — use `session_id` to maintain conversation history across searches *(requires caching enabled)*. Omitting `session_id` still stores history, under the dataset-scoped [default session](https://docs.cognee.ai/core-concepts/sessions-and-caching.md#what-is-a-session). Retrieval-only search types do not use session history.
* **Safe by default**: permissions are checked before any retrieval
* **Observability**: telemetry is emitted for query start/completion

> [!WARNING]
>
> **Dataset scoping** requires specific configuration. See [permissions system](https://docs.cognee.ai/core-concepts/multi-user-mode/permissions-system/datasets.md#dataset-isolation-how-access-is-enforced) for details on access control requirements and supported database setups.

## Where search fits

Use `search` after you've run `.add` and `.cognify`.
At that point, your dataset has chunks, summaries, embeddings, and a knowledge graph—so queries can leverage both **similarity** and **structure**.

> [!WARNING]
>
> If you see `DatabaseNotCreatedError: please call await setup() first`, Cognee has not been initialized yet. In practice, that usually means you are trying to search or use an operation that resolves the default user before initialization has happened. Run `cognee.add(...)` or `cognee.remember(...)` first, then retry your operation.

> [!NOTE]
>
> Completion-type search modes (`GRAPH_COMPLETION`, `RAG_COMPLETION`, and the other `*_COMPLETION` types) call the LLM to compose an answer, so they can fail when the configured LLM provider (or LiteLLM proxy) reports that its token budget is exhausted. In that case `search()` raises `LLMPaymentRequiredError`, which the API surfaces as **HTTP 402 (Payment Required)** with body `{"detail": "LLM provider requires payment or token budget is exhausted. [LLMPaymentRequiredError]"}` — or, when the provider's own budget sentence can be identified, `{"detail": "LLM budget exhausted: <provider sentence> [LLMPaymentRequiredError]"}` (see [402 Payment Required](https://docs.cognee.ai/api-reference/introduction.md)). This error is **terminal** — Cognee does not retry budget-exhaustion failures — so treat a `402` as final for the request and prompt the user to top up their token budget rather than reissuing the call.

## How it works (conceptually)

1. **Scope & permissions**\
   Resolve target datasets (by name or id) and enforce read access.

   For most search types, this scope can contain multiple datasets. `AGENTIC_COMPLETION` is stricter and requires the resolved scope to contain exactly one dataset.

2. **Mode dispatch**\
   Pick a search mode (default: **graph-aware completion**) and route to its retriever.

3. **Retrieve → (optional) generate**\
   Collect context via vectors and/or graph traversal; some modes then ask an LLM to compose a final answer.

4. **Return results**\
   Depending on mode: a natural-language answer string, chunk/summary dicts with metadata, graph records, or Cypher results.

For a practical guide to using search with examples and detailed parameter explanations, see [Search Basics](https://docs.cognee.ai/guides/search-basics.md).

## Retrievers

Each search type is handled by a **retriever**. The pipeline is: `get_retrieved_objects` → `get_context_from_objects` → `get_completion_from_context` (skipped when `only_context=True`).

| Search type | Retriever |
| - | - |
| GRAPH\_COMPLETION | GraphCompletionRetriever |
| RAG\_COMPLETION | CompletionRetriever |
| HYBRID\_COMPLETION | HybridRetriever |
| HYBRID\_COMPLETION\_DECOMPOSITION | HybridDecompositionRetriever |
| CHUNKS | ChunksRetriever |
| SUMMARIES | SummariesRetriever |
| GRAPH\_SUMMARY\_COMPLETION | GraphSummaryCompletionRetriever |
| GRAPH\_COMPLETION\_COT | GraphCompletionCotRetriever |
| GRAPH\_COMPLETION\_CONTEXT\_EXTENSION | GraphCompletionContextExtensionRetriever |
| GRAPH\_COMPLETION\_DECOMPOSITION | GraphCompletionDecompositionRetriever |
| CHUNKS\_LEXICAL | BM25ChunksRetriever |
| CODING\_RULES | CodingRulesRetriever |
| CODE | CodeRetriever |
| TEMPORAL | TemporalHybridRetriever |
| CYPHER | CypherSearchRetriever |
| NATURAL\_LANGUAGE | NaturalLanguageRetriever |
| SKILLS | SkillsRetriever |
| BROAD | BroadRetriever |

You can register a custom retriever for a search type via `use_retriever(SearchType, RetrieverClass)`; the class must implement the same three-step interface (`BaseRetriever`). See the API reference for `BaseRetriever` and `register_retriever`.

If your retriever is deterministic — its result is built from stored data rather than from an LLM answering the query — set the class attribute `supports_session_turn_preparation = False` on it. The attribute defaults to `True`, which makes a search under an active session run the [conversational turn analysis](https://docs.cognee.ai/core-concepts/sessions-and-caching.md#session-context-guidance-auto-feedback) before retrieval: a pre-retrieval LLM call, a query that the analysis may rewrite, and a turn the analysis may gate into a short acknowledgement instead of your payload records. The built-in non-generative retrievers (`ChunksRetriever`, `SummariesRetriever`, `LexicalRetriever` and its BM25/Jaccard subclasses, `CodeRetriever`, `SkillsRetriever`, `GraphReportRetriever`, `CypherSearchRetriever`, `NaturalLanguageRetriever`) all opt out this way — `GraphReportRetriever` because it ignores the query text entirely, `CypherSearchRetriever` because the query is the statement it executes, `NaturalLanguageRetriever` because it returns rows rather than an LLM answer (it still calls the LLM to generate its Cypher), and the rest because they answer with stored records.

```python theme={null}
from cognee.modules.retrieval.base_retriever import BaseRetriever


class MyLookupRetriever(BaseRetriever):
    supports_session_turn_preparation = False
    ...
```

### Multi-query (batch)

**GraphCompletionRetriever**, **GraphCompletionCotRetriever**, and **GraphCompletionContextExtensionRetriever** support **batch mode**: pass `query_batch` (a non-empty list of strings) instead of `query`. You get one result per query; session cache is not used in batch mode. The public `cognee.search()` API accepts only a single `query_text`; batch is available when you use the retrievers directly (e.g. in custom pipelines).

> [accordion] GRAPH\_COMPLETION
>
> Graph-aware question answering.
>
> * **What it does**: Finds relevant graph triplets using vector hints across indexed fields, resolves them into readable context, and asks an LLM to answer your question grounded in that context.
> * **Why it’s useful**: Combines fuzzy matching (vectors) with precise structure (graph) so answers reflect relationships, not just nearby text.
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt it would have sent instead of an answer — the formatted context rendered into the retriever's template; the task template comes back as `system_prompt_result` under `verbose=True` (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `verbose=True`, returns a payload containing `text_result`, `context_result`, `objects_result`, `user_prompt_result`, and `system_prompt_result`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
>
> **The concrete lookup process**
>
> One `GRAPH_COMPLETION` call runs five stages (`GraphCompletionRetriever` → `brute_force_triplet_search`):
>
> 1. **Vector seeds** — the query is embedded once, then searched concurrently across every vector index collection registered by the loaded DataPoint models — typically `Entity_name`, `EntityType_name`, `TextSummary_text`, `DocumentChunk_text` — plus the edge collection `EdgeType_relationship_name`. Each collection returns at most `wide_search_top_k` (default `100`) scored hits; the node hits' ids become the traversal seeds, while edge hits are kept for scoring in the next steps.
> 2. **Graph traversal** — the seeds are resolved against the graph store into an in-memory subgraph ("memory fragment") containing every edge with at least one endpoint among the seed ids, i.e. a 1-hop expansion around the seeds, with the properties `id`, `name`, `type`, `description`, `text`, and `importance_weight` projected per node. Graph adapters without ID-filtered projection fall back to projecting the whole graph. The cosine distances from step 1 are then mapped onto the projected nodes and edges; anything with no vector hit keeps the fallback distance `triplet_distance_penalty` (default `6.5`), which ranks it below every real match.
> 3. **Triplet ranking** — each projected edge is scored as a triplet (`node1`, `edge`, `node2`) by summing the three elements' distances, each scaled by `(2 - importance_weight)` and, when `feedback_influence > 0`, blended with the element's `feedback_weight`. The `top_k` **lowest-scoring** (closest) triplets are kept.
> 4. **Context assembly** — the kept triplets are rendered into one string: a `Nodes:` section listing each distinct endpoint once with its content (a chunk/summary node contributes its `text`, an entity its `description`), followed by a `Connections:` section of `source --[relationship]--> target` lines. `include_global_context_index=True` prepends a [global-context](https://docs.cognee.ai/core-concepts/further-concepts/global-context-index.md) prelude. With `only_context=True` this string is returned and the search stops here.
> 5. **LLM completion** — the question and context are rendered into the `graph_context_for_question.txt` user prompt and sent with the `answer_simple_question.txt` system prompt. With [sessions](https://docs.cognee.ai/core-concepts/sessions-and-caching.md) enabled, conversation history is prepended to the system prompt; with `include_references=True` an `Evidence:` block is appended to the answer.
>
> **How `top_k` affects it**
>
> `top_k` (default `15` through `recall()` and `search()`; `5` when you construct `GraphCompletionRetriever` yourself) is the number of **triplets** kept in step 3 — not nodes, chunks, or characters. So it bounds the context at `top_k` connection lines and at most `2 × top_k` distinct nodes; raising it deepens recall and grows prompt tokens roughly linearly, lowering it tightens the answer. It must be a positive integer, or `None` to use the retriever's own default; non-positive values raise `QueryValidationError`.
>
> `top_k` only selects from what steps 1–2 surfaced, so on large graphs also raise `wide_search_top_k` to widen the candidate pool. Two variants change step 2: setting `neighborhood_depth` replaces the 1-hop projection with a *k*-hop neighborhood grown from up to `neighborhood_seed_top_k` of the vector-hit seeds (all seeds through `search()` and `recall()`, which default it to `None`; `10` when you construct the retriever yourself — seeds are ranked by vector distance, nearest first, with a node that matches in several collections counted at its best distance, so the cap keeps the closest hits), and passing `node_name` drops the per-collection cap (vector hits are node-set filtered instead) without narrowing the projection by seed ids. That node-set filter applies to the node collections only: the edge collection `EdgeType_relationship_name` holds one point per relationship text for the whole dataset — shared vocabulary rather than node-set members — so it is searched unfiltered and only ever scores edges the projection has already scoped. This is why a scoped search keeps each edge's real text-relevance distance instead of the `triplet_distance_penalty` fallback from step 2. The nodes a *k*-hop expansion adds beyond the seeds had no vector hit in step 1; on LanceDB, PGVector, Turso, and Neptune Analytics, Cognee scores them with a second id-filtered vector query so they rank on their real distance, and on adapters without that capability they keep the `triplet_distance_penalty` fallback. A typed scope — `node_name` with a `node_type` other than `NodeSet`, and no `neighborhood_depth` — works differently: Cognee projects that scope from the graph first, then scores only its node and edge ids on those same four adapters (other adapters search their collections unfiltered and map the distances onto the scope), so no node-set filter is applied to the vector hits.

> [accordion] RAG\_COMPLETION
>
> Retrieve-then-generate over text chunks.
>
> * **What it does**: Pulls top-k chunks via vector search, stitches a context window, then asks an LLM to answer.
> * **When to use**: You want fast, text-only RAG without graph structure.
> * **Scope**: Honors `node_name` and `node_name_filter_operator`, so chunk retrieval can be limited to specific node sets or, with a `node_type` other than `NodeSet`, to the chunks of named graph nodes such as one document (see [`search()` parameters](https://docs.cognee.ai/python-api/search#parameters)).
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt it would have sent instead of an answer — the formatted context rendered into the retriever's template; the task template comes back as `system_prompt_result` under `verbose=True` (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `verbose=True`, returns a payload containing `text_result`, `context_result`, `objects_result`, `user_prompt_result`, and `system_prompt_result`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
>
> **Context assembly and `top_k`**
>
> `top_k` (default `15` through `recall()` and `search()`; `1` when you construct `CompletionRetriever` yourself or pass `top_k=None`) is the number of chunks from the `DocumentChunk_text` collection that reach the context — with [user preferences](https://docs.cognee.ai/core-concepts/further-concepts/personalized-memory.md) active the vector search fetches a wider candidate pool first, then re-ranks and trims back to `top_k`. Context assembly then concatenates those chunks' text in rank order, newline-separated, and stops: no summarization, no expansion to neighboring chunks, and no graph lookup. With [sessions](https://docs.cognee.ai/core-concepts/sessions-and-caching.md) enabled, a follow-up turn also retrieves for a conversation-aware rewrite of the query, but the two lanes are merged back into the same `top_k` chunks.
>
> So the context can never hold more than those `top_k` chunks carry. When the answer is spread across more passages than they cover, either raise `top_k`, or pick a search type that assembles context from more than chunk text: `HYBRID_COMPLETION` adds entity neighborhoods and edge-derived facts alongside its own chunk lane, `GRAPH_COMPLETION` answers from graph triplets, and `GRAPH_COMPLETION_COT` / `GRAPH_COMPLETION_CONTEXT_EXTENSION` run further retrieval rounds for multi-hop questions. Inspect what actually reached the prompt with `only_context=True` before tuning — see [Understand Recall with RAG Completion](https://docs.cognee.ai/guides/rag-recall.md).

> [accordion] HYBRID\_COMPLETION (default)
>
> Blended chunk + entity retrieval with LLM completion.
>
> * **What it does**: Builds a single context from document chunks and entity/graph context (matched entities plus their connected edges), then asks an LLM to answer grounded in that combined context. The chunk lane runs two vector searches, over chunks and over their summaries, pairs each summary with its source chunk, and keeps the top `chunks_top_k`. Each entity's edge bullets are ordered by how relevant the edge text is to the query (entity-type edges are pinned first, then query-ranked edges, then remaining edges in graph order). The combined context also ends with a `## Related facts` section: up to `facts_top_k` edge-derived facts ranked by similarity to the query, excluding facts already shown as entity edge bullets. Facts whose text comes from chunk→entity "contains" edges are rendered as `Name: description` glossary-style lines.
> * **When to use**: You want semantic chunk recall alongside entity relationships in one answer. For keyword matching, use `CHUNKS_LEXICAL`.
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt it would have sent instead of an answer — the formatted context rendered into the retriever's template; the task template comes back as `system_prompt_result` under `verbose=True` (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `verbose=True`, returns a payload containing `text_result`, `context_result`, `objects_result`, `user_prompt_result`, and `system_prompt_result`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
> * **Cost**: Issues several vector-store queries per search (chunks, summaries, entities, and facts), so expect higher query load than a single-collection mode.
> * **Limitation**: `query_batch` cannot be combined with the session cache.
> * **Collections searched**: the chunk lane reads `DocumentChunk_text` and `TextSummary_text`, the entity lane reads `Entity_name`, and `## Related facts` reads the edge collection `EdgeType_relationship_name`. When the dataset holds [dlt](https://docs.cognee.ai/integrations/dlt-integration.md) rows, the chunk lane also reads `DltRow_text`, and the entity lane also reads `DltColumn_properties`, `SchemaTable_name`, and `SchemaRelationship_name`. When the vector store has neither a `DocumentChunk_text` nor a `DltRow_text` collection, the request runs as `GRAPH_COMPLETION` instead. See [Searching Custom Data Models](https://docs.cognee.ai/guides/custom-data-models.md#searching-custom-data-models) for what this means for nodes inserted with `add_data_points`.
>
> **How the lanes are ranked and merged**
>
> Both lanes are embedding searches against the same query vector, but each one picks its own results with its own cap. Results are never ranked against the other lane's results.
>
> * **Chunk lane.** It fetches up to `2 × chunks_top_k` hits from `DocumentChunk_text` and up to `chunks_top_k` hits from `TextSummary_text` (or `text_summaries_top_k`, when you set it). A chunk found directly and through its summary becomes one candidate, not two. Candidates are scored with reciprocal-rank fusion over their rank in each search, so appearing in both searches scores higher. That score is multiplied by a factor derived from the chunk's [importance weight](https://docs.cognee.ai/guides/importance-weight.md) (`0.75` at weight `0.0` up to `1.25` at `1.0`) when `use_importance_weight` is on, which it is by default, and by the user-preference or truth factors when those are enabled. The top `chunks_top_k` are kept. Summary hits only help rank chunks; summary text itself is not added to the context. `chunks_top_k` applies to this lane only, never to entities.
> * **Entity lane.** It keeps the top `entities_top_k` matches from `Entity_name` by vector similarity, and lists up to `max_edges_per_entity` edges under each one. With [ontology query grounding](https://docs.cognee.ai/core-concepts/further-concepts/ontologies.md#query-grounding) on, ontology classes and individuals named in the query are pinned at the head of the lane and count against `entities_top_k`.
>
> After any global-context prelude, the context puts the sections in a fixed order: `## Relevant passages` (chunk text), `## Relevant entities` (entity names, types, and edge bullets), then `## Related facts`. Passage text only comes from the chunk lane. The entity lane adds entity names, types, and edges, not chunk text or entity descriptions. So the same passage cannot appear twice, even when an entity came from that passage. Under each entity, the same edge is listed only once. With [ontology query grounding](https://docs.cognee.ai/core-concepts/further-concepts/ontologies.md#query-grounding) on, an `## Ontology grounding` block comes before all of these sections, including the global-context prelude.
>
> **Configuration (`retriever_specific_config`)**
>
> | Key | Default | What it does |
> | - | - | - |
> | `chunks_top_k` | `min(top_k, 10)` (`10`) | Max chunks included in context. Summaries only help rank them. |
> | `entities_top_k` | `min(top_k, 10)` (`10`) | Number of entities retrieved for entity/graph context. |
> | `max_edges_per_entity` | `10` | Max connected edges listed per entity. |
> | `facts_top_k` | `min(top_k, 10)` (`10`) | Max edge-derived facts included in the `## Related facts` section. Set to `0` to disable the section. The fact budget is tied to the entity lane, so with `entities_top_k` at `0` no facts are returned. On `node_name`-scoped searches, only facts expressed by an edge on an in-scope entity are kept. |
> | `include_global_context_index` | `false` | When `true`, prepends a global-context section (root text + top global-context summaries) to the answer context. |
> | `global_context_index_top_k` | `3` | Number of global-context summaries to include when `include_global_context_index=true`. |
>
> Pass these through `retriever_specific_config`.

> [accordion] CHUNKS
>
> Direct chunk retrieval.
>
> * **What it does**: Returns the most similar text chunks to your query via vector search.
> * **When to use**: You want raw passages/snippets to display or post-process.
> * **Output**: `list[dict]`. Each chunk item includes `id`, `text`, `chunk_index`, `chunk_size`, and `cut_type`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`. See [Citation and Source Tracking](https://docs.cognee.ai/guides/search-basics.md#citation-and-source-tracking) for details and examples.

> [accordion] SUMMARIES
>
> Search over precomputed summaries.
>
> * **What it does**: Vector search on `TextSummary` content for concise, high-signal hits.
> * **When to use**: You prefer short summaries instead of full chunks.
> * **Output**: `list[dict]`. Each summary item includes `id` and `text`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`. See [Citation and Source Tracking](https://docs.cognee.ai/guides/search-basics.md#citation-and-source-tracking) for details and examples.

> [accordion] GRAPH\_SUMMARY\_COMPLETION
>
> Graph-aware summary answering.
>
> * **What it does**: Builds graph context like GRAPH\_COMPLETION, then condenses it before answering.
> * **When to use**: You want a tighter, summary-first response.
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt it would have sent instead of an answer — the formatted context rendered into the retriever's template; the task template comes back as `system_prompt_result` under `verbose=True` (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `verbose=True`, returns a payload containing `text_result`, `context_result`, `objects_result`, `user_prompt_result`, and `system_prompt_result`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.

> [accordion] GRAPH\_COMPLETION\_COT
>
> Chain-of-thought over the graph.
>
> * **What it does**: Starts from `GRAPH_COMPLETION` (retrieve triplets, draft an answer), then runs `max_iter` reasoning rounds. Each round validates the current answer, generates a follow-up question, fetches new triplets for it, merges them into the context, and regenerates the answer.
> * **When to use**: Complex multi-hop questions where the answer depends on traversing several relationships (for example `A → B → C → D`). Each round can pull in one additional hop's worth of triplets, so deeper chains need more iterations.
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt it would have sent instead of an answer — the formatted context rendered into the retriever's template; the task template comes back as `system_prompt_result` under `verbose=True` (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `verbose=True`, returns a payload containing `text_result`, `context_result`, `objects_result`, `user_prompt_result`, and `system_prompt_result`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
>
> **Controlling depth with `max_iter`**
>
> `max_iter` (default `4`) is the number of follow-up rounds after the initial retrieval. Higher values let the retriever traverse further from the seed entities but multiply LLM calls — each round adds a validation call, a follow-up-generation call, a new triplet fetch, and a completion call. Latency and token cost scale roughly linearly with `max_iter`.
>
> Pass it through `retriever_specific_config`.

> [accordion] GRAPH\_COMPLETION\_CONTEXT\_EXTENSION
>
> Iterative context expansion.
>
> * **What it does**: Starts like `GRAPH_COMPLETION`: vector similarity seeds relevant triplets, then graph retrieval resolves them into context. It then runs up to `context_extension_rounds` extension rounds (default `4`), using each generated answer as a follow-up query to fetch and merge additional triplets until no new triplets are found.
> * **When to use**: Open-ended or exploratory queries that need broader subgraph coverage than a single `GRAPH_COMPLETION` pass.
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt it would have sent instead of an answer — the formatted context rendered into the retriever's template; the task template comes back as `system_prompt_result` under `verbose=True` (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `verbose=True`, returns a payload containing `text_result`, `context_result`, `objects_result`, `user_prompt_result`, and `system_prompt_result`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.

> [accordion] NATURAL\_LANGUAGE
>
> Natural language to Cypher to execution.
>
> * **What it does**: Infers a Cypher query from your question using the graph schema, runs it, returns the results.
> * **When to use**: You want structured graph answers without writing Cypher.
> * **Output**: `list[dict[str, Any]]` containing executed graph-query result rows — the same shape `CYPHER` returns. There is no text context or completion: with `verbose=True` the rows are in `objects_result`, and `context_result` and `text_result` are `None`. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`. (Before v1.6.3, a search that found rows raised a pydantic `ValidationError`; only searches with no rows completed.)
> * **Availability**: Disabled by default; set `ALLOW_CYPHER_QUERY=true` to enable it. While disabled, the search raises `SearchTypeDisabledError` (HTTP 403).

> [accordion] CYPHER
>
> Run Cypher directly.
>
> * **What it does**: Executes your Cypher query against the graph database.
> * **When to use**: You know the schema and want full control.
> * **Output**: `list[dict[str, Any]]` containing raw Cypher result rows. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
> * **Availability**: Disabled by default; set `ALLOW_CYPHER_QUERY=true` to enable it. While disabled, the search raises `SearchTypeDisabledError` (HTTP 403).

> [accordion] CODING\_RULES
>
> Code-focused retrieval (coding rules / codebase search).
>
> * **What it does**: Retrieves rules or code context from the `coding_agent_rules` nodeset and returns structured code information.
> * **When to use**: Codebases or coding guidelines indexed by Cognee (e.g. via the coding-rule extraction task).
> * **Output**: `list[dict[str, Any]]` containing structured code/rule retrieval objects. Exact fields depend on the retrieved rule/context objects. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
> * **Prereq**: The `coding_agent_rules` nodeset must be populated (e.g. by running `add_rule_associations` through [`run_custom_pipeline()`](https://docs.cognee.ai/python-api/custom-pipeline) — see [Coding rules](https://docs.cognee.ai/core-concepts/main-operations/legacy-operations/memify.md#built-in-pipelines)).

> [accordion] CODE
>
> Deterministic queries over a code graph.
>
> * **What it does**: Loads the dataset's code-graph facts (modules, symbols, routes, storage, services, dependencies, insights, …) into an in-memory snapshot and runs exactly one graph operation on it — list facts, explore a neighborhood, traverse or find a path between facts, analyse impact, read explainer insights, draw the module-level architecture, or report what the last ingestion changed. It uses only the graph adapter: no LLM, embedding, or vector call, and no session-turn step.
> * **When to use**: Repositories indexed by the [code-graph pipeline](https://docs.cognee.ai/guides/code-graph.md) or the [GitHub integration](https://docs.cognee.ai/integrations/github-integration.md), when you want exact structural answers rather than a generated one.
> * **Input**: The operation and its arguments come from the `code_query` dict, not from `query_text` or `retriever_specific_config`. Every operation, its arguments, and the fact kinds it can filter on are listed under [SearchType — CODE](https://docs.cognee.ai/python-api/search-type.md#per-search-type-parameters).
> * **Output**: One `dict` per searched dataset, keyed by the operation — for example `facts` with `total`/`has_more` for `query_facts`, `nodes`/`edges`/`stats` for `explore` and `traverse`, `by_depth` and a `summary` for `impact_analysis`, and a `diagram` block when requested. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.
> * **Prereq**: A code graph in the dataset. Graph paths exist only inside one dataset, so index the repositories you want to connect into the same dataset.

> [accordion] TRIPLET\_COMPLETION (deprecated)
>
> Triplet embeddings and `TripletRetriever` were removed. `TRIPLET_COMPLETION` now runs as `GRAPH_COMPLETION` and raises a `FutureWarning`; use `GRAPH_COMPLETION` instead. The alias is removed in the next release. See [Triplet Embeddings (removed)](https://docs.cognee.ai/guides/memify-triplet-embeddings.md).

> [accordion] CHUNKS\_LEXICAL
>
> Lexical (keyword-style) chunk search.
>
> * **What it does**: Returns chunks that match your query using token-based BM25 lexical ranking, not semantic embeddings.
> * **When to use**: Exact-term or keyword-style lookups; stopword-aware search.
> * **Output**: `list[dict]` containing ranked chunk payloads (chunk text and metadata). BM25 orders the results but does not attach a score to them. With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`.

> [accordion] TEMPORAL
>
> Time-aware retrieval.
>
> * **What it does**: Retrieves content and puts results dated inside the question's time window first, then answers from those hybrid results. Only dates coarser than the question rank lower; see [Temporal Knowledge Graph](https://docs.cognee.ai/guides/temporal-knowledge-graph.md#how-dates-are-stored) for the full ordering.
> * **When to use**: Queries about "before/after X", "in 2020", or "between 2001 and 2004".
> * **Output**: `str` by default. With `only_context=True`, returns the user prompt built around the formatted temporal context instead of an answer (see [Inspecting the LLM input](https://docs.cognee.ai/python-api/search.md#inspecting-the-llm-input)). With `ENABLE_BACKEND_ACCESS_CONTROL=true`, results are wrapped with `dataset_name` and `dataset_id`. See [Temporal Knowledge Graph](https://docs.cognee.ai/guides/temporal-knowledge-graph.md) for setup.

> [accordion] BROAD
>
> Questions over a whole dataset.
>
> * **What it does**: Answers questions that need every record, not just the passages closest to the question: counts, totals, lists, and lookups. For each question it builds a temporary SQLite **record store** of the dataset. CSV/TSV/pipe/semicolon text with a header and at least 10 rows, markdown tables, JSON arrays and JSON Lines, mbox email archives, and dlt rows each become one table per set of columns. All other text goes into a `lines` table, with one row per non-empty line. The store is then used in one of three ways:
>   * **Whole dataset**: if the dataset fits `context_tokens` (default `30000`), the LLM sees all of it. It either answers directly or writes a SQL query when the answer needs many rows counted, summed, or compared.
>   * **Record store**: otherwise the LLM sees only the store's schema, sample rows, and layout. It writes one read-only `SELECT`, which SQLite runs, or asks for the text to be read (below).
>   * **Reading**: when the LLM decides the question needs the text read, the chunks most similar to the question fill a `reading_tokens`-sized prompt (default `12000`). Similarity is matched against the question plus phrasings the LLM supplies. A query over the `lines` table that finds nothing also falls back to reading.
> * **When to use**: "How many…", "list every…", or "what is the total…" questions that similarity search undercounts.
> * **Output**: `str` by default. The answer is followed by a note on how it was reached (whole dataset, the SQL query that ran, or how many parts were read), plus the full result table when a query returns more than one row. No `include_references` evidence; context object ids are `None`. With `only_context=True`, returns the user prompt built over the query result or the parts read; the decision call and the query still run during retrieval.
> * **Limits**: one read-only `SELECT`, at most 1,000 result rows, and 120 seconds per query. The answer model is shown only the first 200 rows. A failing query is retried once with the error. The store is rebuilt for every question. A dataset larger than `store_mb` (default `32`) is represented only by its chunks most similar to the question. Counts then cover only that part, and the answer says what was covered.
> * **Configuration**: `context_tokens`, `reading_tokens`, `batch_mb`, and `store_mb` through `retriever_specific_config`; see [SearchType — BROAD](https://docs.cognee.ai/python-api/search-type.md#per-search-type-parameters). The prompts are `broad_decide_small.txt`, `broad_decide_large.txt`, and `broad_answer.txt` in `cognee/infrastructure/llm/prompts/`.

> [accordion] FEELING\_LUCKY
>
> Automatic mode selection.
>
> * **What it does**: Uses an LLM to choose the most suitable search type for your query, then runs it. It never picks `CODE`, and picks `CYPHER` or `NATURAL_LANGUAGE` only when `ALLOW_CYPHER_QUERY=true` (see [Cypher Query Access](https://docs.cognee.ai/setup-configuration/security.md)). When the LLM's answer is not a valid type, names a type that cannot serve the request, or the selection call fails, it falls back to `RAG_COMPLETION`.
> * **When to use**: Exploratory or one-off queries when you are unsure which mode fits best. For production or latency-sensitive workloads, prefer a specific search type.
> * **Output**: Varies. Returns the same shape as whichever search type the router selects.

> [accordion] INSIGHTS (MCP only)
>
> Graph-edge result format specific to the Cognee MCP server.
>
> * **What it does**: Runs search in the Cognee MCP server and formats the raw triplet results as readable relationship lines instead of asking an LLM to compose an answer.
> * **When to use**: You want to inspect raw graph edges in MCP rather than receive a natural-language response.
> * **Output**: A newline-separated list of relationship statements. `INSIGHTS` is MCP-only and is not available through the Python `SearchType` enum.

> [!NOTE]
>
> **Feedback** is handled via [Sessions](https://docs.cognee.ai/core-concepts/sessions-and-caching.md) and the [Feedback System](https://docs.cognee.ai/guides/feedback-system.md)—use `cognee.session.add_feedback` and `cognee.session.delete_feedback`. See the [Persistent Memory Across Sessions](https://docs.cognee.ai/guides/persistent-memory-across-sessions.md) and [Feedback System](https://docs.cognee.ai/guides/feedback-system.md) for full details.

## Further details

> [accordion] Searching across both graph and vector stores
>
> You do **not** need to run two separate searches and merge the results — the graph-completion family already queries both stores in a single call.
>
> For `GRAPH_COMPLETION`, `GRAPH_COMPLETION_DECOMPOSITION`, `GRAPH_SUMMARY_COMPLETION`, `GRAPH_COMPLETION_COT`, and `GRAPH_COMPLETION_CONTEXT_EXTENSION`, retrieval works in two combined steps:
>
> 1. **Vector store** — seed nodes and edges are found by embedding similarity across indexed fields (`brute_force_triplet_search` over the vector index collections).
> 2. **Graph store** — those seeds are resolved against the knowledge graph so the surrounding triplets (nodes + relationships) come back as structured context.
>
> The merged graph + vector context is then formatted and (unless `only_context=True`) passed to the LLM. So a single `GRAPH_COMPLETION` call is the built-in way to "look at both the graph and the vector store" at once.
>
> ```python theme={null}
> import cognee
> from cognee import SearchType
>
> # One call uses vector similarity to seed and graph structure to expand
> results = await cognee.search(
>     query_text="How are X and Y connected?",
>     query_type=SearchType.GRAPH_COMPLETION,
> )
> ```
>
> If you instead want raw vector-only matches (`CHUNKS`, `SUMMARIES`) and raw graph rows (`CYPHER`, `NATURAL_LANGUAGE`) and prefer to merge them yourself, run each search type separately and combine the returned lists. For multi-part questions, `GRAPH_COMPLETION_DECOMPOSITION` with `retriever_specific_config={"decomposition_mode": "combined_triplets_context"}` splits the query into subqueries, fetches triplets for each, and de-duplicates them into one merged context before answering.

> [accordion] Retrieval pipeline and raw results
>
> Every retriever follows the same three-step internal pipeline:
>
> * **`get_retrieved_objects`** — fetches raw graph triplets (edges + nodes) or vector chunks from the store
> * **`get_context_from_objects`** — formats those objects into a context string (e.g. `"Nodes: … Connections: …"` for graph modes)
> * **`get_completion_from_context`** — sends context to the LLM to produce a natural-language answer *(skipped when `only_context=True`)*
>
> **Completion modes** (`GRAPH_COMPLETION`, `RAG_COMPLETION`, etc.) run all three steps and return a **string answer**. That is why `GRAPH_COMPLETION` returns a plain string by default: the raw graph objects are consumed internally to assemble the LLM prompt.
> **Retrieval-only modes** (`CHUNKS`, `SUMMARIES`) skip the LLM step and return **structured dicts** directly.
>
> **Inspecting the raw retrieved objects**: add `verbose=True` to receive `text_result` (LLM answer), `context_result` (formatted context string), `objects_result` (raw graph edges/nodes or chunk objects), and `user_prompt_result` / `system_prompt_result` (the two messages an `only_context` call stands in for, `None` otherwise) together. Use `only_context=True` to skip LLM generation and get the prompt built around that context instead of an answer. For structured chunk dicts with no LLM call at all, use `SearchType.CHUNKS`. See [Search Basics — raw source objects](https://docs.cognee.ai/guides/search-basics.md#citation-and-source-tracking) for code examples.

> [card] [Add](https://docs.cognee.ai/core-concepts/main-operations/legacy-operations/add.md)
>
> First bring data into Cognee

> [card] [Cognify](https://docs.cognee.ai/core-concepts/main-operations/legacy-operations/cognify.md)
>
> Build the knowledge graph that search queries

> [card] [Architecture](https://docs.cognee.ai/core-concepts/architecture.md)
>
> Understand how vector and graph stores work together

> [card] [Sessions and Caching](https://docs.cognee.ai/core-concepts/sessions-and-caching.md)
>
> Enable conversational memory with sessions


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.