教學
Kibana Dev Tools:Elasticsearch 與 OpenSearch query 範例
在 Kibana Dev Tools 中,每個請求都是一個 HTTP 方法加上路徑,後面接 JSON 主體,例如 GET /order_lines/_search 搭配 {"query": {"match": {"product": "tent"}}}。全文搜尋用 match,比對 keyword 的精確值用 term,組合條件用 bool,彙總統計用 aggs。同樣的語法也適用於 OpenSearch Dashboards。以下是以一家商店的訂單為例、可直接複製的範例。
Kibana Dev Tools console 語法
開啟 Kibana,在選單(或全域搜尋)中找到 Dev Tools,就會看到 Console。OpenSearch Dashboards 也有相同的 Dev Tools console。每個請求都是一個 HTTP 方法和一個路徑,後面可以接 JSON 主體:
# Comments start with # or //
GET /orders/_search
{
"query": { "match_all": {} }
}按 Ctrl+Enter(Mac 上為 Cmd+Enter)會執行游標所在的請求;選取多個請求則會依序執行。Console 會把請求送到 Kibana 所連線的叢集,而它的 Copy as 選單可以把請求轉成 curl。在終端機中執行同一個請求:
curl --cacert http_ca.crt -u elastic -H 'Content-Type: application/json' \
'https://localhost:9200/orders/_search' -d '{"query": {"match_all": {}}}'除非該節另有說明,以下範例適用於 Elasticsearch 8 和 9,以及 OpenSearch 2 和 3。
範例資料
所有範例都使用同一家商店的資料,分成兩個 index:orders 和 order_lines。mapping 很重要,因為 text 和 keyword 欄位的行為不同:
PUT /order_lines
{
"mappings": {
"properties": {
"order_id": { "type": "integer" },
"product": { "type": "text", "fields": { "keyword": { "type": "keyword" } } },
"category": { "type": "keyword" },
"quantity": { "type": "integer" },
"revenue": { "type": "double" },
"ordered_at": { "type": "date" }
}
}
}在 orders 中,status、ship_country 和 channel 是 keyword,total 是 double,refunded 是 boolean,ordered_at 是 date。一筆訂單如下:
{ "order_id": 58213, "customer_id": 1042, "ordered_at": "2026-10-14T09:31:00",
"status": "delivered", "ship_country": "United Kingdom", "channel": "email",
"total": 288.0, "items": 2, "refunded": false, "categories": ["Cooking", "Tents"] }match、match_phrase 與 term
text 欄位在建立索引時會經過分析:「Ridgeline 2P tent」會被存成 ridgeline、2p 和 tent 這幾個 token。keyword 欄位則照原樣儲存。請依欄位類型選擇對應的 query。
match 會用同樣的方式分析你的文字,找出包含任一個字詞的文件,最相符的排在前面。加上 "operator": "and" 就會要求全部字詞都要出現:
GET /order_lines/_search
{
"query": { "match": { "product": { "query": "ridgeline tent", "operator": "and" } } }
}match_phrase 要求字詞相連且順序一致:
GET /order_lines/_search
{
"query": { "match_phrase": { "product": "Ridgeline 2P tent" } }
}term 不做任何分析,直接找精確值。請用在 keyword、數字、日期和布林欄位上;要比對多個值則用 terms:
GET /order_lines/_search
{
"query": { "term": { "product.keyword": "Ridgeline 2P tent" } }
}
GET /orders/_search
{
"query": { "terms": { "status": ["pending", "processing"] } }
}最常見的錯誤是在 text 欄位上用 term。{"term": {"product": "Ridgeline 2P tent"}} 不會傳回任何結果,因為沒有任何一個已儲存的 token 等於這個字串。Elasticsearch 文件寫得很清楚:text 欄位不要用 term。keyword 值有區分大小寫;需要時可以在 term 中加上 "case_insensitive": true。
bool:must、filter、should、must_not
bool 用來組合多個 query:
must:必須符合,並且會計入相關性分數。filter:必須符合,但不計分,因此可以被快取。適合用在「是/否」條件。should:非必要。如果沒有must或filter,至少要符合一個should;否則should只會提高分數。must_not:必須不符合。
已出貨或已送達、金額 200 以上、未退款的英國訂單,並讓 email 管道的訂單排在前面:
GET /orders/_search
{
"query": {
"bool": {
"filter": [
{ "terms": { "status": ["shipped", "delivered"] } },
{ "term": { "ship_country": "United Kingdom" } },
{ "range": { "total": { "gte": 200 } } }
],
"must_not": [ { "term": { "refunded": true } } ],
"should": [ { "term": { "channel": "email" } } ]
}
}
}因為有 filter,should 子句不會排除任何文件。加上 "minimum_should_match": 1 才會變成必要條件。
日期、範圍與缺少的欄位
range 接受 gt、gte、lt 和 lte。10 月的訂單,使用半開區間,才不會漏掉 10 月 31 日的資料:
GET /orders/_search
{
"query": {
"range": { "ordered_at": { "gte": "2026-10-01", "lt": "2026-11-01", "time_zone": "Europe/London" } }
}
}也可以用日期運算:"gte": "now-30d/d" 表示 30 天前,並往下取整到午夜。沒有指定 time_zone 時,不含時區偏移的日期會被視為 UTC。
exists 會找出某欄位有值的文件。null 和空陣列不算有值,所以沒有國家的訂單可以這樣找:
GET /orders/_search
{
"query": { "bool": { "must_not": { "exists": { "field": "ship_country" } } } }
}wildcard 與 prefix,以及它們的代價
GET /order_lines/_search
{
"query": { "prefix": { "product.keyword": "Ridgeline" } }
}
GET /order_lines/_search
{
"query": { "wildcard": { "product.keyword": { "value": "*tent", "case_insensitive": true } } }
}這兩種 query 都是針對 term 運作,而不是經過分析的字詞,所以請用在 keyword 欄位上。它們比 term 或 match 慢得多:以 * 或 ? 開頭的模式必須檢查欄位中的每一個 term,Elasticsearch 文件也建議避免這樣做。若叢集將 search.allow_expensive_queries 設為 false,會完全拒絕 wildcard query。要找「包含某個字」,正確做法是在 text 欄位上用 match。
排序、分頁與選擇欄位
size 設定傳回幾筆 hit(預設 10),from 跳過前面的 hit,sort 決定排序,_source 選擇要傳回的欄位。待處理訂單的第 3 頁,最新的排前面:
GET /orders/_search
{
"size": 20,
"from": 40,
"sort": [ { "ordered_at": "desc" }, { "order_id": "desc" } ],
"_source": ["order_id", "status", "total", "ordered_at"],
"query": { "term": { "status": "pending" } }
}第二個排序欄位用來決定同分時的順序,避免分頁內容重疊。from + size 預設不能超過 10,000 筆 hit(index.max_result_window)。若要往更深處翻頁,請開啟 point in time(PIT),再用 search_after 分頁,並帶入你收到的最後一筆 hit 的 sort 值:
POST /orders/_pit?keep_alive=1m # Elasticsearch
POST /orders/_search/point_in_time?keep_alive=1m # OpenSearch
GET /_search
{
"size": 20,
"pit": { "id": "<id from the call above>", "keep_alive": "1m" },
"sort": [ { "ordered_at": "desc" }, { "order_id": "desc" } ],
"search_after": [1791970260000, 58213]
}這個搜尋的路徑中沒有 index,因為 PIT 已經指定了。Elastic 已不再建議用 scroll API 做深度分頁。
Aggregation
Aggregation 會彙總符合條件的文件。只需要彙總結果時,請設定 "size": 0。過去一年依狀態統計的訂單數與營收:
GET /orders/_search
{
"size": 0,
"query": { "range": { "ordered_at": { "gte": "now-12M/M" } } },
"aggs": {
"status": {
"terms": { "field": "status" },
"aggs": {
"revenue": { "sum": { "field": "total" } },
"avg_order": { "avg": { "field": "total" } }
}
}
}
}每月退款訂單數,退款暴增時就能一眼看出:
GET /orders/_search
{
"size": 0,
"query": { "term": { "refunded": true } },
"aggs": {
"month": { "date_histogram": { "field": "ordered_at", "calendar_interval": "month" } }
}
}Aggregation 可以巢狀使用。每月前三大類別及其營收:
GET /order_lines/_search
{
"size": 0,
"aggs": {
"month": {
"date_histogram": { "field": "ordered_at", "calendar_interval": "month" },
"aggs": {
"categories": {
"terms": { "field": "category", "size": 3 },
"aggs": { "revenue": { "sum": { "field": "revenue" } } }
}
}
}
}
}注意事項:除非設定 size,否則 terms 只傳回前 10 個 bucket;在有多個 shard 的 index 上,它的計數可能是近似值;它預設依文件數排序,而 Elastic 提醒,依 sub-aggregation 排序可能會得到錯誤結果;它也不能用在 text 欄位上,請改用 .keyword 子欄位。calendar_interval 接受日曆單位,例如 month 或 1M;像 30m 這樣的固定時間長度請用 fixed_interval。
計數與查看叢集狀況
GET /orders/_count
{
"query": { "term": { "status": "pending" } }
}
GET /_cat/indices?v=true&s=store.size:desc
GET /_cat/indices/orders,order_lines?format=json&bytes=mb
GET /orders/_mapping_count 會給出精確的數量。搜尋結果中的 hits.total 計到 10,000 就會停止,除非設定 "track_total_hits": true。_cat API 是給人看的:v=true 會加上標頭,s 用來排序,format=json 則改為傳回 JSON 而不是文字表格。
SQL:Elasticsearch _sql 與 OpenSearch _plugins/_sql
兩種引擎都接受用 SQL 讀取資料,但 endpoint 不同。Elasticsearch:
POST /_sql?format=txt
{
"query": "SELECT status, COUNT(*) AS orders, SUM(total) AS revenue FROM orders GROUP BY status ORDER BY revenue DESC"
}
POST /_sql/translate
{
"query": "SELECT status, COUNT(*) FROM orders GROUP BY status"
}format 可以是 txt、json、csv 等;_sql/translate 會顯示你的 SQL 轉換後的 query DSL。Elasticsearch 8.14 以後的版本還有 ES|QL,這是一種管線式語言,endpoint 為 POST /_query,主體例如 {"query": "FROM orders | STATS orders = COUNT(*) BY status"}。
OpenSearch:
POST /_plugins/_sql
{
"query": "SELECT status, COUNT(*) AS orders, SUM(total) AS revenue FROM orders GROUP BY status"
}
POST /_plugins/_sql/_explain
{
"query": "SELECT status, COUNT(*) FROM orders GROUP BY status"
}回應格式預設為 jdbc;也可以用 ?format=csv 和 ?format=raw。OpenSearch 的另一種查詢語言 PPL 位於 POST /_plugins/_ppl,例如 source=orders | stats count() by status。
在 Tablux 中執行 console 請求
Mac、iPhone 和 iPad 上的 Tablux 對 Elasticsearch 和 OpenSearch 都接受相同的 console 語法:一行 GET、POST、PUT、DELETE、HEAD 或 PATCH,接著是 JSON 主體,也支援 # 和 // 註解行。多個請求會依序執行。hit 會變成資料列(_id、_index,接著是 _source 欄位);設定 "size": 0 時,第一個 bucket aggregation 會變成每個 bucket 一列,doc_count 以及 sum、avg 等單值 metric 則成為欄位;_count 和 _cat/…?format=json 也會以表格呈現。純 SQL 會送到 _sql 或 _plugins/_sql。刪除 index、match_all 的 _delete_by_query、_reindex 和 _close 在執行前都會先提出警示,而唯讀連線只允許讀取操作。
常見問題
Elasticsearch 中 match 和 term 有什麼不同?
match 會用與欄位相同的方式分析你的搜尋文字,所以適合 text 欄位。term 不做分析、直接找精確值,所以適合 keyword、數字、日期和布林欄位;用在 text 欄位上通常找不到任何結果。
Kibana 的 Dev Tools 在哪裡?
在導覽選單中找到 Dev Tools,或用全域搜尋列搜尋。它的 Console 會把請求送到 Kibana 所連線的叢集。
如何從 Elasticsearch 取得超過 10,000 筆結果?
from + size 預設最多到 10,000 筆 hit。請開啟 point in time,再用 search_after 分頁,並帶入最後一筆 hit 的 sort 值。
bool query 中的 must 和 filter 有什麼不同?
兩者都必須符合。must 會計入相關性分數;filter 不計分且可被快取,所以狀態或日期範圍這類「是/否」條件請用 filter。
Kibana console 的 query 可以在 OpenSearch 中使用嗎?
可以。OpenSearch Dashboards 有相同的 Dev Tools console,本指南中的 query DSL 適用於 OpenSearch 2 和 3。Point in time 和 SQL 使用的 endpoint 不同。
如何對 Elasticsearch 或 OpenSearch 執行 SQL?
Elasticsearch:POST /_sql?format=txt,主體為 {"query": "SELECT …"}。OpenSearch:POST /_plugins/_sql,使用相同的主體。
更新日期 2026-11-26