kql
microsoft/skills
撰寫正確且高效的 Kusto 查詢語言(KQL)查詢,內容涵蓋語法、聯結、動態類型、日期時間的常見陷阱、正規表達式、序列化、記憶體管理以及進階函式。
...展開全部KQL 精通
親自試試看:此技能的所有
✅本技能中的範例皆可於公開的協助叢集上執行:https://help.kusto.windows.net,資料庫Samples(包含StormEvents,SimpleGraph_Nodes/Edges,nyc_taxi,以及更多)。
1. KQL 基礎知識
Kusto 查詢語言(KQL)是一種用於探索資料的管線式查詢語言。它是 Azure Data Explorer (ADX)、Microsoft Fabric 即時智慧 (EventHouse)、Azure Monitor Log Analytics、Microsoft Sentinel 及其他 Microsoft 資料服務的原生查詢語言。
管線向前語法
KQL 查詢是由以 |分隔的操作子串聯而成。資料流從左至右流動:
StormEvents // start with a table
| where State == "TEXAS" // filter rows
| summarize count() by EventType // aggregate
| top 5 by count_ desc // limit results
查詢與管理指令
KQL 具有兩個執行層面:
| 執行層 | 始於 | 範例 |
|---|---|---|
| 查詢 | 表名稱、 let, print, datatable |
StormEvents | where State == "TEXAS" |
| 管理 | .show, .create, .set, .drop, .alter |
.show tables, .show table T schema |
管理指令後可接續查詢運算子(輸出為表格格式),但整個請求皆在管理層執行。您無法以查詢開頭,並將結果傳送至管理指令中。
// ✅ WORKS — management command piped to query operators
.show tables | project TableName | where TableName has "Events"
// ❌ WRONG — query piped into management command
StormEvents | take 5 | .show tables
如有疑問:若第一個標記以 .,則為管理指令。如需完整的架構探索指令清單,請參閱 references/discovery-queries.md.
2. 動態類型規範
KQL 的 dynamic 的類型雖具彈性,但在特定情境下仍相當嚴格。常見的錯誤是將動態欄位用於 summarize by, order by中,或 join on 中使用動態欄位卻未進行型別轉換。
規則:每當您在 by, on或 order by中使用動態型別的欄位時,請務必以明確的型別轉換包裹它。
// ❌ ERROR: "Summarize group key ... is of a 'dynamic' type"
StormEvents | summarize count() by StormSummary.Details.Location
// ✅ FIX
StormEvents | summarize count() by tostring(StormSummary.Details.Location)
// ❌ ERROR: "order operator: key can't be of dynamic type"
StormEvents | order by StormSummary.TotalDamages desc
// ✅ FIX
StormEvents | order by tolong(StormSummary.TotalDamages) desc
// ❌ ERROR in join: dynamic join key
StormEvents | join kind=inner (PopulationData) on $left.StormSummary == $right.State
// ✅ FIX — cast both sides
StormEvents
| extend State_str = tostring(StormSummary.Details.Location)
| join kind=inner (PopulationData) on $left.State_str == $right.State
自我修正:當你在錯誤訊息中看到「是『動態』類型」時,請加上 tostring(), tolong(),或 todouble().
3. 聯結模式與陷阱
KQL JOIN 運算式的限制條件與 SQL 不同。
僅等值
KQL 的聯結條件僅支援==。聯結判準中不 <, >, !=,或函式呼叫。
// ❌ ERROR: "Only equality is allowed in this context"
StormEvents | join (nyc_taxi) on geo_distance_2points(BeginLon, BeginLat, pickup_longitude, pickup_latitude) < 1000
// ✅ WORKAROUND — pre-bucket into spatial cells, then join on cell ID
StormEvents
| extend cell = geo_point_to_s2cell(BeginLon, BeginLat, 8)
| join kind=inner (nyc_taxi | extend cell = geo_point_to_s2cell(pickup_longitude, pickup_latitude, 8)) on cell
對於範圍聯結,預先分箱的值: | extend bin_val = bin(Value, 100),然後根據 bin_val。注意:接近區間邊界的值可能會落入相鄰的區間中——為確保精確度,請考慮檢查相鄰區間或讓範圍有所重疊。
左/右屬性匹配
聯結 on 子句的兩側都必須僅引用欄位實體 — 不得引用表達式或彙總函數。
// ❌ ERROR: "for each left attribute, right attribute should be selected"
StormEvents | join kind=inner (PopulationData) on $left.State
// ✅ FIX — specify both sides explicitly
StormEvents | join kind=inner (PopulationData) on $left.State == $right.State
執行大規模聯結前的基數檢查
在彙合行數超過 1 萬的資料表前,務必檢查基數。一次交叉彙合的爆炸性增長,正是導致該單一 E_RUNAWAY_QUERY 錯誤的根源(25K × 195 = 潛在 480 萬行)。
// Before joining, check how many rows each side contributes
StormEvents | summarize dcount(State) // → 67 distinct states
PopulationData | summarize dcount(State) // → 52 — safe to join
4. KQL 中的正規表達式
KQL 原生支援正規表達式 — 無需使用 Python。
此處的 extract_all 注意事項
與 Python 的 re.findall()不同,KQL 的 extract_all 在正規表達式中需要使用擷取群組:
// ❌ ERROR: "extractall(): argument 2 must be a valid regex with [1..16] matching groups"
StormEvents | extend words = extract_all(@"[a-zA-Z]{3,}", EventNarrative)
// ✅ FIX — add parentheses around the pattern
StormEvents | extend words = extract_all(@"([a-zA-Z]{3,})", EventNarrative)
正規表達式工具組 — 切勿回退至 Python
| 函式 | 使用案例 | 範例 |
|---|---|---|
extract(regex, group, source) |
單一匹配 | extract(@"User '([^']+)'", 1, Msg) |
extract_all(regex, source) |
所有匹配(需要 ()) |
extract_all(@"(\w+)", Text) |
parse |
結構化擷取 | parse Msg with * "User '" Sender "' sent" * |
matches regex |
布林篩選 | where Url matches regex @"^https?://" |
replace_regex |
尋找與替換 | replace_regex(Text, @"\s+", " ") |
5. 序列化要求
視窗函數需要序列化(有序)的輸入。
// ❌ ERROR: "Function 'row_cumsum' cannot be invoked. The row set must be serialized."
StormEvents
| where State == "TEXAS"
| summarize DailyCount = count() by bin(StartTime, 1d)
| extend CumulativeCount = row_cumsum(DailyCount)
// ✅ FIX — add | serialize (or | order by, which implicitly serializes)
StormEvents
| where State == "TEXAS"
| summarize DailyCount = count() by bin(StartTime, 1d)
| order by StartTime asc
| extend CumulativeCount = row_cumsum(DailyCount)
需要序列化的函數: row_number(), row_cumsum(), prev(), next(), row_window_session().
6. 記憶體安全查詢模式
最常見的記憶體錯誤。成因在於未經預先篩選便掃描過多資料。
安全性演進
Safest ──────────────────────────────────────────────── Most dangerous
| count | take 10 | where + summarize | summarize (no filter) | full scan
針對大型資料表(>100 萬筆)的規則
- 務必先執行 `
| count` 以掌握資料表大小 - 在執行 `
| summarize` 之前,務必先執行 `| where` —— 請先過濾時間範圍、分區鍵或類別 - 切勿在未進行預篩選的情況下,對高基數欄位執行 `
dcount()` - 執行前請先檢查聯結基數(參見第 3 節)
- 針對被多次引用的子查詢,應使用 `
materialize()`
// ❌ OUT OF MEMORY — large table, no filter, many group-by columns
StormEvents
| summarize dcount(EventType), count() by StartTime, State, Source
| where dcount_EventType > 1
// ✅ SAFE — filter first, then aggregate
StormEvents
| where StartTime between (datetime(2007-04-15) .. datetime(2007-04-16))
| summarize dcount(EventType) by State, Source
| where dcount_EventType > 1
當您看到 E_LOW_MEMORY_CONDITION
「查詢涉及過多資料」時,您的選項:
- 新增
| where篩選條件(時間範圍、分區鍵) - 減少
by列的數量summarize - 將資料拆分為較小的時間區間,並將結果進行聯合
- 使用
| sample 10000進行探索性分析,而非執行全表掃描
當您發現 E_RUNAWAY_QUERY
某個聯結或彙總產生了過多的輸出列時,請檢查聯結基數——一方或雙方規模過大。
7. 結果大小管理
過大的結果集會拖慢分析速度。預防措施:
| 查詢類型 | 防護措施 |
|---|---|
| 探索性 | 務必以 | take 10 或 | take 20 |
| 彙總 | 使用 | top 20 by ... 而非無界 summarize |
| 寬列(向量、JSON) | | project 僅需列 |
make_list() / make_set() |
應避免用於高基數群組(會產生龐大的儲存格) |
| 未知大小 | 執行 | count 優先執行 |
向量陷阱:包含嵌入欄位的資料表(1536 維浮點數陣列)每行會產生約 30KB。即使 | take 20 會產生 600KB。除非您確實需要,否則請始終 | project 移除向量欄位,除非您確實需要它們。
8. 字串比對的嚴格程度
KQL 在比較計算得出的字串值時,有時需要明確進行型別轉換——即使雙方原本已是字串。
// ❌ ERROR: "Cannot compare values of types string and string. Try adding explicit casts"
StormEvents | where geo_point_to_s2cell(BeginLon, BeginLat, 16) == other_cell
// ✅ FIX — wrap both sides in tostring()
StormEvents | where tostring(geo_point_to_s2cell(BeginLon, BeginLat, 16)) == tostring(other_cell)
這種情況最常發生在來自 geo_point_to_s2cell() 與 strcat() 運算所產生的計算結果最為常見。如有疑問,請使用 tostring().
9. 進階函式
KQL 會原生處理這些情況——無需使用 Python:
向量相似度
// try it! — cosine similarity on Iris feature vectors
let target = pack_array(5.1, 3.5, 1.4, 0.2);
Iris
| extend Vec = pack_array(SepalLength, SepalWidth, PetalLength, PetalWidth)
| extend sim = series_cosine_similarity(Vec, target)
| top 5 by sim desc
地理運算
// Distance between two points (meters)
StormEvents | extend dist = geo_distance_2points(BeginLon, BeginLat, EndLon, EndLat)
// Spatial bucketing for joins
StormEvents | extend cell = geo_point_to_s2cell(BeginLon, BeginLat, 8)
圖查詢
// Persistent graph model — try it on the help cluster!
graph("Simple")
| graph-match (src)-[e*1..3]->(dst)
where src.name == "Alice"
project src.name, dst.name, path_length = array_length(e)
// Transient graph — build inline with make-graph
SimpleGraph_Edges
| make-graph source --> target with SimpleGraph_Nodes on id
| graph-match (src)-[e*1..5]->(dst)
where src.name == "Alice"
project src.name, dst.name, path_length = array_length(e)
時間序列
// try it! — create a time series and detect anomalies
StormEvents
| make-series count() default=0 on StartTime step 1d
| extend anomalies = series_decompose_anomalies(count_)
如需詳細範例與模式,請參閱 references/advanced-patterns.md.
10. 自動修正查表
當您遇到錯誤時,請在重新嘗試之前先在此處查詢:
| 錯誤訊息包含 | 可能原因 | 解決方法 |
|---|---|---|
is of a 'dynamic' type |
動態欄位位於 by/on/order by |
請以 tostring()/tolong() |
Only equality is allowed |
聯結條件中的範圍謂詞 | 包含 S2/H3 儲存單元的預先分桶,或 bin() |
extractall(): matching groups |
遺漏 () 在正規表達式中 |
新增 (): @"(\w+)" not @"\w+" |
row set must be serialized |
對未排序資料套用視窗函數 | 新增 | serialize 或 | order by 在其前 |
Cannot compare values of types string and string |
計算後的字串比較 | 在 tostring() 兩側 |
Failed to resolve column named 'X' |
欄位名稱錯誤或資料表錯誤 | 執行 .show table T schema 以檢查欄位名稱 |
E_LOW_MEMORY_CONDITION |
查詢涉及的資料過多 | 新增 | where 篩選條件、縮短時間範圍、分階段執行 |
E_RUNAWAY_QUERY |
聯結/彙總產生過多資料列 | 在進行聯結前檢查基數;新增預篩選條件 |
for each left attribute, right attribute |
聯結 on 子句不完整 |
請使用顯式形式: on $left.X == $right.Y |
needs to be bracketed |
將保留字用作識別符 | 請使用 ['keyword'] 語法 |
plugin doesn't exist |
此叢集上無法使用該外掛程式 | 回退至等效函式或 Python |
Expected string literal in datetime() |
datetime 字面量中的裸整數 | 使用 datetime(2024-01-01) not datetime(2024) |
Unexpected token 之後 by |
在 `summarize by` 子句中使用複雜表達式 | extend 先處理該表達式,然後 summarize by 該欄位 |
not recognized / unknown operator |
此引擎不支援該運算子 | 請檢查運算子支援狀況;嘗試使用等效運算子 (order by = sort by) |
11. 日期與時間的陷阱
日期時間字面值是常見的錯誤來源。錯誤的字面值格式可能會引發連鎖反應,導致必須採取截然不同的解決方案,而非僅能解決這個小問題。
字面值格式
// ❌ WRONG — bare year is not a valid datetime
StormEvents | where StartTime > datetime(2007)
// ✅ RIGHT — always use full date format
StormEvents | where StartTime > datetime(2007-01-01)
依年、月或小時篩選
// ❌ WRONG — comparing datetime column to integer
StormEvents | where StartTime == 2007
// ✅ RIGHT — use datetime_part() to extract components
StormEvents | where datetime_part("year", StartTime) == 2007
// ✅ ALSO RIGHT — use between with datetime range
StormEvents | where StartTime between (datetime(2007-01-01) .. datetime(2007-12-31T23:59:59))
在 `summarize` 中進行時間分桶
// This works, but can be harder to read and reuse in complex queries
StormEvents | summarize count() by startofmonth(StartTime)
// Clearer — extend first, then summarize by the computed column
StormEvents
| extend Month = startofmonth(StartTime)
| summarize count() by Month
| order by Month asc
實用的日期時間函數
| 函數 | 用途 | 範例 |
|---|---|---|
bin(ts, 1h) |
向下取整至區間邊界 | bin(Timestamp, 1d) |
startofmonth(ts) |
當月首日 | startofmonth(Timestamp) |
datetime_part("hour", ts) |
萃取組成部分 | datetime_part("year", Timestamp) |
format_datetime(ts, fmt) |
格式化為字串 | format_datetime(Timestamp, "yyyy-MM") |
ago(1d) |
相對時間 | where Timestamp > ago(1d) |
between(a .. b) |
範圍篩選(含起始值) | where Timestamp between (datetime(2024-01-01) .. datetime(2024-01-31T23:59:59)) |
todatetime(str) |
解析字串 → 日期時間 | todatetime("2024-01-15T10:30:00Z") |
totimespan(str) |
解析字串 → 時間間隔 | totimespan("01:30:00") |
12. 運算子命名與等值
KQL 與 SQL 語法存在細微差異。
命名規範
| 實體 | 規範 | 範例 |
|---|---|---|
| 資料表 | 大寫駝峰式 | StormEvents, NetworkLogs |
| 欄位 | 駱駝式大寫 | StartTime, EventType |
變數 (let) |
蛇形命名法 | let filtered_events = ... |
| 內建函式 | 蛇形命名法 | format_bytes(), geo_distance_2points() |
| 儲存函式 | 駱駝大寫 | .create function GetTopUsers |
相等運算子
// In where clauses, == is case-sensitive, =~ is case-insensitive
StormEvents | where State == "TEXAS" | count // exact match
StormEvents | where State =~ "texas" | count // case-insensitive
// In joins, use == only
StormEvents | join kind=inner (PopulationData) on State
排序 vs 順序
兩者皆可 sort by 和 order by 在KQL中運作方式完全相同 — 它們是別名。請隨意選用其中一種,但請保持一致。
contains 與 has
// contains: substring match (slower)
StormEvents | where EventNarrative contains "tree" // finds "trees", "treetop" too
// has: term/word match (faster, uses index)
StormEvents | where EventNarrative has "tree" // matches word boundaries only
// For exact prefix/suffix
StormEvents | where EventType startswith "Thunder"
StormEvents | where Source endswith "Spotter"
13. 錯誤復原策略
當第一個 KQL 查詢失敗時,人們往往會忍不住想放棄整個方法,轉而嘗試完全不同的做法。正確的應對方式幾乎總是修正該特定錯誤,而非改變策略。
應避免的模式
Query 1: extract(@"pattern", 1, col) → Parse error
Query 2: todynamic(col) → Different error
Query 3: parse_json(col) → Another error
Query 4: Python script → Works but 10x tokens
正確的模式
Query 1: extract(@"pattern", 1, col) → Parse error (bad escaping)
Query 2: extract(@"pattern", 1, col) → Fix the specific escaping issue → Success
錯誤復原規則:
- 仔細閱讀錯誤訊息——它幾乎總是能精確指出問題所在
- 修正具體的語法/轉義問題,不要更換方法
- 使用「自我修正表」(第 10 節)將錯誤對應至解決方案
- 僅在同一個查詢嘗試修正兩次失敗後,才更換處理方法
- 該
parse運算子通常比extract():
// Instead of complex regex on TraceLogs:
// extract(@"file path: \"\"([^\"]+)\"\"", 1, Message)
// Use parse for structured extraction (try it on help cluster, SampleLogs db):
cluster("help").database("SampleLogs").TraceLogs
| where Message has "file path"
| parse Message with * "file path: \"\"" FilePath "\"\"" *
| project Timestamp, FilePath
| take 5
14. 查詢撰寫檢查清單
在執行任何 KQL 查詢之前,請在腦中確認:
- 是否已預先過濾?大型資料表有
| where在執行任何| summarize - 結果範圍是否明確?探索性查詢應以
| take N或| top N - 動態欄位已轉換型別?任何動態欄位在
by/on/order by會被包裹 - 正則表達式含有分組嗎?
extract_all模式中包含()包圍您想要擷取的內容 - 連接的基數是否安全?雙方皆已透過
dcount()在進行彙合前 - 僅保留所需欄位?寬表會
| project刪除不需要的欄位 - 日期時間字面值是否有效?使用
datetime(2024-01-01)不datetime(2024)或裸整數 - 複雜的 by-表達式?請先使用
| extend,然後| summarize by計算欄位 - 錯誤恢復方案?若查詢失敗,請修正特定錯誤 — 切勿變更策略
---
name: kql
description: Write correct, efficient Kusto Query Language queries with coverage of syntax, joins, dynamic types, datetime pitfalls, regex, serialization, memory management, and advanced functions.
---
# KQL Mastery
> **Try it yourself**: All `✅` examples in this skill can be run against the public help cluster:
> `https://help.kusto.windows.net`, database `Samples` (contains `StormEvents`, `SimpleGraph_Nodes`/`Edges`, `nyc_taxi`, and more).
## 1. KQL Basics
Kusto Query Language (KQL) is a pipe-forward query language for exploring data. It is the native query language for Azure Data Explorer (ADX), Microsoft Fabric Real-Time Intelligence (EventHouse), Azure Monitor Log Analytics, Microsoft Sentinel, and other Microsoft data services.
### Pipe-forward syntax
KQL queries are a chain of operators separated by `|`. Data flows left to right:
```kql
StormEvents // start with a table
| where State == "TEXAS" // filter rows
| summarize count() by EventType // aggregate
| top 5 by count_ desc // limit results
```
### Query vs management commands
KQL has two execution planes:
| Plane | Starts with | Examples |
|-------|-------------|----------|
| **Query** | Table name, `let`, `print`, `datatable` | `StormEvents \| where State == "TEXAS"` |
| **Management** | `.show`, `.create`, `.set`, `.drop`, `.alter` | `.show tables`, `.show table T schema` |
Management commands can be followed by query operators (the output is tabular), but the entire request runs on the management plane. You cannot start with a query and pipe into a management command.
```kql
// ✅ WORKS — management command piped to query operators
.show tables | project TableName | where TableName has "Events"
// ❌ WRONG — query piped into management command
StormEvents | take 5 | .show tables
```
When in doubt: if the first token starts with `.`, it's a management command. For a full catalog of schema exploration commands, see `references/discovery-queries.md`.
## 2. Dynamic Type Discipline
KQL's `dynamic` type is flexible but strict in certain contexts. A common mistake is using a dynamic column in `summarize by`, `order by`, or `join on` without casting.
**The rule**: Any time you use a dynamic-typed column in `by`, `on`, or `order by`, wrap it in an explicit cast.
```kql
// ❌ ERROR: "Summarize group key ... is of a 'dynamic' type"
StormEvents | summarize count() by StormSummary.Details.Location
// ✅ FIX
StormEvents | summarize count() by tostring(StormSummary.Details.Location)
```
```kql
// ❌ ERROR: "order operator: key can't be of dynamic type"
StormEvents | order by StormSummary.TotalDamages desc
// ✅ FIX
StormEvents | order by tolong(StormSummary.TotalDamages) desc
```
```kql
// ❌ ERROR in join: dynamic join key
StormEvents | join kind=inner (PopulationData) on $left.StormSummary == $right.State
// ✅ FIX — cast both sides
StormEvents
| extend State_str = tostring(StormSummary.Details.Location)
| join kind=inner (PopulationData) on $left.State_str == $right.State
```
**Self-correction**: When you see "is of a 'dynamic' type" in an error, add `tostring()`, `tolong()`, or `todouble()`.
## 3. Join Patterns & Pitfalls
KQL joins have constraints that differ from SQL.
### Equality only
KQL join conditions support **only `==`**. No `<`, `>`, `!=`, or function calls in join predicates.
```kql
// ❌ ERROR: "Only equality is allowed in this context"
StormEvents | join (nyc_taxi) on geo_distance_2points(BeginLon, BeginLat, pickup_longitude, pickup_latitude) < 1000
// ✅ WORKAROUND — pre-bucket into spatial cells, then join on cell ID
StormEvents
| extend cell = geo_point_to_s2cell(BeginLon, BeginLat, 8)
| join kind=inner (nyc_taxi | extend cell = geo_point_to_s2cell(pickup_longitude, pickup_latitude, 8)) on cell
```
For range joins, pre-bin values: `| extend bin_val = bin(Value, 100)`, then join on `bin_val`. Note: values near bin boundaries may land in adjacent bins — consider checking neighboring bins or overlapping the range for precision.
### Left/right attribute matching
Both sides of a join `on` clause must reference **column entities only** — not expressions, not aggregates.
```kql
// ❌ ERROR: "for each left attribute, right attribute should be selected"
StormEvents | join kind=inner (PopulationData) on $left.State
// ✅ FIX — specify both sides explicitly
StormEvents | join kind=inner (PopulationData) on $left.State == $right.State
```
### Cardinality check before large joins
**Always** check cardinality before joining tables with >10K rows. A cross-join explosion was the source of the single `E_RUNAWAY_QUERY` error (25K × 195 = potential 4.8M rows).
```kql
// Before joining, check how many rows each side contributes
StormEvents | summarize dcount(State) // → 67 distinct states
PopulationData | summarize dcount(State) // → 52 — safe to join
```
## 4. Regex in KQL
KQL handles regex natively — no need for Python.
### The `extract_all` gotcha
Unlike Python's `re.findall()`, KQL's `extract_all` **requires capturing groups** in the regex:
```kql
// ❌ ERROR: "extractall(): argument 2 must be a valid regex with [1..16] matching groups"
StormEvents | extend words = extract_all(@"[a-zA-Z]{3,}", EventNarrative)
// ✅ FIX — add parentheses around the pattern
StormEvents | extend words = extract_all(@"([a-zA-Z]{3,})", EventNarrative)
```
### Regex toolkit — don't fall back to Python
| Function | Use case | Example |
|----------|----------|---------|
| `extract(regex, group, source)` | Single match | `extract(@"User '([^']+)'", 1, Msg)` |
| `extract_all(regex, source)` | All matches (needs `()`) | `extract_all(@"(\w+)", Text)` |
| `parse` | Structured extraction | `parse Msg with * "User '" Sender "' sent" *` |
| `matches regex` | Boolean filter | `where Url matches regex @"^https?://"` |
| `replace_regex` | Find and replace | `replace_regex(Text, @"\s+", " ")` |
## 5. Serialization Requirements
Window functions need serialized (ordered) input.
```kql
// ❌ ERROR: "Function 'row_cumsum' cannot be invoked. The row set must be serialized."
StormEvents
| where State == "TEXAS"
| summarize DailyCount = count() by bin(StartTime, 1d)
| extend CumulativeCount = row_cumsum(DailyCount)
// ✅ FIX — add | serialize (or | order by, which implicitly serializes)
StormEvents
| where State == "TEXAS"
| summarize DailyCount = count() by bin(StartTime, 1d)
| order by StartTime asc
| extend CumulativeCount = row_cumsum(DailyCount)
```
Functions requiring serialization: `row_number()`, `row_cumsum()`, `prev()`, `next()`, `row_window_session()`.
## 6. Memory-Safe Query Patterns
The most common memory error. Caused by scanning too much data without pre-filtering.
### The progression of safety
```
Safest ──────────────────────────────────────────────── Most dangerous
| count | take 10 | where + summarize | summarize (no filter) | full scan
```
### Rules for large tables (>1M rows)
1. **Always start with `| count`** to understand table size
2. **Always `| where` before `| summarize`** — filter time range, partition key, or category first
3. **Never `dcount()` on high-cardinality columns** without pre-filtering
4. **Check join cardinality** before executing (see Section 3)
5. **Use `materialize()`** for subqueries referenced multiple times
```kql
// ❌ OUT OF MEMORY — large table, no filter, many group-by columns
StormEvents
| summarize dcount(EventType), count() by StartTime, State, Source
| where dcount_EventType > 1
// ✅ SAFE — filter first, then aggregate
StormEvents
| where StartTime between (datetime(2007-04-15) .. datetime(2007-04-16))
| summarize dcount(EventType) by State, Source
| where dcount_EventType > 1
```
### When you see `E_LOW_MEMORY_CONDITION`
The query touched too much data. Your options:
- Add `| where` filters (time range, partition key)
- Reduce the number of `by` columns in `summarize`
- Break into smaller time windows and union results
- Use `| sample 10000` for exploratory work instead of full scans
### When you see `E_RUNAWAY_QUERY`
A join or aggregation produced too many output rows. Check join cardinality — one or both sides is too large.
## 7. Result Size Discipline
Large results slow down analysis. Prevention:
| Query type | Safeguard |
|-----------|-----------|
| Exploratory | Always end with `\| take 10` or `\| take 20` |
| Aggregation | Use `\| top 20 by ...` not unbounded `summarize` |
| Wide rows (vectors, JSON) | `\| project` only needed columns |
| `make_list()` / `make_set()` | Avoid on high-cardinality groups (produces huge cells) |
| Unknown size | Run `\| count` first |
**The vector trap**: Tables with embedding columns (1536-dim float arrays) produce ~30KB per row. Even `| take 20` yields 600KB. Always `| project` away vector columns unless you specifically need them.
## 8. String Comparison Strictness
KQL sometimes requires explicit casts when comparing computed string values — even when both sides are already strings.
```kql
// ❌ ERROR: "Cannot compare values of types string and string. Try adding explicit casts"
StormEvents | where geo_point_to_s2cell(BeginLon, BeginLat, 16) == other_cell
// ✅ FIX — wrap both sides in tostring()
StormEvents | where tostring(geo_point_to_s2cell(BeginLon, BeginLat, 16)) == tostring(other_cell)
```
This is most common with computed values from `geo_point_to_s2cell()` and `strcat()` comparisons. When in doubt, cast with `tostring()`.
## 9. Advanced Functions
KQL handles these natively — no need for Python:
### Vector similarity
```kql
// try it! — cosine similarity on Iris feature vectors
let target = pack_array(5.1, 3.5, 1.4, 0.2);
Iris
| extend Vec = pack_array(SepalLength, SepalWidth, PetalLength, PetalWidth)
| extend sim = series_cosine_similarity(Vec, target)
| top 5 by sim desc
```
### Geo operations
```kql
// Distance between two points (meters)
StormEvents | extend dist = geo_distance_2points(BeginLon, BeginLat, EndLon, EndLat)
// Spatial bucketing for joins
StormEvents | extend cell = geo_point_to_s2cell(BeginLon, BeginLat, 8)
```
### Graph queries
```kql
// Persistent graph model — try it on the help cluster!
graph("Simple")
| graph-match (src)-[e*1..3]->(dst)
where src.name == "Alice"
project src.name, dst.name, path_length = array_length(e)
// Transient graph — build inline with make-graph
SimpleGraph_Edges
| make-graph source --> target with SimpleGraph_Nodes on id
| graph-match (src)-[e*1..5]->(dst)
where src.name == "Alice"
project src.name, dst.name, path_length = array_length(e)
```
### Time series
```kql
// try it! — create a time series and detect anomalies
StormEvents
| make-series count() default=0 on StartTime step 1d
| extend anomalies = series_decompose_anomalies(count_)
```
For detailed examples and patterns, consult `references/advanced-patterns.md`.
## 10. Self-Correction Lookup Table
When you encounter an error, look it up here before retrying:
| Error message contains | Likely cause | Fix |
|---|---|---|
| `is of a 'dynamic' type` | Dynamic column in `by`/`on`/`order by` | Wrap in `tostring()`/`tolong()` |
| `Only equality is allowed` | Range predicate in join condition | Pre-bucket with S2/H3 cells or `bin()` |
| `extractall(): matching groups` | Missing `()` in regex | Add `()`: `@"(\w+)"` not `@"\w+"` |
| `row set must be serialized` | Window function on unsorted data | Add `\| serialize` or `\| order by` before it |
| `Cannot compare values of types string and string` | Computed string comparison | Add `tostring()` on both sides |
| `Failed to resolve column named 'X'` | Wrong column name or wrong table | Run `.show table T schema` to check column names |
| `E_LOW_MEMORY_CONDITION` | Query touched too much data | Add `\| where` filters, reduce time range, break into steps |
| `E_RUNAWAY_QUERY` | Join/aggregation produced too many rows | Check cardinality before joining; add pre-filters |
| `for each left attribute, right attribute` | Join `on` clause incomplete | Use explicit form: `on $left.X == $right.Y` |
| `needs to be bracketed` | Reserved word used as identifier | Use `['keyword']` syntax |
| `plugin doesn't exist` | Unavailable plugin on this cluster | Fall back to equivalent function or Python |
| `Expected string literal in datetime()` | Bare integer in datetime literal | Use `datetime(2024-01-01)` not `datetime(2024)` |
| `Unexpected token` after `by` | Complex expression in summarize by-clause | `extend` the expression first, then `summarize by` the column |
| `not recognized` / `unknown operator` | Operator not available on this engine | Check operator support; try equivalent (`order by` = `sort by`) |
## 11. Datetime Pitfalls
Datetime literals are a common source of errors. A wrong literal format can cascade into completely different approaches instead of fixing the small issue.
### Literal format
```kql
// ❌ WRONG — bare year is not a valid datetime
StormEvents | where StartTime > datetime(2007)
// ✅ RIGHT — always use full date format
StormEvents | where StartTime > datetime(2007-01-01)
```
### Filtering by year, month, or hour
```kql
// ❌ WRONG — comparing datetime column to integer
StormEvents | where StartTime == 2007
// ✅ RIGHT — use datetime_part() to extract components
StormEvents | where datetime_part("year", StartTime) == 2007
// ✅ ALSO RIGHT — use between with datetime range
StormEvents | where StartTime between (datetime(2007-01-01) .. datetime(2007-12-31T23:59:59))
```
### Time bucketing in summarize
```kql
// This works, but can be harder to read and reuse in complex queries
StormEvents | summarize count() by startofmonth(StartTime)
// Clearer — extend first, then summarize by the computed column
StormEvents
| extend Month = startofmonth(StartTime)
| summarize count() by Month
| order by Month asc
```
### Useful datetime functions
| Function | Purpose | Example |
|----------|---------|---------|
| `bin(ts, 1h)` | Round down to bucket boundary | `bin(Timestamp, 1d)` |
| `startofmonth(ts)` | First day of month | `startofmonth(Timestamp)` |
| `datetime_part("hour", ts)` | Extract component | `datetime_part("year", Timestamp)` |
| `format_datetime(ts, fmt)` | Format as string | `format_datetime(Timestamp, "yyyy-MM")` |
| `ago(1d)` | Relative time | `where Timestamp > ago(1d)` |
| `between(a .. b)` | Range filter (inclusive) | `where Timestamp between (datetime(2024-01-01) .. datetime(2024-01-31T23:59:59))` |
| `todatetime(str)` | Parse string → datetime | `todatetime("2024-01-15T10:30:00Z")` |
| `totimespan(str)` | Parse string → timespan | `totimespan("01:30:00")` |
## 12. Operator Naming & Equality
KQL has subtle differences from SQL syntax.
### Naming conventions
| Entity | Convention | Example |
|--------|-----------|---------|
| Tables | UpperCamelCase | `StormEvents`, `NetworkLogs` |
| Columns | UpperCamelCase | `StartTime`, `EventType` |
| Variables (`let`) | snake_case | `let filtered_events = ...` |
| Built-in functions | snake_case | `format_bytes()`, `geo_distance_2points()` |
| Stored functions | UpperCamelCase | `.create function GetTopUsers` |
### Equality operators
```kql
// In where clauses, == is case-sensitive, =~ is case-insensitive
StormEvents | where State == "TEXAS" | count // exact match
StormEvents | where State =~ "texas" | count // case-insensitive
// In joins, use == only
StormEvents | join kind=inner (PopulationData) on State
```
### sort vs order
Both `sort by` and `order by` work identically in KQL — they are aliases. Use whichever you prefer, but be consistent.
### contains vs has
```kql
// contains: substring match (slower)
StormEvents | where EventNarrative contains "tree" // finds "trees", "treetop" too
// has: term/word match (faster, uses index)
StormEvents | where EventNarrative has "tree" // matches word boundaries only
// For exact prefix/suffix
StormEvents | where EventType startswith "Thunder"
StormEvents | where Source endswith "Spotter"
```
## 13. Error Recovery Strategy
When a first KQL query fails, the temptation is to abandon the entire approach and try something completely different. The correct response is almost always to **fix the specific error**, not change strategy.
### The pattern to avoid
```
Query 1: extract(@"pattern", 1, col) → Parse error
Query 2: todynamic(col) → Different error
Query 3: parse_json(col) → Another error
Query 4: Python script → Works but 10x tokens
```
### The correct pattern
```
Query 1: extract(@"pattern", 1, col) → Parse error (bad escaping)
Query 2: extract(@"pattern", 1, col) → Fix the specific escaping issue → Success
```
**Rules for error recovery:**
1. Read the error message carefully — it almost always tells you exactly what's wrong
2. Fix the **specific** syntax/escaping issue, don't switch approaches
3. Use the self-correction table (Section 10) to map errors to fixes
4. Only switch approaches after 2 failed fixes of the same query
5. The `parse` operator is often simpler than `extract()` for structured text:
```kql
// Instead of complex regex on TraceLogs:
// extract(@"file path: \"\"([^\"]+)\"\"", 1, Message)
// Use parse for structured extraction (try it on help cluster, SampleLogs db):
cluster("help").database("SampleLogs").TraceLogs
| where Message has "file path"
| parse Message with * "file path: \"\"" FilePath "\"\"" *
| project Timestamp, FilePath
| take 5
```
## 14. Query Writing Checklist
Before running any KQL query, mentally check:
1. **Pre-filtered?** Large tables have a `| where` before any `| summarize`
2. **Result bounded?** Exploratory queries end with `| take N` or `| top N`
3. **Dynamic columns cast?** Any dynamic column in `by`/`on`/`order by` is wrapped
4. **Regex has groups?** `extract_all` patterns have `()` around what you want to capture
5. **Join cardinality safe?** Both sides checked with `dcount()` before joining
6. **Needed columns only?** Wide tables get `| project` to drop unneeded columns
7. **Datetime literals valid?** Using `datetime(2024-01-01)` not `datetime(2024)` or bare integers
8. **Complex by-expressions?** Use `| extend` first, then `| summarize by` the computed column
9. **Error recovery plan?** If a query fails, fix the specific error — don't change strategy
所有檔案
0 個檔案安裝 kql
請下載技能檔案,並將其解壓縮至您的 .claude/skills/ 目錄中。
下載 ZIP複製儲存庫並將技能檔案複製到您的專案中。
git clone https://github.com/microsoft/skills/tree/main/.github/skills/kql # Copy SKILL.md to your .claude/skills/ directory
複製





首頁
