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.
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.
You get one dict per dataset, so a single-dataset search returns a one-element list — unlike "context", which unwraps to the context itself.
  • user_prompt and system_prompt are None for the non-generative search types (CHUNKS, SUMMARIES, CODE, …), which have no prompt template, and for CYPHER and AGENTIC_COMPLETION, which opt out of the preview. The session layer is still reported for all of them.
  • session_context is the session layer for session_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 as session_context_result, user_prompt_result, and system_prompt_result. They are keyed off the requested format rather than off whether the values are set, so they are always present (possibly None) when you ask for the prompt shape, and never present otherwise.
Building the envelope reconstructs the session layer read-only: no LLM call is made and nothing is written back to the session. It does cost one conversation-history read, which embeds the query.
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

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 a populated subgraph, lower-level graph projection can raise:
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.
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"] can fail with DatasetNotFoundError even when Bob has permission to read it. In that case, use dataset_ids=[shared_id].
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.