Skip to main content

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
Search Types & Use Cases: HYBRID_COMPLETION (Default - Recommended): Natural language Q&A over document passages plus the entity neighbourhoods around them, answered by an LLM. Best for: Most questions, where both source text and graph structure help. Returns: Conversational AI responses backed by passages and graph context. GRAPH_COMPLETION: 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 summaries of content. Best for: Quick overviews, document abstracts, topic summaries. Returns: Generated content summaries. 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. Disabled by default; set ALLOW_CYPHER_QUERY=true to enable it (also covers NATURAL_LANGUAGE). 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 HYBRID_COMPLETION for conversational AI responses. user: User context for data access permissions. Uses default if None. datasets: Dataset name(s) to search within. If None (and no dataset_ids), the search is routed to the best-matching readable datasets (see the datasets parameter below). 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: Routed to the best-matching readable 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: What the names in node_name are. NodeSet (the default) means node-set tags; any other graph node type (TextDocument, Entity, …) means the named nodes of that type and their one-hop neighbours. node_name: Names to scope the search to, read according to node_type. Node-set tags are honoured by CHUNKS, RAG_COMPLETION, HYBRID_COMPLETION, TEMPORAL, CODING_RULES and the graph-completion family. A graph scope is honoured by the graph-completion family (it ranks the projected nodes), by CHUNKS and RAG_COMPLETION (they score the chunks in the projection: a document’s chunks, an entity’s mentions) and by HYBRID_COMPLETION (defers to GRAPH_COMPLETION). A search type that cannot apply the filter raises QueryValidationError, node_name without a node_type raises too, and FEELING_LUCKY picks only among the types that can apply it. session_id: Optional session identifier for caching Q&A interactions. When None, resolves to the dataset-scoped default session: 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
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

str
required
Natural language search query.
SearchType
default:"SearchType.HYBRID_COMPLETION"
Type of search to perform.
User | None
default:"None"
User performing the search.
list[str] | str | None
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.) 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.
list[UUID] | UUID | None
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'"
Name of a system prompt file in cognee’s built-in prompts directory (cognee/infrastructure/llm/prompts). Paths that resolve outside it raise PromptPathOutsideBaseDirectoryError.
str | None
default:"None"
Inline system prompt string (overrides system_prompt_path).
int
default:"15"
Maximum number of results to return.
type | None
default:"NodeSet"
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.
list[str] | None
default:"None"
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 in cognee.add(..., node_set=[...]). Honoured by CHUNKS, RAG_COMPLETION, HYBRID_COMPLETION, HYBRID_COMPLETION_DECOMPOSITION, TEMPORAL, CODING_RULES and 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. CHUNKS and RAG_COMPLETION score only the chunks inside the projection, which means a document’s own chunks or the chunks that mention an entity. HYBRID_COMPLETION runs as GRAPH_COMPLETION. HYBRID_COMPLETION_DECOMPOSITION raises QueryValidationError and points you to GRAPH_COMPLETION_DECOMPOSITION. TEMPORAL and CODING_RULES do not honour a graph scope.
Any other combination raises 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.
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.
str | None
default:"None"
Session ID for conversational context tracking.
int | None
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.
float | None
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.
float
default:"0.0"
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.
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).
dict | None
default:"None"
Additional configuration for the selected retriever.
int | None
default:"None"
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.
int | None
default:"None"
Maximum number of vector-hit seeds, nearest first, that the neighborhood_depth expansion grows from. None uses all seeds. Must be a positive integer.
list[str | Skill] | None
default:"None"
Skill names or Skill objects to load into the agentic retriever. Requires query_type=SearchType.AGENTIC_COMPLETION; any other type raises InvalidAgenticSearchConfig.
list[str] | None
default:"None"
Allow-list of tool names the agentic retriever may call. Requires query_type=SearchType.AGENTIC_COMPLETION, like skills.
int | None
default:"None"
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).
dict[str, Any] | None
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, 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.
LLMConfig | None
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.
EmbeddingConfig | None
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 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.
Without 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, CODE and the other non-generative types have no prompt template, and CYPHER and AGENTIC_COMPLETION opt out, so only_context=True gives them the bare retrieval context and both prompt keys come back None.
  • An empty retrieval returns the bare (empty) context. A prompt wrapped around nothing would read as a hit, so “nothing found” stays detectable.
The prompts are assembled read-only by the same code a real completion uses, so preview and production cannot drift: no LLM completion call, no session write, and no QA turn recorded. It is not free — the session layer’s conversation-history lookup embeds the query. That is one embedding call per search, shared across a multi-dataset fan-out rather than paid per dataset, and only when a prompt is actually built.
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.
Migrating from 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

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.
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 any nodes, lower-level graph projection can raise:
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 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, 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.
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: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:
The error key appears only on entries that could not be searched, so results from populated datasets keep their usual shape.
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"] fails with DatasetNotFoundError even when Bob has permission to read it. In that case, use dataset_ids=[shared_id].Resolution is strict, so this applies to a mistyped or deleted name too, and to any unresolvable name in a list: datasets=["research_papers", "typo"] raises DatasetNotFoundError (HTTP 404) naming 'typo' instead of quietly answering from research_papers alone. Duplicate names are reported once. Validate names before querying, or pass dataset_ids to search by UUID.
See SearchType for all available search modes.
include_global_context_index only has an effect after the dataset has been improved with build_global_context_index=True. See Global Context Index.