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

# Search Embeddings

> Find similar chunks using an embedding vector.

Use this to retrieve the most similar chunk IDs to a single query embedding.

Expected outcome:
- You receive the closest chunk IDs with optional similarity scores.

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 expandable theme={null}
    curl -X 'POST' \
    'https://api.usecortex.ai/embeddings/search-raw-embeddings' \
    -H 'accept: application/json' \
    -H 'Content-Type: application/json' \
    -d '{
    "tenant_id": "string",
    "sub_tenant_id": "string",
    "query_embedding": [
    0
    ],
    "limit": 10,
    "filter_expr": "string",
    "output_fields": [
    "string"
    ]
    }'
    ```
  </Tab>

  <Tab title="TypeScript">
    ```ts theme={null}
    const results = await client.embeddings.search({
      tenant_id: "tenant_1234",
      sub_tenant_id: "sub_tenant_4567",
      embeddings: [
        0.123413, 0.655367, 0.987654, 0.123456, 0.789012
      ],
      max_chunks: 10
    });
    ```
  </Tab>

  <Tab title="Python (Sync)">
    ```python theme={null}
    # Async usage is similar, just use async_client and await
    results = client.embeddings.search(
        tenant_id="tenant_1234",
        sub_tenant_id="sub_tenant_4567",
        embeddings=[
            0.123413, 0.655367, 0.987654, 0.123456, 0.789012
        ],
        max_chunks=10
    )
    ```
  </Tab>
</Tabs>

Search for similar content using vector embeddings by comparing your input embedding against the vector database to find the most similar content chunks.

## Vector Search Concepts

### What are Embeddings?

Embeddings are high-dimensional vector representations of text that capture semantic meaning:

* **Semantic Understanding**: Similar concepts have similar vector representations
* **Mathematical Distance**: Content similarity is measured by vector distance
* **Language Agnostic**: Works across different languages and formats
* **Context Preservation**: Maintains meaning and relationships between concepts

### How Vector Search Works

1. **Input Processing**: Your embedding vector is compared against all stored embeddings
2. **Similarity Calculation**: Cosine similarity or other distance metrics are computed
3. **Ranking**: Results are ranked by similarity score (higher = more similar)
4. **Retrieval**: Most similar chunks are returned with their similarity scores

### Embedding Dimensions

* **Standard Dimensions**: Most embeddings use 384, 512, 768, or 1536 dimensions
* **Quality vs Speed**: Higher dimensions = better quality, slower search
* **Compatibility**: Ensure your embedding model matches Cortex's expected format

## Search Parameters

### Max Chunks

Controls the number of results returned:

* **Range**: 1-200 chunks
* **Default**: 10 chunks
* **Recommendation**:
  * Start with 10-20 for most use cases
  * Use 50-100 for comprehensive searches
  * Use 1-5 for precise, top results only

### Embedding Format

* **Type**: Single embedding vector (1D array of numeric values)
* **Values**: Floating-point numbers (typically between -1 and 1)
* **Length**: Must match the embedding model's dimension size
* **Example**: `[0.1, -0.2, 0.3, 0.4, -0.5, ...]`

## Use Cases

### Semantic Similarity Search

* **Content Discovery**: Find documents similar to a reference document
* **Recommendation Systems**: Suggest related content based on user interests
* **Duplicate Detection**: Identify similar or duplicate content
* **Content Clustering**: Group related documents together

### Cross-Language Search

* **Multilingual Content**: Find similar content across different languages
* **Translation Support**: Search for content in one language using another
* **Global Knowledge**: Access information regardless of original language

### Advanced Retrieval

* **Conceptual Search**: Find content based on meaning, not exact keywords
* **Context-Aware Search**: Retrieve content that matches conceptual context
* **Fuzzy Matching**: Find content even with different wording or phrasing

## Best Practices

### Embedding Quality

* **Use High-Quality Models**: Choose well-trained embedding models (OpenAI, Cohere, etc.)
* **Consistent Models**: Use the same embedding model for both indexing and searching
* **Preprocessing**: Clean and normalize text before generating embeddings
* **Batch Processing**: Generate embeddings in batches for better performance

### Search Optimization

* **Appropriate Max Chunks**: Start with 10-20, adjust based on your needs
* **Similarity Thresholds**: Set minimum similarity scores to filter low-quality matches
* **Multiple Queries**: Try different embedding representations of the same concept
* **Hybrid Approaches**: Combine vector search with keyword search for better results

### Performance Considerations

* **Vector Size**: Larger vectors provide better quality but slower search
* **Index Size**: More indexed content = longer search times
* **Batch Requests**: Process multiple embeddings simultaneously when possible
* **Caching**: Cache frequently used embeddings to improve response times

## Common Patterns

### Document Similarity

```json theme={null}
{
  "embeddings": [0.1, 0.2, 0.3, ...],
  "max_chunks": 20
}
```

Use when you want to find documents similar to a reference document.

### Concept Search

```json theme={null}
{
  "embeddings": [0.4, -0.1, 0.8, ...],
  "max_chunks": 10
}
```

Use when searching for content related to a specific concept or topic.

### Recommendation Engine

```json theme={null}
{
  "embeddings": [0.2, 0.5, -0.3, ...],
  "max_chunks": 50
}
```

Use when building recommendation systems that need many similar items.

## Sample Response

```json theme={null}
{
  "chunk_ids": [
    "CortexEmbeddings123_0",    
    "CortexEmbeddings456_0",
    "CortexEmbeddings456_1",
    "CortexEmbeddings123_2",   
    "CortexEmbeddings123_8"
  ],
  "scores": [
    0.95,
    0.89,
    0.87,
    0.82,
    0.78
  ]
}
```

## 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 /embeddings/search-raw-embeddings
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:
  /embeddings/search-raw-embeddings:
    post:
      tags:
        - embeddings
      summary: Search Raw Embeddings Endpoint
      description: >-
        Find similar chunks using an embedding vector.


        Use this to retrieve the most similar chunk IDs to a single query
        embedding.


        Expected outcome:

        - You receive the closest chunk IDs with optional similarity scores.
      operationId: search_raw_embeddings_endpoint_embeddings_search_raw_embeddings_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: >-
                #/components/schemas/Body_search_raw_embeddings_endpoint_embeddings_search_raw_embeddings_post
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                items:
                  $ref: '#/components/schemas/RawEmbeddingSearchResult'
                type: array
                title: >-
                  Response Search Raw Embeddings Endpoint Embeddings Search Raw
                  Embeddings Post
        '400':
          description: Bad Request - Invalid input parameters
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
        '401':
          description: Unauthorized - Authentication required
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
        '403':
          description: Forbidden - Access denied
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
        '404':
          description: Not Found - Resource does not exist
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
        '422':
          description: Unprocessable Entity - Validation failed
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
        '500':
          description: Internal Server Error
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
        '503':
          description: Service Unavailable
          content:
            application/json:
              schema:
                $ref: >-
                  #/components/schemas/cortex__models__response__commons__ActualErrorResponse
      security:
        - HTTPBearer: []
components:
  schemas:
    Body_search_raw_embeddings_endpoint_embeddings_search_raw_embeddings_post:
      properties:
        tenant_id:
          type: string
          title: Tenant Id
          description: Unique identifier for the tenant/organization
          example: tenant_1234
        sub_tenant_id:
          type: string
          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_embedding:
          items:
            type: number
          type: array
          title: Query Embedding
          description: Query embedding vector to search for
          example: []
        limit:
          type: integer
          maximum: 1000
          minimum: 1
          title: Limit
          description: Maximum number of results to return
          default: 10
          example: 1
        filter_expr:
          anyOf:
            - type: string
            - type: 'null'
          title: Filter Expr
          description: Optional Milvus filter expression for additional filtering
        output_fields:
          anyOf:
            - items:
                type: string
              type: array
            - type: 'null'
          title: Output Fields
          description: >-
            Optional list of fields to return in results (default: chunk_id,
            source_id, metadata)
      type: object
      required:
        - tenant_id
        - sub_tenant_id
        - query_embedding
      title: >-
        Body_search_raw_embeddings_endpoint_embeddings_search_raw_embeddings_post
    RawEmbeddingSearchResult:
      properties:
        source_id:
          type: string
          title: Source Id
          description: Source identifier
          example: CortexDoc1234
        embedding:
          anyOf:
            - $ref: '#/components/schemas/RawEmbeddingVector'
            - type: 'null'
          description: Embedding payload with chunk id and vector (if set)
        score:
          type: number
          title: Score
          description: Similarity score
          default: 0
          example: 1
        distance:
          type: number
          title: Distance
          description: Vector distance
          default: 0
          example: 1
        metadata:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Metadata
          description: Metadata associated with the embedding
      type: object
      required:
        - source_id
      title: RawEmbeddingSearchResult
      description: Search result for raw embedding collections.
    cortex__models__response__commons__ActualErrorResponse:
      properties:
        detail:
          $ref: >-
            #/components/schemas/cortex__models__response__commons__ErrorResponse
      type: object
      required:
        - detail
      title: ActualErrorResponse
    RawEmbeddingVector:
      properties:
        chunk_id:
          type: string
          title: Chunk Id
          description: Primary key / chunk identifier
          example: <chunk_id>
        embedding:
          items:
            type: number
          type: array
          title: Embedding
          description: Embedding vector
          example: []
      type: object
      required:
        - chunk_id
        - embedding
      title: RawEmbeddingVector
      description: Embedding payload containing the chunk identifier and vector.
    cortex__models__response__commons__ErrorResponse:
      properties:
        success:
          type: boolean
          title: Success
          default: false
          example: true
        message:
          type: string
          title: Message
          default: Error occurred
        error_code:
          anyOf:
            - type: string
            - type: 'null'
          title: Error Code
      type: object
      title: ErrorResponse
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````