> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiperai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Search Index for Documents

> Search documents within an index using semantic search.
Returns matching documents with relevance scores.


# Search Index for Documents

Search documents within an index using semantic search.

## Endpoint

```
GET /indexes/{indexName}/search
```

## Description

Search documents within an index using semantic search. Returns matching documents with relevance scores, sorted by relevance.

## Authentication

Required: API Key

```bash theme={null}
Authorization: Bearer sk-your-api-key-here
```

## Path Parameters

| Parameter   | Type   | Required | Description                 |
| ----------- | ------ | -------- | --------------------------- |
| `indexName` | string | Yes      | Name of the index to search |

## Query Parameters

| Parameter   | Type    | Required | Description                                               |
| ----------- | ------- | -------- | --------------------------------------------------------- |
| `query`     | string  | Yes      | Search query text                                         |
| `top_k`     | integer | No       | Maximum number of results to return (1-50, default: 10)   |
| `min_score` | float   | No       | Minimum relevance score threshold (0.0-1.0, default: 0.0) |

## Request Example

```bash theme={null}
curl -X GET "https://{customer.name}.hiperai.ai/api/external/indexes/my-knowledge-base/search?query=What%20is%20machine%20learning?&top_k=10&min_score=0.5" \
  -H "Authorization: Bearer sk-your-api-key-here"
```

### JavaScript/Node.js

```javascript theme={null}
const query = encodeURIComponent('What is machine learning?');
const response = await fetch(`https://{customer.name}.hiperai.ai/api/external/indexes/my-knowledge-base/search?query=${query}&top_k=10&min_score=0.5`, {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer sk-your-api-key-here'
  }
});

const data = await response.json();
console.log('Total matches:', data.results.total);
data.results.matches.forEach(match => {
  console.log(`Rank ${match.rank}: ${match.content.substring(0, 100)}... (score: ${match.score})`);
});
```

### Python

```python theme={null}
import requests

url = "https://{customer.name}.hiperai.ai/api/external/indexes/my-knowledge-base/search"
headers = {
    "Authorization": "Bearer sk-your-api-key-here"
}
params = {
    "query": "What is machine learning?",
    "top_k": 10,
    "min_score": 0.5
}

response = requests.get(url, headers=headers, params=params)
result = response.json()
print('Total matches:', result['results']['total'])
for match in result['results']['matches']:
    print(f"Rank {match['rank']}: {match['content'][:100]}... (score: {match['score']})")
```

## Response

### Success Response (200)

```json theme={null}
{
  "success": true,
  "request_id": "550e8400-e29b-41d4-a716-446655440000",
  "query": "What is machine learning?",
  "results": {
    "matches": [
      {
        "rank": 1,
        "score": 0.85,
        "source": "training",
        "content": "Machine learning is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed...",
        "metadata": {
          "page": 1,
          "chunkIndex": 0,
          "title": "Introduction to ML",
          "documentId": "60a7c8f5e8b4f5001f7a8c26"
        }
      },
      {
        "rank": 2,
        "score": 0.78,
        "source": "training",
        "content": "Machine learning algorithms build mathematical models based on training data to make predictions or decisions...",
        "metadata": {
          "page": 2,
          "chunkIndex": 1,
          "title": "Introduction to ML",
          "documentId": "60a7c8f5e8b4f5001f7a8c26"
        }
      }
    ],
    "total": 5,
    "top_k": 10
  },
  "index": {
    "name": "my-knowledge-base",
    "namespace": "user-60a7c8f5e8b4f5001f7a8c24-index-my-knowledge-base"
  }
}
```

### Response Fields

| Field        | Type    | Description                         |
| ------------ | ------- | ----------------------------------- |
| `success`    | boolean | Always true for successful requests |
| `request_id` | string  | Request ID for tracking             |
| `query`      | string  | The search query that was used      |
| `results`    | object  | Search results                      |
| `index`      | object  | Index information                   |

### Results Object

| Field     | Type    | Description                                      |
| --------- | ------- | ------------------------------------------------ |
| `matches` | array   | Array of matching documents, sorted by relevance |
| `total`   | integer | Total number of matches found                    |
| `top_k`   | integer | Requested top\_k value                           |

### Match Object

| Field      | Type    | Description                                        |
| ---------- | ------- | -------------------------------------------------- |
| `rank`     | integer | Result rank (1-based)                              |
| `score`    | float   | Relevance score (0.0-1.0, higher is more relevant) |
| `source`   | string  | Document source identifier                         |
| `content`  | string  | Content preview (truncated to 500 characters)      |
| `metadata` | object  | Additional metadata                                |

### Metadata Object

| Field        | Type          | Description                 |
| ------------ | ------------- | --------------------------- |
| `page`       | integer\|null | Page number (if from PDF)   |
| `chunkIndex` | integer\|null | Chunk index within document |
| `title`      | string\|null  | Document title              |
| `documentId` | string\|null  | Document ID                 |

## Error Responses

### 400 Bad Request

```json theme={null}
{
  "success": false,
  "error": "Invalid request",
  "message": "Missing or invalid query parameter"
}
```

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "error": "Invalid API key",
  "message": "The provided API key is invalid or has been revoked"
}
```

### 403 Forbidden

```json theme={null}
{
  "success": false,
  "error": "Access denied",
  "message": "User doesn't have access to this index"
}
```

### 404 Not Found

```json theme={null}
{
  "success": false,
  "error": "Index not found",
  "message": "The specified index does not exist"
}
```

### 500 Internal Server Error

```json theme={null}
{
  "success": false,
  "error": "Search failed",
  "message": "An error occurred during search"
}
```

## Notes

* Semantic search uses vector similarity to find relevant documents
* Results are sorted by relevance score (highest first)
* Use `min_score` to filter out low-relevance results
* Content previews are truncated to 500 characters
* The `top_k` parameter limits the number of results returned
* Metadata includes information about the document source and location


## OpenAPI

````yaml GET /indexes/{indexName}/search
openapi: 3.0.3
info:
  title: SecureAI External API
  description: >
    SecureAI External API provides AI chat completion and image generation
    capabilities with knowledge base retrieval, 

    security policies, and comprehensive usage tracking. This API is designed
    for external developers 

    and integrations using API key authentication.


    ## Key Features

    - **RAG (Retrieval-Augmented Generation)**: Automatically search knowledge
    bases for relevant context

    - **Multi-Model Support**: OpenAI, Anthropic, Google, Meta, and other AI
    models

    - **Model Redundancy & Failover**: Caller-defined failover chains (primary +
    fallbacks) with per-attempt timeouts

    - **OpenAI-Compatible Endpoint**: Point any OpenAI SDK at `/api/external/v1`
    — no code changes

    - **Image Generation**: Generate and edit images using Google Gemini 2.5
    Flash Image

    - **Speech-to-Speech (S2S)**: Real-time voice conversations using OpenAI
    Realtime API with WebRTC

    - **Security Policies**: SMLTP policy enforcement, per-call Prompt Shield,
    and signed compliance receipts

    - **Usage Tracking**: Comprehensive usage monitoring, self-service quota,
    and rate limiting

    - **Knowledge Base Integration**: Access to personal and shared knowledge
    bases

    - **User Management**: Complete user, group, and role management
    capabilities

    - **Audit Logging**: Comprehensive activity and security audit logs


    ## Authentication

    All endpoints (except health check) require API key authentication using
    Bearer token:

    ```

    Authorization: Bearer sk-your-api-key-here

    ```


    ## Billing and Usage

    By default, API requests are billed to the user account that owns the API
    key. You can specify 

    a different user to bill by including the `user_id` parameter in your
    request. This allows for:

    - Multi-tenant applications with per-user billing

    - Flexible completion limit management

    - Per-user "Usage by Model" settings


    ## Rate Limits

    - Default: 60 requests per minute, 1000 requests per hour

    - Daily limits: 100 requests (configurable)

    - Monthly limits: 10,000 requests (configurable)


    ## Base URL

    ```

    https://secureai.hiperai.ai/api/external

    ```
  version: 1.1.0
  contact:
    name: SecureAI Support
    email: support@secureai.hiperai.ai
  license:
    name: Proprietary
    url: https://secureai.hiperai.ai/terms
servers:
  - url: https://secureai.hiperai.ai/api/external
    description: Production server
  - url: http://localhost:3010/api/external
    description: Development server
security:
  - ApiKeyAuth: []
tags:
  - name: System
    description: System health and status endpoints
  - name: Discovery
    description: Endpoints to discover available models, indexes, and policies
  - name: Chat
    description: AI chat completion endpoints
  - name: User Management
    description: Endpoints for managing user accounts and roles
  - name: Index Management
    description: Endpoints for managing knowledge base indexes
  - name: Group Management
    description: Endpoints for managing user groups
  - name: SMLTP Security
    description: Endpoints for managing SMLTP security policies and audit logs
  - name: Role Management
    description: Endpoints for managing user roles
  - name: Activity Logs
    description: Endpoints for retrieving activity logs
externalDocs:
  description: SecureAI Documentation
  url: https://secureai.hiperai.ai/docs
paths:
  /indexes/{indexName}/search:
    get:
      tags:
        - Index Management
      summary: Search Index for Documents
      description: |
        Search documents within an index using semantic search.
        Returns matching documents with relevance scores.
      parameters:
        - name: indexName
          in: path
          required: true
          description: Name of the index to search
          schema:
            type: string
            example: my-knowledge-base
        - name: query
          in: query
          required: true
          description: Search query text
          schema:
            type: string
            example: What is machine learning?
        - name: top_k
          in: query
          required: false
          description: 'Maximum number of results to return (1-50, default: 10)'
          schema:
            type: integer
            minimum: 1
            maximum: 50
            default: 10
            example: 10
        - name: min_score
          in: query
          required: false
          description: 'Minimum relevance score threshold (0.0-1.0, default: 0.0)'
          schema:
            type: number
            format: float
            minimum: 0
            maximum: 1
            default: 0
            example: 0.5
      responses:
        '200':
          description: Search completed successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  request_id:
                    type: string
                    format: uuid
                    example: 550e8400-e29b-41d4-a716-446655440000
                  query:
                    type: string
                    example: What is machine learning?
                  results:
                    type: object
                    properties:
                      matches:
                        type: array
                        items:
                          type: object
                          properties:
                            rank:
                              type: integer
                              description: Result rank (1-based)
                              example: 1
                            score:
                              type: number
                              format: float
                              description: Relevance score (0.0-1.0)
                              example: 0.85
                            source:
                              type: string
                              description: Document source identifier
                              example: training
                            content:
                              type: string
                              description: Content preview (truncated to 500 chars)
                              example: >-
                                Machine learning is a subset of artificial
                                intelligence...
                            metadata:
                              type: object
                              properties:
                                page:
                                  type: integer
                                  nullable: true
                                  description: Page number (if from PDF)
                                  example: 1
                                chunkIndex:
                                  type: integer
                                  nullable: true
                                  description: Chunk index within document
                                  example: 0
                                title:
                                  type: string
                                  nullable: true
                                  description: Document title
                                  example: Introduction to ML
                                documentId:
                                  type: string
                                  nullable: true
                                  description: Document ID
                                  example: 60a7c8f5e8b4f5001f7a8c26
                      total:
                        type: integer
                        description: Total number of matches found
                        example: 5
                      top_k:
                        type: integer
                        description: Requested top_k value
                        example: 10
                  index:
                    type: object
                    properties:
                      name:
                        type: string
                        example: my-knowledge-base
                      namespace:
                        type: string
                        example: user-60a7c8f5e8b4f5001f7a8c24-index-my-knowledge-base
        '400':
          description: Invalid request (missing or invalid query parameter)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Access denied - user doesn't have access to this index
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '404':
          description: Index not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '500':
          description: Search failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Invalid API key
        message:
          type: string
          example: The provided API key is invalid or has been revoked
        request_id:
          type: string
          example: req-abc123
          description: Request ID for tracking (if available)
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````