OpenSearch 9200 常用 REST API
OpenSearch(與 Elasticsearch 相容)預設透過 HTTP :9200 提供 REST API。以下以本機 http://localhost:9200 為例,整理日常開發最常用的端點。
若叢集啟用安全外掛,請在 curl 加上
-u admin:password或對應的 Bearer token。
快速對照
| 分類 | Method | Path | 用途 |
|---|---|---|---|
| 連線檢查 | GET | / | 確認服務與版本 |
| 叢集健康 | GET | /_cluster/health | green / yellow / red |
| 節點列表 | GET | /_cat/nodes | 看有哪些 node |
| Index 列表 | GET | /_cat/indices | 列出 index 與 health |
| 建立 Index | PUT | /{index} | 建 index + mapping |
| 查 Mapping | GET | /{index}/_mapping | 看欄位型別 |
| 寫入文件 | PUT/POST | /{index}/_doc/{id} | 單筆 index |
| 讀取文件 | GET | /{index}/_doc/{id} | 依 _id 取文件 |
| 刪除文件 | DELETE | /{index}/_doc/{id} | 刪單筆 |
| 搜尋 | GET/POST | /{index}/_search | 查詢 |
| 批次 | POST | /_bulk | 大量寫入/刪除 |
| 依條件刪 | POST | /{index}/_delete_by_query | 條件刪除 |
1. 連線與叢集資訊
根路徑(版本、叢集名)
curl "http://localhost:9200/?pretty"
回傳大致包含 cluster_name、version.number、tagline。
叢集健康
curl "http://localhost:9200/_cluster/health?pretty"
常用 query:
| 參數 | 說明 |
|---|---|
pretty | 美化 JSON |
level=indices | 細到每個 index |
wait_for_status=green | 等到指定狀態再回傳 |
單節點常見 yellow 的原因與處理,見 OpenSearch 單節點、Replica 與 Cluster Health。
叢集設定
# 讀取
curl "http://localhost:9200/_cluster/settings?pretty"
# 暫態調整(重啟後消失)
curl -X PUT "http://localhost:9200/_cluster/settings" \
-H 'Content-Type: application/json' \
-d '{
"transient": {
"cluster.routing.allocation.enable": "all"
}
}'
2. Cat API(人讀友善表格)
_cat/* 回傳文字表格,適合在終端機快速查看。建議加 ?v(顯示欄位標題)。
# 所有 index
curl "http://localhost:9200/_cat/indices?v"
# 節點
curl "http://localhost:9200/_cat/nodes?v"
# 分片配置
curl "http://localhost:9200/_cat/shards?v"
# 別名
curl "http://localhost:9200/_cat/aliases?v"
# 健康摘要
curl "http://localhost:9200/_cat/health?v"
常用額外參數:?v&s=index:asc(排序)、?h=index,health,docs.count(只顯示指定欄位)。
3. Index 管理
建立 Index(含 mapping / settings)
curl -X PUT "http://localhost:9200/documents" \
-H 'Content-Type: application/json' \
-d '{
"settings": {
"number_of_shards": 1,
"number_of_replicas": 0
},
"mappings": {
"properties": {
"filename": { "type": "text" },
"content": { "type": "text" },
"source": { "type": "keyword" },
"indexed_at": { "type": "date" }
}
}
}'
text / keyword 差異見 Mapping:text 與 keyword。