Skip to main content

cognee.search()

async def search(
    query_text: str,
    query_type: SearchType = SearchType.GRAPH_COMPLETION,
    user: Optional[User] = None,
    datasets: Optional[Union[list[str], str]] = None,
    dataset_ids: Optional[Union[list[UUID], UUID]] = None,
    system_prompt_path: str = 'answer_simple_question.txt',
    system_prompt: Optional[str] = None,
    top_k: int = 10,
    node_type: Optional[Type] = NodeSet,
    node_name: Optional[List[str]] = None,
    node_name_filter_operator: str = "OR",
    only_context: bool = False,
    session_id: Optional[str] = None,
    wide_search_top_k: Optional[int] = 100,
    triplet_distance_penalty: Optional[float] = 3.5,
    verbose: bool = False,
    retriever_specific_config: Optional[dict] = None,
) -> List[SearchResult]

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: GRAPH_COMPLETION (Default - Recommended): 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 (e.g., Jaccard). 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 GRAPH_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. Defaults to ‘default_session’ if None. 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. 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 10, 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

query_text
str
required
Natural language search query.
query_type
SearchType
default:"SearchType.GRAPH_COMPLETION"
Type of search to perform.
user
Optional[User]
default:"None"
User performing the search.
datasets
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.
dataset_ids
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.
system_prompt_path
str
default:"'answer_simple_question.txt'"
Path to a custom system prompt file.
system_prompt
Optional[str]
default:"None"
Inline system prompt string (overrides system_prompt_path).
top_k
int
default:"10"
Maximum number of results to return.
node_type
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.
node_name
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.
node_name_filter_operator
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.
only_context
bool
default:"False"
If true, return only the retrieved context without LLM completion.
session_id
Optional[str]
default:"None"
Session ID for conversational context tracking.
wide_search_top_k
Optional[int]
default:"100"
Number of candidates for the wide search phase.
triplet_distance_penalty
Optional[float]
default:"3.5"
Penalty factor for triplet distance in scoring.
verbose
bool
default:"False"
Include detailed retrieval metadata in results.
retriever_specific_config
Optional[dict]
default:"None"
Additional configuration for the selected retriever.

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.

Examples

import cognee
from cognee import SearchType

# Default graph completion search
results = await cognee.search("What is Cognee?")

# RAG-style search
results = await cognee.search(
    "How does chunking work?",
    query_type=SearchType.RAG_COMPLETION,
)

# Get raw chunks without LLM completion
results = await cognee.search(
    "knowledge graph",
    query_type=SearchType.CHUNKS,
    top_k=5,
)

# Search within specific datasets
results = await cognee.search(
    "deployment options",
    datasets=["infrastructure_docs"],
)

# Context-only mode (no LLM answer)
context = await cognee.search(
    "What are the main entities?",
    only_context=True,
)

# Session-aware conversational search
results = await cognee.search(
    "Tell me more about that",
    session_id="conversation_123",
)

# Recommended v1.0 entry point for global context summaries
results = await cognee.recall(
    "What is the current state of the rollout plan?",
    query_type=SearchType.GRAPH_COMPLETION,
    datasets=["product_docs"],
    retriever_specific_config={
        "include_global_context_index": True,
        "global_context_index_top_k": 3,
    },
)

# Filter to a specific node set (data tagged with node_set=["projectA"] during add())
from cognee.modules.engine.models.node_set import NodeSet
results = await cognee.search(
    "What are the key decisions?",
    node_type=NodeSet,
    node_name=["projectA"],
)

# AND operator — only return results that belong to both node sets
results = await cognee.search(
    "Cross-cutting concerns",
    node_type=NodeSet,
    node_name=["projectA", "finance"],
    node_name_filter_operator="AND",
)

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:
EntityNotFoundError: Nodeset does not exist, or empty nodeset projected from the database.
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.