> ## 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 documents within an index using semantic search.
Returns matching documents with relevance scores.


# 문서 검색 색인

의미 검색을 사용하여 인덱스 내의 문서를 검색합니다.

## 엔드포인트

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

## 설명

의미 검색을 사용하여 인덱스 내의 문서를 검색합니다. 관련성 점수가 있는 일치하는 문서를 관련성 기준으로 정렬하여 반환합니다.

## 인증

필수: API 키

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

## 경로 매개변수

| 매개변수        | 유형  | 필수 | 설명         |
| ----------- | --- | -- | ---------- |
| `indexName` | 문자열 | 예  | 검색할 인덱스 이름 |

## 쿼리 매개변수

| 매개변수        | 유형  | 필수  | 설명                               |
| ----------- | --- | --- | -------------------------------- |
| `query`     | 문자열 | 예   | 검색어 텍스트                          |
| `top_k`     | 정수  | 아니요 | 반환할 최대 결과 수(1-50, 기본값: 10)       |
| `min_score` | 플로트 | 아니요 | 최소 관련성 점수 임계값(0.0-1.0, 기본값: 0.0) |

## 요청 예시

```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"
```

### 자바스크립트/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 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']})")
```

## 응답

### 성공 응답 (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"
  }
}
```

### 응답 필드

| 필드           | 유형  | 설명                  |
| ------------ | --- | ------------------- |
| `success`    | 부울  | 성공적인 요청의 경우 항상 true |
| `request_id` | 문자열 | 추적을 위한 요청 ID        |
| `query`      | 문자열 | 사용된 검색어             |
| `results`    | 개체  | 검색결과                |
| `index`      | 개체  | 지수정보                |

### 결과 개체

| 필드        | 유형 | 설명                     |
| --------- | -- | ---------------------- |
| `matches` | 배열 | 관련성에 따라 정렬된 일치하는 문서 배열 |
| `total`   | 정수 | 발견된 총 일치 수             |
| `top_k`   | 정수 | 요청된 top\_k 값           |

### 일치 개체

| 필드         | 유형  | 설명                            |
| ---------- | --- | ----------------------------- |
| `rank`     | 정수  | 결과순위(1기준)                     |
| `score`    | 플로트 | 관련성 점수(0.0-1.0, 높을수록 관련성이 높음) |
| `source`   | 문자열 | 문서 소스 식별자                     |
| `content`  | 문자열 | 콘텐츠 미리보기(500자로 잘림)            |
| `metadata` | 개체  | 추가 메타데이터                      |

### 메타데이터 개체

| 필드           | 유형     | 설명              |
| ------------ | ------ | --------------- |
| `page`       | 정수\|널  | 페이지 번호(PDF의 경우) |
| `chunkIndex` | 정수\|널  | 문서 내 청크 인덱스     |
| `title`      | 문자열\|널 | 문서 제목           |
| `documentId` | 문자열\|널 | 문서 ID           |

## 오류 응답

### 400 잘못된 요청

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

### 401 승인되지 않음

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

### 403 금지됨

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

### 404 찾을 수 없음

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

### 500 내부 서버 오류

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

## 메모

* 의미 검색은 벡터 유사성을 사용하여 관련 문서를 찾습니다.
* 결과는 관련성 점수에 따라 정렬됩니다(가장 높은 것부터)
* 관련성이 낮은 결과를 필터링하려면 `min_score`을 사용하세요.
* 콘텐츠 미리보기가 500자로 잘립니다.
* `top_k` 매개변수는 반환되는 결과 수를 제한합니다.
* 메타데이터에는 문서 소스 및 위치에 대한 정보가 포함됩니다.


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

````