# opensearch-script

Part of **OPENSEARCH**

# OpenSearch Script Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| Manage Sort Scripts | Synchronous | Create, delete, list, and retrieve details of custom sort scripts. |
| Manage Script Files | Synchronous | Upload, retrieve, and list script files used in search operations. |
| Release Sort Script | Synchronous | Deploy or activate a sort script for use in search operations. |

## API Calling Patterns

### Authentication
Use **Bearer Token** authentication as the primary method:
- Include the header: `Authorization: Bearer <your_api_key>`
- Store your API key in the environment variable: `DASHSCOPE_API_KEY`
- Example: `export DASHSCOPE_API_KEY=sk-xxxxxx`

While other auth methods may exist in broader Alibaba Cloud contexts, all OpenSearch Script Management APIs documented here require this Bearer token format.

### Service Endpoint
The base URL pattern is:
```text
https://api.aliyun.com/v4/openapi
```
All endpoints are global (not region-specific), so no regional variation is needed. Common regions like `cn-hangzhou`, `cn-shanghai`, and `cn-beijing` are supported through this single endpoint.

### Synchronous API Pattern
All script management operations follow a **synchronous** pattern:
1. Send an HTTP request (GET, POST, PUT, or DELETE) to the appropriate endpoint with required path/query/body parameters
2. Include the `Authorization: Bearer $DASHSCOPE_API_KEY` header
3. Receive an immediate JSON response containing a `requestId` and, where applicable, result data
4. Handle success or error based on HTTP status code and response body

No polling or async task handling is required—each call completes within the same request-response cycle.

## Parameter Reference

### Manage Sort Scripts

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| appGroupIdentity | String | Yes | — | — | The name or ID of the OpenSearch application |
| appVersionId | String | Yes | — | — | The version number of the application |
| scriptName | String | Yes | — | — | The name of the sort script |
| type | String | Yes | — | must be 'cava_script' | The type of the script |
| scope | String | Yes | — | must be 'second_rank' | The sort phase to which the script applies |

### Manage Script Files

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| appGroupIdentity | String | Yes | — | — | The name or ID of the OpenSearch application |
| appVersionId | String | Yes | — | — | The version number of the application |
| scriptName | String | Yes | — | — | The name of the script |
| fileName | String | Yes | — | — | The name of the script file (e.g., `UserScorer.cava`) |
| content | String | Yes | — | — | The Base64-encoded script content |
| version | Integer | No | current time | — | Version number for concurrent update control |

### Release Sort Script

| Parameter | Type | Required | Default | Constraints | Description |
|-----------|------|----------|---------|-------------|-------------|
| appGroupIdentity | String | Yes | — | — | The name or ID of the OpenSearch application |
| appVersionId | String | Yes | — | — | The version number of the application |
| scriptName | String | Yes | — | — | The name of the script to release |

## Code Examples

### Create Sort Script - curl - all

```bash
curl -X POST https://api.aliyun.com/v4/openapi/app-groups/my_app/apps/123456/sort-scripts \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
    "scriptName": "script1",
    "type": "cava_script",
    "scope": "second_rank"
}'
```

### Upload Script File - curl - all

```bash
curl -X PUT https://api.aliyun.com/v4/openapi/app-groups/my_app/apps/123456/sort-scripts/script1/files/src/UserScorer.cava \
-H "Authorization: Bearer YOUR_API_KEY" \
-d '{
    "content": "YWJjZGVmZw==",
    "version": 123456
}'
```

### Get Script Content - Python - all

```python
import requests
import base64
import os

url = 'https://api.aliyun.com/v4/openapi/app-groups/my_app/apps/123456/sort-scripts/script1/files/src/UserScorer.cava'
headers = {
    'Authorization': f'Bearer {os.environ["DASHSCOPE_API_KEY"]}'
}

response = requests.get(url, headers=headers)
data = response.json()
if 'result' in data and 'content' in data['result']:
    decoded_content = base64.b64decode(data['result']['content']).decode('utf-8')
    print(decoded_content)
else:
    print("Failed to retrieve script content")
```

### List All Sort Scripts - curl - all

```bash
curl -X GET "https://api.aliyun.com/v4/openapi/app-groups/my_app/apps/123456/sort-scripts" \
-H "Authorization: Bearer YOUR_API_KEY"
```

### Release Sort Script - curl - all

```bash
curl -X POST https://api.aliyun.com/v4/openapi/app-groups/my_app/apps/123456/sort-scripts/script1/actions/release \
-H "Authorization: Bearer YOUR_API_KEY"
```

### Delete Sort Script - curl - all

```bash
curl -X DELETE https://api.aliyun.com/v4/openapi/app-groups/my_app/apps/123456/sort-scripts/script1 \
-H "Authorization: Bearer YOUR_API_KEY"
```

## Response Format

```json
{
    "requestId": "ABCDEFGH",
    "result": {
        "type": "cava_script",
        "scope": "second_rank",
        "status": "released",
        "createTime": "2020-04-02 20:21:14",
        "modifyTime": "2020-04-02 21:21:14"
    }
}
```

**Key Fields**:
- `requestId` — Unique identifier for the API request; useful for debugging and support
- `result.type` — Always `cava_script` for sort scripts
- `result.scope` — Always `second_rank`, indicating the script runs during second-stage ranking
- `result.status` — Current deployment status (`released`, `draft`, etc.)
- `result.createTime` — Timestamp when the script was first created
- `result.modifyTime` — Timestamp of the last modification

For file content responses, `result.content` contains Base64-encoded script source code.

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|-------------------|----------------------------|----------------------------------------|
| 400 | Bad Request: The request is malformed or contains invalid parameters. | Validate all required parameters and ensure `type=cava_script` and `scope=second_rank`. |
| 401 | Unauthorized: Authentication failed or missing credentials. | Verify that `DASHSCOPE_API_KEY` is set and valid; check the Authorization header format. |
| 403 | Forbidden: The user does not have permission to perform this operation. | Ensure your account has OpenSearch write permissions for the specified app group. |
| 404 | Not Found: The specified appGroupIdentity, appVersionId, script, or file does not exist. | Double-check application name, version ID, script name, and file path. |
| 500 | Internal Server Error: An unexpected error occurred on the server side. | Retry the request; if persistent, contact Alibaba Cloud support with the `requestId`. |
| InvalidAppStatus | The application is in an invalid status. | Ensure the OpenSearch application is active and deployed before managing scripts. |
| ResourceNotFound | The specified script or file was not found. | Confirm the script exists via `ListSortScripts` before attempting file operations. |
| InvalidAppSpec | Cava scripts only support private spec apps. | Use a private specification OpenSearch application, not public/shared instances. |

## Environment Requirements

- Set your API key: `export DASHSCOPE_API_KEY=your_api_key_here`
- For Python usage, install requests: `pip install requests`
- No specific runtime version requirements beyond standard HTTP client capabilities

## FAQ

Q: What is a "sort script" in OpenSearch?
A: A sort script is a custom Cava-based program that modifies document ranking during the second stage of search results processing. It allows fine-grained control over relevance scoring beyond standard ranking algorithms.

Q: Do I need to Base64-encode my script content?
A: Yes. When uploading script files via `SaveSortScriptFile`, the `content` parameter must be a Base64-encoded string of your `.cava` source file.

Q: Can I use these APIs with public OpenSearch instances?
A: No. Cava sort scripts are only supported on private specification OpenSearch applications. Attempting to use them on public instances will return an `InvalidAppSpec` error.

Q: How do I debug a failed script upload?
A: Check the `requestId` in the error response and verify: (1) your app is active, (2) the script name doesn’t already exist (for creation), (3) you’re using the correct app group and version IDs, and (4) your API key has proper permissions.

Q: Is there a size limit for script files?
A: While not explicitly stated in the documentation, practical limits apply due to HTTP payload constraints. Keep scripts concise and modular; large files may cause timeouts or rejection.

## Pricing & Billing

### Billing Model
All script management operations are billed **per request**, regardless of success or failure. Each API call (create, delete, list, get, upload, release) counts as one billable request.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| standard | 0.0001 / | 0.0001 / |
| default | 0.001 / | 0.001 / |

*Note: Pricing varies slightly by operation type as shown in source documentation.*

### Free Tier
Most operations include **1000 free requests per month**. Exceptions (like `DeleteSortScriptFile`) may have no free tier—check individual operation pricing.

### Usage Limits
- **100 QPS** per app group or account (varies by operation)
- Some delete operations limited to **10 QPS**

### Billing Notes
- Billing occurs at month-end based on total usage
- Free tier resets monthly
- Failed requests still count toward billing and quotas