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

### 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 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`       | 整数\|null  | ページ番号 (PDF からの場合)   |
| `chunkIndex` | 整数\|null  | ドキュメント内のチャンク インデックス |
| `title`      | 文字列\|null | 文書のタイトル             |
| `documentId` | 文字列\|null | ドキュメント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`

````