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, and strictly: a name that resolves to no such dataset raises
DatasetNotFoundError (HTTP 404) listing the names that did not resolve, rather than being dropped from the search scope. Passing dataset_ids avoids this only if you pass it instead of datasets — supply both and the names are still resolved strictly, so an unresolvable one fails the call even though dataset_ids is what determines the scope. (recall() differs here: it skips name resolution entirely when dataset_ids is given.)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 what the LLM would have received instead of its answer, making no completion call. For completion search types that is the user prompt (
BROAD still makes its decision call and runs its query during retrieval); the system prompt travels separately. Retrieval-only types return their retrieved context. See Inspecting the LLM input.Optional[str]
default:"None"
Session ID for conversational context tracking.
Optional[int]
default:"None"
Number of candidates for the wide search phase. When omitted, retrievers that use it fall back to their own default of
100. Honored by the graph-completion family, AGENTIC_COMPLETION, and RAG_COMPLETION, and ignored by TEMPORAL; any explicit value with the default HYBRID_COMPLETION raises InvalidHybridSearchConfig (a CogneeValidationError, HTTP 422) before retrieval starts — see Search Basics — Advanced Parameters.Optional[float]
default:"None"
Penalty factor for triplet distance in scoring. When omitted, graph retrievers fall back to their own default of
6.5. Graph-only, and rejected on HYBRID_COMPLETION exactly like wide_search_top_k.bool
default:"False"
Include detailed retrieval metadata in results:
text_result, context_result, objects_result, user_prompt_result, and system_prompt_result. The last two are set only by an only_context=True call on a search type that sends a templated prompt, and are None otherwise (see Inspecting the LLM input).Optional[dict]
default:"None"
Additional configuration for the selected retriever.
Optional[dict]
default:"None"
Structured operation and arguments for
SearchType.CODE — for example {"operation": "impact_analysis", "name": "UserService", "max_depth": 3}. The operation key selects one of query_facts, explore, traverse, find_path, impact_analysis, insights, architecture, or delta; omitting it runs explore seeded with query_text. Add "diagram": "mermaid" (or "dot") to any operation to get diagram source under result["diagram"]. Passing it with any other query_type raises InvalidCodeSearchConfig. Every operation’s arguments and the fact kinds they filter on are listed under SearchType — CODE; the Code Graph guide shows how to build the graph this searches.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 behind the answer, and fills the result’s evidence list with structured references to the chunks, graph nodes, and graph edges that were placed in the LLM context. For graph completion the cited chunks come from the edge-evidence sidecar, which requires Alembic revision f3a7b9c1d2e4. The block is built in-process with no extra LLM call and 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.
Inspecting the LLM input
only_context=True returns what the LLM would have been sent instead of its answer, and makes no completion call. For completion search types (GRAPH_COMPLETION, RAG_COMPLETION, …) that is the user prompt: the conversation history, then the question and retrieval context rendered through the retriever’s user template, then the session guidance block. The system prompt — the retriever’s task template — is a separate value, because the LLM receives the two as separate messages.
verbose=True, search() hands back the user prompt as the search result and the system prompt is not reachable. recall() carries both on every item — item.text and item.system_prompt — with no flag needed.
- Retrieval-only types return their context, unchanged.
CHUNKS,SUMMARIES,CODEand the other non-generative types have no prompt template, andCYPHERandAGENTIC_COMPLETIONopt out, soonly_context=Truegives them the bare retrieval context and both prompt keys come backNone. - An empty retrieval returns the bare (empty) context. A prompt wrapped around nothing would read as a hit, so “nothing found” stays detectable.
The result is the prompt for the context actually retrieved, not a replay of a full turn. A real sequential turn first rewrites your question with an LLM call, and that rewrite fills the question slot, selects the conversation history, and ranks the guidance block. This path cannot make that call, so it uses your raw query for all three.
context_format. The opt-in context_format parameter that shipped in 1.5.4 has been removed — only_context=True now always returns the full LLM input, so there is nothing to opt into. Passing context_format= to search() or recall() raises TypeError; contextFormat on the HTTP API is ignored rather than rejected. The old "prompt" envelope dict is gone with it: read user_prompt_result and system_prompt_result off the verbose payload instead of envelope["user_prompt"] / envelope["system_prompt"].
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 The node count alone decides this: a nodeset whose nodes exist but have no relationships between them projects with an empty edge list rather than raising.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 any nodes, 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.Empty graph vs. no match (NoDataError)
Empty graph vs. no match (NoDataError)
Completion searches no longer send an empty context to the LLM for a single query, so an empty result means nothing was found rather than an LLM reply such as “There is no context provided…”. Two different states can leave you with nothing:The
This applies to
GRAPH_COMPLETION and the other graph-completion types, RAG_COMPLETION, TRIPLET_COMPLETION, and the default HYBRID_COMPLETION. AGENTIC_COMPLETION is the exception: its skills and tools can answer without memory context, so it still runs on an empty context. A skipped completion records no Q&A turn in the session.The empty-graph check runs for the graph-completion types and HYBRID_COMPLETION. RAG_COMPLETION and TRIPLET_COMPLETION raise the same NoDataError when their vector collection is missing — for TRIPLET_COMPLETION, also on a populated graph that never ran create_triplet_embeddings.With backend access control enabled (the default), when you search several datasets at once, one empty dataset does not fail the call. search() raises NoDataError only when every searched dataset is empty. Otherwise each dataset that could not be searched comes back as an entry with an empty search_result and an error key explaining why, next to the normal results from the other datasets:error key appears only on entries that could not be searched, so results from populated datasets keep their usual shape.include_global_context_index only has an effect after the dataset has been improved with build_global_context_index=True. See Global Context Index.