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: Routed to the best-matching readable 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 generated content summaries]
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
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.) When neither datasets nor dataset_ids is given, the search is routed: every readable dataset is scored against the query and only the best-matching ones are searched. An explicit scope is never routed. See Dataset routing.Dataset UUID(s) to search within. Use these for shared datasets that the user can access but did not create.
Name of a system prompt file in cognee’s built-in prompts directory (
cognee/infrastructure/llm/prompts). Paths that resolve outside it raise PromptPathOutsideBaseDirectoryError.Sets what the names in
node_name mean. With NodeSet (the default), they are node-set tags. With any other graph node type, such as TextDocument, Entity, SchemaColumn or a custom DataPoint class, the scope is the named nodes of that type (matched by their name) plus their one-hop neighbours (a graph scope). For example, node_type=SchemaColumn with node_name=["genre:name"] scopes a search to one dlt column. Internal Cognee types such as ParagraphNode are not part of the public API and cannot be used here. Passing node_name with node_type=None raises QueryValidationError.Names to scope the search to.
node_type decides how they are read.- Node-set scope (
node_type=NodeSet): pass the same names you used incognee.add(..., node_set=[...]). Honoured byCHUNKS,RAG_COMPLETION,HYBRID_COMPLETION,HYBRID_COMPLETION_DECOMPOSITION,TEMPORAL,CODING_RULESand the graph-completion family (GRAPH_COMPLETION,GRAPH_COMPLETION_COT,GRAPH_COMPLETION_CONTEXT_EXTENSION,GRAPH_COMPLETION_DECOMPOSITION,GRAPH_SUMMARY_COMPLETION,AGENTIC_COMPLETION). See NodeSets. - Graph scope (any other
node_type): the graph-completion family ranks the projected nodes.CHUNKSandRAG_COMPLETIONscore only the chunks inside the projection, which means a document’s own chunks or the chunks that mention an entity.HYBRID_COMPLETIONruns asGRAPH_COMPLETION.HYBRID_COMPLETION_DECOMPOSITIONraisesQueryValidationErrorand points you toGRAPH_COMPLETION_DECOMPOSITION.TEMPORALandCODING_RULESdo not honour a graph scope.
QueryValidationError, and the error names the search types that would apply the filter. FEELING_LUCKY chooses only among those types.With a graph scope (and no neighborhood_depth), graph-completion triplet retrieval projects the scope from the graph first and ranks the scoped nodes and edges by their real vector distance to the query; scoped nodes without a stored vector keep the default distance penalty. On LanceDB, PGVector, Turso and Neptune Analytics only the scoped vectors are scored; other vector adapters search their whole collections to rank the same scope, which is slower. On CHUNKS and RAG_COMPLETION, a graph scope needs a vector adapter that implements score_by_ids. Without it, the search raises CogneeConfigurationError (ScopedChunkSearchUnsupported) rather than scanning the whole collection.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.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.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.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.How much stored feedback weights count when graph retrievers score triplets. The default comes from
DEFAULT_FEEDBACK_INFLUENCE (0.0, feedback ignored). With the default HYBRID_COMPLETION, a value above 0 makes the search use GRAPH_COMPLETION instead.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).Replace the 1-hop graph projection with a k-hop neighborhood grown from the vector-hit seeds. Must be a positive integer. With the default
HYBRID_COMPLETION, setting it makes the search use GRAPH_COMPLETION instead. See Search — Graph completion.Maximum number of vector-hit seeds, nearest first, that the
neighborhood_depth expansion grows from. None uses all seeds. Must be a positive integer.Skill names or
Skill objects to load into the agentic retriever. Requires query_type=SearchType.AGENTIC_COMPLETION; any other type raises InvalidAgenticSearchConfig.Allow-list of tool names the agentic retriever may call. Requires
query_type=SearchType.AGENTIC_COMPLETION, like skills.Maximum number of reasoning rounds before the retriever must answer. Must be a positive integer. It is merged into
retriever_specific_config, so it applies to AGENTIC_COMPLETION (default 6 tool-call rounds) and GRAPH_COMPLETION_COT (default 4 follow-up rounds).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, delta, capabilities, search, neighbors, subgraph, flows, hubs, or ask; omitting it runs explore seeded with query_text. Add "diagram": "mermaid" (or "dot") to any operation except capabilities, search, flows, hubs and ask 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.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.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.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 the hybrid types, only the chunks the answer cites). 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
QueryValidationError: '... does not apply node_name'
QueryValidationError: '... does not apply node_name'
The search type you picked cannot apply this
node_name filter. For example, SUMMARIES applies no node_name filter at all, and TEMPORAL applies a node-set scope but not a graph scope. The error message lists the search types that do apply it, so switch to one of them. A node_name passed with node_type=None is refused the same way. Pass NodeSet for node-set tags, or the graph type to scope to.The default node_type is NodeSet. A document name passed without node_type=TextDocument is therefore matched against node-set tags and usually returns nothing.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 raises the same NoDataError when its vector collection is missing. The deprecated TRIPLET_COMPLETION runs as GRAPH_COMPLETION, so it gets the empty-graph check.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.