> ## Documentation Index
> Fetch the complete documentation index at: https://cortex-ad5578da.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Hybrid Search

> Search for relevant content within your indexed sources or user memories.
    
    Results are ranked by relevance and can be customized with parameters like 
    result limits, alpha weighting, and recency preferences.
    
    Use `search_mode` to specify what to search:
    - "sources" (default): Search over indexed documents
    - "memories": Search over user memories (uses inferred content)
    
    Use `mode` to control retrieval quality:
    - "fast" (default): Single query, faster response
    - "accurate": Multi-query generation with reranking, higher quality

export const TableOfContents = ({title = 'On this page', items, minHeadingLevel = 2, maxHeadingLevel = 3, className = '', activeClassName = 'text-primary dark:text-primary-light border-primary dark:border-primary-light hover:border-primary dark:hover:border-primary-light', inactiveClassName = 'hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-300'}) => {
  const [toc, setToc] = useState(items ?? []);
  const [activeId, setActiveId] = useState('');
  useEffect(() => {
    if (items && items.length) return;
    if (typeof document === 'undefined') return;
    const selectors = [];
    for (let lvl = minHeadingLevel; lvl <= maxHeadingLevel; lvl++) {
      selectors.push(`h${lvl}`);
    }
    const nodes = Array.from(document.querySelectorAll(selectors.join(','))).filter(el => el.id);
    const built = [];
    let currentTop = null;
    nodes.forEach(el => {
      const level = Number(el.tagName.slice(1));
      const node = {
        id: el.id,
        label: el.textContent.trim(),
        href: `#${el.id}`,
        children: []
      };
      if (level === minHeadingLevel) {
        built.push(node);
        currentTop = node;
      } else if (level > minHeadingLevel && currentTop) {
        currentTop.children.push(node);
      } else {
        built.push(node);
      }
    });
    setToc(built);
  }, [items, minHeadingLevel, maxHeadingLevel]);
  useEffect(() => {
    if (typeof document === 'undefined') return;
    const applyHash = () => {
      const h = window.location.hash.replace('#', '');
      if (h) setActiveId(h);
    };
    applyHash();
    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          setActiveId(entry.target.id);
        }
      });
    }, {
      rootMargin: '0px 0px -70% 0px',
      threshold: 0.1
    });
    const ids = toc.flatMap(i => [i, ...i.children ?? []]).map(i => i.id);
    ids.forEach(id => {
      const el = document.getElementById(id);
      if (el) observer.observe(el);
    });
    window.addEventListener('hashchange', applyHash);
    return () => {
      window.removeEventListener('hashchange', applyHash);
      observer.disconnect();
    };
  }, [toc]);
  const Item = ({node, depth = 0}) => {
    const isActive = activeId === node.id;
    return <li className="toc-item relative ml-6" data-depth={depth}>
        <a href={node.href} className={`py-1 block font-medium ${isActive ? activeClassName : inactiveClassName}`} style={depth > 0 ? {
      marginLeft: `${depth}rem`
    } : {}} onClick={() => setActiveId(node.id)}>
          {node.label}
        </a>
        {node.children && node.children.length > 0 && <>
            {node.children.map(child => <Item node={child} depth={depth + 1} key={child.href} />)}
          </>}
      </li>;
  };
  const data = toc && toc.length ? toc : items || [];
  return <div className={`text-gray-600 text-sm leading-6 w-[18rem] pb-4 -mt-10 pt-10 hidden xl:block ${className}`} id="table-of-contents-custom">
      <ul id="table-of-contents-custom-content" className="toc">
        <li className="toc-item relative">
          <div className="text-gray-700 dark:text-gray-300 font-medium flex items-center space-x-2 py-1">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" xmlns="http://www.w3.org/2000/svg" className="h-3 w-3">
              <path d="M2.44434 12.6665H13.5554" strokeLinecap="round" strokeLinejoin="round"></path>
              <path d="M2.44434 3.3335H13.5554" strokeLinecap="round" strokeLinejoin="round"></path>
              <path d="M2.44434 8H7.33323" strokeLinecap="round" strokeLinejoin="round"></path>
            </svg>
            <span>{title}</span>
          </div>
        </li>
        {data.map(node => <Item node={node} key={node.href} />)}
      </ul>
    </div>;
};

<Panel>
  <TableOfContents />
</Panel>

<Tip> Hit the `Try it` button to try this API now in our playground. It's the best way to check the full request and response in one place, customize your parameters, and generate ready-to-use code snippets.</Tip>

### Examples

<Tabs>
  <Tab title="API Request">
    ```bash theme={null}
    curl -X 'POST' \
    'https://api.usecortex.ai/search/hybrid-search' \
    -H 'accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{
    "tenant_id": "string",
    "sub_tenant_id": "string",
    "query": "string",
    "max_chunks": 0,
    "mode": "fast",
    "alpha": "0.8",
    "recency_bias": 0,
    "num_related_chunks": 10,
    "personalise_search": false,
    "graph_context": false,
    "extra_context": "string",
    "search_mode": "sources"
    }'
    ```
  </Tab>

  <Tab title="TypeScript">
    ```ts theme={null}
    const results = await client.search.retrieve({
      query: "Which mode does user prefer",
      tenant_id: "tenant_1234",
      sub_tenant_id: "sub_tenant_4567",
      alpha: 0.8,
      recency_bias: 0,
      personalise_search: true
    });
    ```
  </Tab>

  <Tab title="Python (Sync)">
    ```python theme={null}
    # Async usage is similar, just use async_client and await
    results = client.search.retrieve(
        query="Which mode does user prefer",
        tenant_id="tenant_1234",
        sub_tenant_id="sub_tenant_4567",
        alpha=0.8,
        recency_bias=0,
        personalise_search=True
    )
    ```
  </Tab>
</Tabs>

Search across your tenant's knowledge base using both semantic and keyword matching for comprehensive results.

<Note>
  **Default Sub-Tenant Behavior**: If you don't specify a `sub_tenant_id`, the search will be performed within the default sub-tenant created when your tenant was set up. This searches across organization-wide documents.
</Note>

## Search Modes

The Hybrid Search endpoint combines multiple search strategies to provide the most relevant results:

### Semantic Search

* **Purpose**: Finds content based on meaning and context, not just exact keywords
* **Best for**: Conceptual queries, finding related content, understanding intent
* **Example**: Searching for "machine learning" will also find content about "AI", "neural networks", "deep learning"

### Keyword Search

* **Purpose**: Finds content containing specific terms or phrases
* **Best for**: Exact term matching, technical specifications, proper nouns
* **Example**: Searching for "TensorFlow 2.0" will find documents mentioning this specific version

### Hybrid Approach

* **Purpose**: Combines semantic understanding with keyword precision
* **Best for**: Most use cases where you want both relevance and accuracy
* **Example**: "Python data analysis libraries" finds both semantic matches (pandas, numpy) and exact keyword matches

## Search Parameters

### Alpha Parameter

Controls the balance between semantic and keyword search:

* **`0.0`** - Pure keyword search only
  * Best for: Exact term matching, technical specifications
  * Use when: You need precise keyword matches
* **`1.0`** - Pure semantic search only
  * Best for: Conceptual queries, finding related content
  * Use when: You want to discover related concepts
* **`0.8`** - Default balanced approach (recommended)
  * Best for: Most general use cases
  * Provides optimal balance of precision and recall
* **`"auto"`** - Intelligent auto-selection
  * Cortex analyzes your query and chooses the optimal alpha
  * Best for: When you're unsure which approach to use

### Recency Bias

Controls how much recent content is prioritized:

* **`0.0`** - No recency bias (default)
* **`0.1-0.5`** - Light to moderate recency preference
* **`0.6-1.0`** - Strong recency preference
* **Best for**: News, documentation updates, time-sensitive information

### Max Chunks

Controls the number of results returned:

* **Range**: 1-1001 chunks
* **Default**: System limit
* **Recommendation**: Start with 10-20 for most use cases

### Personalise Search

Enables personalized search results based on user memories from the corresponding tenant and sub-tenant combination:

* **`true`** - Enable personalized search results
  * Leverages user memories stored in the tenant/sub-tenant combination
  * Provides more relevant and tailored search results
  * Considers user's historical interactions and preferences
* **`false`** - Standard search without personalization (default)
  * Returns results based purely on content relevance
  * No user-specific context applied

<Info>
  **Best Practice**: Enable personalise\_search for applications where user context significantly impacts result relevance, such as personalized dashboards, recommendation systems, or user-specific knowledge bases.
</Info>

## Knowledge Graph Context

Search results are automatically enriched with knowledge graph context, providing entity relationships extracted from your content.

**What's included in responses:**

* **`extra_context.chunk_relations`** — Entities and relationships found within each chunk
* **`extra_graph_context`** — Additional entity relationships extracted from your query

This helps your AI understand not just *what* is mentioned, but *how* things relate—like knowing that "Sarah Chen" leads "Project Phoenix" which depends on the "Authentication Service".

<Card title="Learn More: Knowledge Graphs" img="https://mintcdn.com/cortex-ad5578da/OYp3WOJk3NHZ1Ugg/images/network.png?fit=max&auto=format&n=OYp3WOJk3NHZ1Ugg&q=85&s=fbf8066746d7ff3d6b84b62bdc2262b7" href="/essentials/graph-rag" width="1197" height="697" data-path="images/network.png">
  See how to leverage entity relationships, build context for your LLM, and create intelligent features with graph data.
</Card>

## Search Optimization Tips

### For Better Precision

* Use **lower alpha values** (0.2-0.4) for exact term matching
* Include **specific terminology** in your queries
* Set **higher max\_chunks** to get more comprehensive results

### For Better Recall

* Use **higher alpha values** (0.6-0.8) for broader semantic matching
* Try **synonyms and related terms** in your queries
* Use **conceptual language** rather than specific terms
* Enable **recency bias** for time-sensitive content

### For Complex Queries

* Use **"auto" alpha** to let Cortex optimize automatically
* Combine **specific terms with conceptual language**
* Adjust **recency bias** based on content type
* Experiment with **different alpha values** to find optimal results
* Enable **personalise\_search** for user-specific contexts and preferences

### Alpha Parameter

The `alpha` parameter controls the balance between semantic and keyword search:

* `0.0` = keyword search only
* `1.0` = semantic search only
* `0.8` = default balanced approach
* `"auto"` = Cortex intelligently decides the optimal alpha value based on the query

## Error Responses

All endpoints return consistent error responses following the standard format. For detailed error information, see our [Error Responses](/api-reference/error-responses) documentation.


## OpenAPI

````yaml POST /search/hybrid-search
openapi: 3.1.0
info:
  title: Cortex SDK API
  description: REST APIs for Cortex AI retrieval engine
  version: 0.0.1
servers:
  - url: /
    description: Local
    x-fern-server-name: cortex-backend-local
  - url: https://api.usecortex.ai
    description: Production
    x-fern-server-name: cortex-prod
    x-fern-audiences:
      - public
  - url: https://preprod.usecortex.ai
    description: Staging
    x-fern-server-name: cortex-staging
security: []
paths:
  /search/hybrid-search:
    post:
      tags:
        - Search
      summary: Hybrid search
      description: >-
        Search for relevant content within your indexed sources or user
        memories.
            
            Results are ranked by relevance and can be customized with parameters like 
            result limits, alpha weighting, and recency preferences.
            
            Use `search_mode` to specify what to search:
            - "sources" (default): Search over indexed documents
            - "memories": Search over user memories (uses inferred content)
            
            Use `mode` to control retrieval quality:
            - "fast" (default): Single query, faster response
            - "accurate": Multi-query generation with reranking, higher quality
      operationId: hybrid_search_search_hybrid_search_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/HybridSearchRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RetrievalResult'
        '400':
          description: Bad Request - Invalid input parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '401':
          description: Unauthorized - Authentication required
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '403':
          description: Forbidden - Access denied
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '404':
          description: Not Found - Resource does not exist
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '422':
          description: Unprocessable Entity - Validation failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '429':
          description: Too Many Requests - Rate limit exceeded
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
        '503':
          description: Service Unavailable
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ActualErrorResponse'
      security:
        - HTTPBearer: []
components:
  schemas:
    HybridSearchRequest:
      properties:
        tenant_id:
          type: string
          title: Tenant Id
          description: Unique identifier for the tenant/organization
          example: tenant_1234
        sub_tenant_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Sub Tenant Id
          description: >-
            Optional sub-tenant identifier used to organize data within a
            tenant. If omitted, the default sub-tenant created during tenant
            setup will be used.
          example: sub_tenant_4567
        query:
          type: string
          title: Query
          description: Search terms to find relevant content
          example: Which mode does user prefer
        max_chunks:
          anyOf:
            - type: integer
            - type: 'null'
          title: Max Chunks
          description: Maximum number of results to return
        mode:
          $ref: '#/components/schemas/RetrieveMode'
          description: Retrieval mode to use ('fast' or 'accurate')
          default: fast
        alpha:
          anyOf:
            - type: string
            - type: number
          title: Alpha
          description: Search ranking algorithm parameter (0.0-1.0 or 'auto')
          default: 0.8
        recency_bias:
          type: number
          title: Recency Bias
          description: >-
            Preference for newer content (0.0 = no bias, 1.0 =            
            strong recency preference)
          default: 0
          example: 1
        personalise_search:
          type: boolean
          title: Personalise Search
          description: Enable personalized search results based on user preferences
          default: false
          example: true
        graph_context:
          type: boolean
          title: Graph Context
          description: Enable graph context for search results
          default: false
          example: true
        extra_context:
          anyOf:
            - type: string
            - type: 'null'
          title: Extra Context
          description: Additional context provided by the user to guide retrieval
        search_mode:
          $ref: '#/components/schemas/SearchMode'
          description: >-
            What to search: 'sources' for documents or 'memories' for user
            memories
          default: sources
      type: object
      required:
        - tenant_id
        - query
      title: HybridSearchRequest
    RetrievalResult:
      properties:
        chunks:
          items:
            $ref: '#/components/schemas/VectorStoreChunk'
          type: array
          title: Chunks
          example: []
        graph_context:
          $ref: '#/components/schemas/GraphContext'
      type: object
      title: RetrievalResult
      description: Result of a hybrid search retrieval operation.
    ActualErrorResponse:
      properties:
        detail:
          $ref: '#/components/schemas/ErrorResponse'
      type: object
      required:
        - detail
      title: ActualErrorResponse
    RetrieveMode:
      type: string
      enum:
        - fast
        - accurate
      title: RetrieveMode
    SearchMode:
      type: string
      enum:
        - sources
        - memories
      title: SearchMode
      description: Search mode to specify what type of content to search.
    VectorStoreChunk:
      properties:
        chunk_uuid:
          type: string
          title: Chunk Uuid
          description: Unique identifier for this content chunk
          examples:
            - a1b2c3d4-e5f6-7890-1234-567890abcdef
          example: <chunk_uuid>
        source_id:
          type: string
          title: Source Id
          description: Unique identifier for the source document
          examples:
            - doc_12345
          example: CortexDoc1234
        chunk_content:
          type: string
          title: Chunk Content
          description: The actual text content of this chunk
          examples:
            - This is a chunk of text from the source document.
          example: <chunk_content>
        source_type:
          type: string
          title: Source Type
          description: Type of the source document (file, webpage, etc.)
          default: ''
          examples:
            - file
          example: <source_type>
        source_upload_time:
          type: string
          title: Source Upload Time
          description: When the source document was originally uploaded
          default: ''
          examples:
            - '2023-10-27T10:00:00Z'
          example: <source_upload_time>
        source_title:
          type: string
          title: Source Title
          description: Title or name of the source document
          default: ''
          examples:
            - Project Phoenix Overview
          example: <source_title>
        source_last_updated_time:
          type: string
          title: Source Last Updated Time
          description: When the source document was last modified
          default: ''
          examples:
            - '2023-10-27T12:30:00Z'
          example: <source_last_updated_time>
        layout:
          anyOf:
            - type: string
            - type: 'null'
          title: Layout
          description: >-
            Layout of the chunk in original document. You will generally
            receive        a stringified dict with 2 keys, `offsets` and
            `page`(optional). Offsets will have       
            `document_level_start_index` and `page_level_start_index`(optional)
          examples:
            - '{"offsets": {"document_level_start_index": 1024}, "page": 2}'
        relevancy_score:
          anyOf:
            - type: number
            - type: 'null'
          title: Relevancy Score
          description: >-
            Score indicating how relevant this chunk is to your search
            query,         with higher values indicating better matches
        document_metadata:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Document Metadata
          description: Metadata extracted from the source document
          examples:
            - author: John Doe
              category: Internal
        tenant_metadata:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Tenant Metadata
          description: Custom metadata associated with your tenant
          examples:
            - department: R&D
      type: object
      required:
        - chunk_uuid
        - source_id
        - chunk_content
      title: VectorStoreChunk
    GraphContext:
      properties:
        query_paths:
          items:
            $ref: '#/components/schemas/ScoredPathResponse'
          type: array
          title: Query Paths
          example: []
        chunk_relations:
          items:
            $ref: '#/components/schemas/ScoredPathResponse'
          type: array
          title: Chunk Relations
          example: []
        chunk_id_to_group_ids:
          additionalProperties:
            items:
              type: string
            type: array
          type: object
          title: Chunk Id To Group Ids
      type: object
      title: GraphContext
      description: >-
        Graph context containing query-based paths and chunk-based relation
        paths.
    ErrorResponse:
      properties:
        success:
          type: boolean
          title: Success
          default: false
        message:
          type: string
          minLength: 1
          title: Message
          default: Error occurred
        error_code:
          anyOf:
            - type: string
            - type: 'null'
          title: Error Code
      type: object
      title: ErrorResponse
    ScoredPathResponse:
      properties:
        triplets:
          items:
            $ref: '#/components/schemas/PathTriplet'
          type: array
          title: Triplets
          example: []
        relevancy_score:
          type: number
          title: Relevancy Score
          example: 1
        combined_context:
          anyOf:
            - type: string
            - type: 'null'
          title: Combined Context
        group_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Group Id
          description: Path group identifier (e.g., 'p_0') for chunk mapping
      type: object
      required:
        - triplets
        - relevancy_score
      title: ScoredPathResponse
    PathTriplet:
      properties:
        source:
          $ref: '#/components/schemas/Entity'
        relation:
          $ref: '#/components/schemas/RelationEvidence'
        target:
          $ref: '#/components/schemas/Entity'
      type: object
      required:
        - source
        - relation
        - target
      title: PathTriplet
    Entity:
      properties:
        name:
          type: string
          title: Name
          description: Normalized entity name
          example: <name>
        type:
          type: string
          title: Type
          description: PERSON, ORGANIZATION, PROJECT, PRODUCT, ERROR_CODE, etc.
          example: <type>
        namespace:
          type: string
          title: Namespace
          description: Context category like 'employees', 'projects'
          default: default
          example: <namespace>
        entity_id:
          type: string
          title: Entity Id
          description: Internal unique entity ID from graph database
          example: <entity_id>
        identifier:
          anyOf:
            - type: string
            - type: 'null'
          title: Identifier
          description: Unique ID like email, employee_id, URL
      type: object
      required:
        - name
        - type
        - entity_id
      title: Entity
    RelationEvidence:
      properties:
        canonical_predicate:
          type: string
          title: Canonical Predicate
          description: Relationship phrase like 'works for', 'reports to'
          example: <canonical_predicate>
        raw_predicate:
          type: string
          title: Raw Predicate
          description: Original predicate from text
          example: <raw_predicate>
        context:
          type: string
          title: Context
          description: >-
            Rich contextual description of the relationship with surrounding
            information, details about how/why/when, and any relevant
            background. Should be comprehensive enough to understand the
            relationship without referring back to source.
          example: <context>
        confidence:
          type: number
          maximum: 1
          minimum: 0
          title: Confidence
          description: Confidence score
          default: 0.8
          example: 1
        temporal_details:
          anyOf:
            - type: string
            - type: 'null'
          title: Temporal Details
          description: >-
            Temporal timing information extracted from text (e.g., 'last week',
            'in 2023', 'yesterday')
        timestamp:
          type: string
          format: date-time
          title: Timestamp
          description: Timestamp when this relation was introduced
          example: <timestamp>
        relationship_id:
          type: string
          title: Relationship Id
          description: Unique ID for this relationship from graph database
          example: <relationship_id>
        chunk_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Chunk Id
          description: ID of the chunk this relation was extracted from
        source_entity_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Source Entity Id
          description: The entity ID of source node
        target_entity_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Target Entity Id
          description: The entity ID of target node
      type: object
      required:
        - canonical_predicate
        - raw_predicate
        - context
        - relationship_id
      title: RelationEvidence
      description: Single piece of evidence for a relationship between two entities
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````