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 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 HYBRID_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. 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 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

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.
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

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 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:
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.