> ## 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 the knowledge graph

# cognee.search()

```python theme={null}
async def search(
    query_text: str,
    query_type: SearchType = SearchType.GRAPH_COMPLETION,
    user: Optional[User] = None,
    datasets: Optional[Union[list[str], str]] = None,
    dataset_ids: Optional[Union[list[UUID], UUID]] = None,
    system_prompt_path: str = 'answer_simple_question.txt',
    system_prompt: Optional[str] = None,
    top_k: int = 15,
    node_type: Optional[Type] = NodeSet,
    node_name: Optional[List[str]] = None,
    node_name_filter_operator: str = "OR",
    only_context: bool = False,
    session_id: Optional[str] = None,
    wide_search_top_k: Optional[int] = 100,
    triplet_distance_penalty: Optional[float] = 6.5,
    verbose: bool = False,
    retriever_specific_config: Optional[dict] = None,
    llm_config: Optional[LLMConfig] = None,
    embedding_config: Optional[EmbeddingConfig] = None,
    include_references: bool = False,
) -> List[SearchResult]
```

## Description

Search and query the knowledge graph for insights, information, and connections.

This is the final step in the Cognee workflow that retrieves information from the
processed knowledge graph. It supports multiple search modes optimized for different
use cases - from simple fact retrieval to complex reasoning and code analysis.

Search Prerequisites:

* **LLM\_API\_KEY**: Required for GRAPH\_COMPLETION and RAG\_COMPLETION search types
* **Data Added**: Must have data previously added via `cognee.add()`
* **Knowledge Graph Built**: Must have processed data via `cognee.cognify()`
* **Dataset Permissions**: User must have 'read' permission on target datasets
* **Vector Database**: Must be accessible for semantic search functionality

Search Types & Use Cases:

**GRAPH\_COMPLETION** (Default - Recommended):
Natural language Q\&A using full graph context and LLM reasoning.
Best for: Complex questions, analysis, summaries, insights.
Returns: Conversational AI responses with graph-backed context.

**RAG\_COMPLETION**:
Traditional RAG using document chunks without graph structure.
Best for: Direct document retrieval, specific fact-finding.
Returns: LLM responses based on relevant text chunks.

**CHUNKS**:
Raw text segments that match the query semantically.
Best for: Finding specific passages, citations, exact content.
Returns: Ranked list of relevant text chunks with metadata.

**SUMMARIES**:
Pre-generated hierarchical summaries of content.
Best for: Quick overviews, document abstracts, topic summaries.
Returns: Multi-level summaries from detailed to high-level.

**CODING\_RULES**:
Code-specific search with syntax and semantic understanding.
Best for: Finding functions, classes, implementation patterns.
Returns: Structured code information with context and relationships.

**CYPHER**:
Direct graph database queries using Cypher syntax.
Best for: Advanced users, specific graph traversals, debugging.
Returns: Raw graph query results.

**FEELING\_LUCKY**:
Intelligently selects and runs the most appropriate search type.
Best for: General-purpose queries or when you're unsure which search type is best.
Returns: The results from the automatically selected search type.

**CHUNKS\_LEXICAL**:
Token-based lexical chunk search (BM25-style lexical ranking). Best for: exact-term matching, stopword-aware lookups.
Returns: Ranked text chunks (optionally with scores).

Args:
query\_text: Your question or search query in natural language.
Examples:

* "What are the main themes in this research?"
* "How do these concepts relate to each other?"
* "Find information about machine learning algorithms"
* "What functions handle user authentication?"

query\_type: SearchType enum specifying the search mode.
Defaults to GRAPH\_COMPLETION for conversational AI responses.

user: User context for data access permissions. Uses default if None.

datasets: Dataset name(s) to search within. Searches all accessible if None.
Name lookup is limited to datasets owned by the searching user.
For shared datasets the user can access but does not own, use dataset\_ids instead.

* Single dataset: "research\_papers"
* Multiple datasets: \["docs", "reports", "analysis"]
* None: Search across all user datasets

dataset\_ids: Alternative to datasets - use specific UUID identifiers.
Required when searching a dataset the user can access but does not own.

system\_prompt\_path: Custom system prompt file for LLM-based search types.
Defaults to "answer\_simple\_question.txt".

top\_k: Maximum number of results to return (1-N)
Higher values provide more comprehensive but potentially noisy results.

node\_type: Filter results to specific entity types (for advanced filtering).

node\_name: Filter results to specific named entities (for targeted search).

session\_id: Optional session identifier for caching Q\&A interactions. Defaults to 'default\_session' if None.

verbose: If True, returns detailed result information including graph representation (when possible).

retriever\_specific\_config: Optional dictionary of additional configuration parameters specific to the retriever being used.

include\_references: Defaults to False. When set to True, completion-style answers
(e.g. GRAPH\_COMPLETION, RAG\_COMPLETION) get a deterministic "Evidence:" block appended
to the answer text. The block is assembled in-process from the retrieved chunk payloads
or graph context — no extra LLM call is made — and is omitted silently when no usable
references are found. The return type and response schema are unchanged.

Returns:
list: Search results in format determined by query\_type:

**GRAPH\_COMPLETION/RAG\_COMPLETION**:
\[List of conversational AI response strings]

**CHUNKS**:
\[List of relevant text passages with source metadata]

**SUMMARIES**:
\[List of hierarchical summaries from general to specific]

**CODING\_RULES**:
\[List of structured code information with context]

**FEELING\_LUCKY**:
\[List of results in the format of the search type that is automatically selected]

Performance & Optimization:

* **GRAPH\_COMPLETION**: Slower but most intelligent, uses LLM + graph context
* **RAG\_COMPLETION**: Medium speed, uses LLM + document chunks (no graph traversal)
* **CHUNKS**: Fastest, pure vector similarity search without LLM
* **SUMMARIES**: Fast, returns pre-computed summaries
* **CODING\_RULES**: Medium speed, specialized for code understanding
* **FEELING\_LUCKY**: Variable speed, uses LLM + search type selection intelligently
* **top\_k**: Start with 15, increase for comprehensive analysis (max 100)
* **datasets**: Specify datasets to improve speed and relevance

Next Steps After Search:

* Use results for further analysis or application integration
* Combine different search types for comprehensive understanding
* Export insights for reporting or downstream processing
* Iterate with refined queries based on initial results

Environment Variables:
Required for LLM-based search types (GRAPH\_COMPLETION, RAG\_COMPLETION):

* LLM\_API\_KEY: API key for your LLM provider

Optional:

* LLM\_PROVIDER, LLM\_MODEL: Configure LLM for search responses
* VECTOR\_DB\_PROVIDER: Must match what was used during cognify
* GRAPH\_DATABASE\_PROVIDER: Must match what was used during cognify

## Parameters

<ParamField path="query_text" type="str" required>Natural language search query.</ParamField>
<ParamField path="query_type" type="SearchType" default="SearchType.GRAPH_COMPLETION">Type of search to perform.</ParamField>
<ParamField path="user" type="Optional[User]" default="None">User performing the search.</ParamField>
<ParamField path="datasets" type="Optional[Union[list[str], str]]" default="None">Dataset name(s) to search within. Dataset names are resolved only against datasets owned by the searching user.</ParamField>
<ParamField path="dataset_ids" type="Optional[Union[list[UUID], UUID]]" default="None">Dataset UUID(s) to search within. Use these for shared datasets that the user can access but did not create.</ParamField>
<ParamField path="system_prompt_path" type="str" default="'answer_simple_question.txt'">Path to a custom system prompt file.</ParamField>
<ParamField path="system_prompt" type="Optional[str]" default="None">Inline system prompt string (overrides system\_prompt\_path).</ParamField>
<ParamField path="top_k" type="int" default="15">Maximum number of results to return.</ParamField>
<ParamField path="node_type" type="Optional[Type]" default="NodeSet">Filter results to a specific [DataPoint](/core-concepts/building-blocks/datapoints) subclass type. Pass any class that inherits from `DataPoint`, including [custom classes](/guides/custom-data-models) you define in your own code. Defaults to `NodeSet` (the built-in group container). Internal Cognee types such as `ParagraphNode` are not part of the public API and cannot be used here.</ParamField>
<ParamField path="node_name" type="Optional[List[str]]" default="None">Names of the node sets to filter results to. Pass the same names used in `cognee.add(..., node_set=[...])`. Works with graph-completion search types (e.g. `GRAPH_COMPLETION`, `GRAPH_COMPLETION_COT`, `TEMPORAL`). See [NodeSets](/core-concepts/further-concepts/node-sets).</ParamField>
<ParamField path="node_name_filter_operator" type="str" default="&#x22;OR&#x22;">Controls how multiple `node_name` values are combined. `"OR"` returns results connected to any of the specified node sets; `"AND"` returns results connected to all of them.</ParamField>
<ParamField path="only_context" type="bool" default="False">If true, return only the retrieved context without LLM completion.</ParamField>
<ParamField path="session_id" type="Optional[str]" default="None">Session ID for conversational context tracking.</ParamField>
<ParamField path="wide_search_top_k" type="Optional[int]" default="100">Number of candidates for the wide search phase.</ParamField>
<ParamField path="triplet_distance_penalty" type="Optional[float]" default="6.5">Penalty factor for triplet distance in scoring.</ParamField>
<ParamField path="verbose" type="bool" default="False">Include detailed retrieval metadata in results.</ParamField>
<ParamField path="retriever_specific_config" type="Optional[dict]" default="None">Additional configuration for the selected retriever.</ParamField>
<ParamField path="llm_config" type="Optional[LLMConfig]" default="None">LLM settings to install into the current async context for completion-based search types. When omitted, Cognee uses the active context config or global LLM config. Import `LLMConfig` from `cognee.infrastructure.llm.config`.</ParamField>
<ParamField path="embedding_config" type="Optional[EmbeddingConfig]" default="None">Embedding settings to install into the current async context for semantic retrieval. When omitted, Cognee uses the active context config or global embedding config. Import `EmbeddingConfig` from `cognee.infrastructure.databases.vector.embeddings.config`.</ParamField>
<ParamField path="include_references" type="bool" default="False">When set to `True`, appends a deterministic `Evidence:` block to completion-style answers (such as `GRAPH_COMPLETION` and `RAG_COMPLETION`), listing the source chunks or graph context behind the answer. The block is built in-process with no extra LLM call, the response schema is unchanged, and it is omitted silently when no usable references exist.</ParamField>

## Returns

`List[SearchResult]`

For the full breakdown of per-mode output shapes, see [Search](/core-concepts/main-operations/legacy-operations/search). The search-type accordions there now document each mode’s output directly.

## Examples

```python theme={null}
import cognee
from cognee import SearchType

# Default graph completion search
results = await cognee.search("What is Cognee?")

# RAG-style search
results = await cognee.search(
    "How does chunking work?",
    query_type=SearchType.RAG_COMPLETION,
)

# Get raw chunks without LLM completion
results = await cognee.search(
    "knowledge graph",
    query_type=SearchType.CHUNKS,
    top_k=5,
)

# Search within specific datasets
results = await cognee.search(
    "deployment options",
    datasets=["infrastructure_docs"],
)

# Context-only mode (no LLM answer)
context = await cognee.search(
    "What are the main entities?",
    only_context=True,
)

# Session-aware conversational search
results = await cognee.search(
    "Tell me more about that",
    session_id="conversation_123",
)

# Recommended v1.0 entry point for global context summaries
results = await cognee.recall(
    "What is the current state of the rollout plan?",
    query_type=SearchType.GRAPH_COMPLETION,
    datasets=["product_docs"],
    retriever_specific_config={
        "include_global_context_index": True,
        "global_context_index_top_k": 3,
    },
)

# Filter to a specific node set (data tagged with node_set=["projectA"] during add())
from cognee.modules.engine.models.node_set import NodeSet
results = await cognee.search(
    "What are the key decisions?",
    node_type=NodeSet,
    node_name=["projectA"],
)

# AND operator — only return results that belong to both node sets
results = await cognee.search(
    "Cross-cutting concerns",
    node_type=NodeSet,
    node_name=["projectA", "finance"],
    node_name_filter_operator="AND",
)
```

## Troubleshooting

<Accordion title="Fixing 'Nodeset does not exist' (EntityNotFoundError)">
  NodeSets are **created at ingestion time** and **referenced at search time** — the names must match. During `remember()` or `add()`, the `node_set` tags you pass are attached to your data and materialized as `NodeSet` nodes when the graph is built. At search time, passing `node_type=NodeSet` with `node_name=[...]` projects only the subgraph connected to those names.

  If none of the requested names resolve to a populated subgraph, lower-level graph projection can raise:

  ```text theme={null}
  EntityNotFoundError: Nodeset does not exist, or empty nodeset projected from the database.
  ```

  In regular `search()` or `recall()` flows, this can also appear as empty context or no results, depending on the search path.

  Common causes:

  * **The name was never created during ingestion.** You filtered on a name (e.g. `"finance"`) that was not passed in `node_set` during any `remember()` or `add()` call. A NodeSet only exists if data was tagged with it.
  * **A typo or case mismatch.** Names are matched exactly, so `"Finance"` and `"finance"` are different NodeSets.
  * **Search ran before ingestion finished.** With `run_in_background=True`, await the `RememberResult` before searching so the `NodeSet` nodes exist.
  * **Wrong scope.** NodeSets live in the graph they were ingested into. If you query a different dataset or a different user/tenant under [multi-user mode](/core-concepts/multi-user-mode/multi-user-mode-overview), the names won't be found.
  * **`AND` filtering with no overlap.** Using `node_name_filter_operator="AND"` requires nodes connected to *all* listed names simultaneously; if no node belongs to every name, the projection is empty.

  To resolve it, confirm the exact NodeSet names you used during ingestion and reuse them verbatim in `search()` or `recall()`, scoped to the same dataset.
</Accordion>

<Warning>
  With backend access control enabled, `datasets=["name"]` does not mean "any dataset with this name that I can read". It resolves names only within datasets owned by the current user. If Bob is querying Alice's shared dataset `shared_dataset`, `datasets=["shared_dataset"]` can fail with `DatasetNotFoundError` even when Bob has permission to read it. In that case, use `dataset_ids=[shared_id]`.
</Warning>

See [SearchType](/python-api/search-type) for all available search modes.

<Note>
  `include_global_context_index` only has an effect after the dataset has been improved with `build_global_context_index=True`. See [Global Context Index](/core-concepts/further-concepts/global-context-index).
</Note>
