cognee.search()
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
- “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?”
- Single dataset: “research_papers”
- Multiple datasets: [“docs”, “reports”, “analysis”]
- None: Search across all user datasets
default_session_<dataset_id>
when the dataset is known, falling back to the global ‘default_session’ when it
is not. Searches against different datasets therefore never share one session.
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
- 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
- LLM_API_KEY: API key for your LLM provider
- 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
str
required
Natural language search query.
SearchType
default:"SearchType.HYBRID_COMPLETION"
Type of search to perform.
Optional[User]
default:"None"
User performing the search.
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.
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.
str
default:"'answer_simple_question.txt'"
Path to a custom system prompt file.
Optional[str]
default:"None"
Inline system prompt string (overrides system_prompt_path).
int
default:"15"
Maximum number of results to return.
Optional[Type]
default:"NodeSet"
Filter results to a specific DataPoint subclass type. Pass any class that inherits from
DataPoint, including custom classes 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.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.str
default:"\"OR\""
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.bool
default:"False"
If true, return only the retrieved context without LLM completion.
Union[ContextFormat, str]
default:"\"context\""
Shape of the value returned when
only_context=True; ignored otherwise. "context" (the default) returns the bare retrieval context, byte-identical to earlier releases. "prompt" returns the whole envelope a completion would be sent — see The prompt envelope below. Any other value raises InvalidContextFormatError (a CogneeValidationError, HTTP 422).Optional[str]
default:"None"
Session ID for conversational context tracking.
Optional[int]
default:"100"
Number of candidates for the wide search phase.
Optional[float]
default:"6.5"
Penalty factor for triplet distance in scoring.
bool
default:"False"
Include detailed retrieval metadata in results:
text_result, context_result, and objects_result, plus three more keys when combined with context_format="prompt" (see The prompt envelope).Optional[dict]
default:"None"
Additional configuration for the selected retriever.
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.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.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.Returns
List[SearchResult]
For the full breakdown of per-mode output shapes, see Search. The search-type accordions there now document each mode’s output directly.
The prompt envelope
only_context=True returns the bare retrieval context — no session guidance, no conversation history, no rendered prompt — while a real completion is sent all of it. Pass context_format="prompt" to get the whole envelope instead, as a dict with question, context, session_context, user_prompt, and system_prompt. Import ContextFormat from cognee.modules.search.types, or pass the plain string.
"context", which unwraps to the context itself.
user_promptandsystem_promptareNonefor the non-generative search types (CHUNKS,SUMMARIES,CODE, …), which have no prompt template, and forCYPHERandAGENTIC_COMPLETION, which opt out of the preview. The session layer is still reported for all of them.session_contextis the session layer forsession_id, or for the dataset’s default session when you omit it. With caching off it falls back to the durable preference block, and it is""only when no session layer resolves at all.- With
verbose=True, the same three values also appear on the verbose dict assession_context_result,user_prompt_result, andsystem_prompt_result. They are keyed off the requested format rather than off whether the values are set, so they are always present (possiblyNone) when you ask for the prompt shape, and never present otherwise.
The envelope reports the prompt for the context actually retrieved, not a replay of a full turn. A real turn first rewrites your question with an LLM call, and that rewrite fills
question, selects the conversation history, and ranks the guidance block. The preview cannot make that call, so it uses your raw query for all three.Examples
Troubleshooting
Fixing 'Nodeset does not exist' (EntityNotFoundError)
Fixing 'Nodeset does not exist' (EntityNotFoundError)
NodeSets are created at ingestion time and referenced at search time — the names must match. During In regular
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: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 innode_setduring anyremember()oradd()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 theRememberResultbefore searching so theNodeSetnodes 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, the names won’t be found.
ANDfiltering with no overlap. Usingnode_name_filter_operator="AND"requires nodes connected to all listed names simultaneously; if no node belongs to every name, the projection is empty.
search() or recall(), scoped to the same dataset.include_global_context_index only has an effect after the dataset has been improved with build_global_context_index=True. See Global Context Index.