

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 支援的 PPL 命令
<a name="supported-ppl"></a>

下表顯示 OpenSearch Dashboards 支援哪些 PPL 命令來查詢 CloudWatch Logs、Amazon S3 或 Security Lake，以及 CloudWatch Logs Insights 支援哪些命令。在查詢 CloudWatch Logs 時，CloudWatch Logs Insights 使用與 OpenSearch Dashboards 相同的 PPL 語法，而資料表同時稱為 CloudWatch Logs。

**注意**  
當您分析 OpenSearch Service 外部的資料時，命令的執行方式可能與 OpenSearch 索引不同。

**Topics**
+ [命令](#supported-ppl-commands)
+ [函數](#supported-ppl-functions)
+ [使用 OpenSearch PPL 的 CloudWatch Logs Insights 使用者其他資訊](#supported-ppl-for-cloudwatch-users)

## 命令
<a name="supported-ppl-commands"></a>


| PPL 命令 | Description | CloudWatch Logs | Amazon S3 | Security Lake | 範例 命令 | 
| --- | --- | --- | --- | --- | --- | 
| [field 命令](#supported-ppl-fields-command) | 顯示一組需要投影的欄位。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> fields field1, field2</pre>  | 
| [其中 命令](#supported-ppl-where-command) | 根據您指定的條件篩選資料。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> where field1="success"<br />| where field2 != "i -023fe0a90929d8822"<br />| fields field3, col4, col5, col6<br />| head 1000</pre>  | 
| [stats 命令](#supported-ppl-stats-command) | 執行彙總和計算。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>stats count(),<br />      count(`field1`),<br />      min(`field1`),<br />      max(`field1`),<br />      avg(`field1`)<br />by field2<br />| head 1000</pre>  | 
| [剖析命令](#supported-ppl-parse-command) | 從字串擷取規則表達式 (regex) 模式，並顯示擷取的模式。擷取的模式可以進一步用來建立新的欄位或篩選資料。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>parse `field1` ".*/(?<field2>[^/]+$)"<br />| where field2 = "requestId"<br />| fields field2, `field2`<br />| head 1000</pre>  | 
| [模式命令](#supported-ppl-patterns-command) | 從文字欄位擷取日誌模式，並將結果附加到搜尋結果。依模式分組日誌可讓您更輕鬆地從大量日誌資料彙總統計資料，以進行分析和故障診斷。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.png) 不支援 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>patterns new_field='no_numbers' pattern='[0-9]' message<br />| fields message, no_numbers</pre>  | 
| [sort 命令](#supported-ppl-sort-command) | 依欄位名稱排序顯示的結果。使用** sort -*FieldName*** 以遞減順序排序。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>stats count(),<br />      count(`field1`),<br />      min(`field1`) as field1Alias,<br />      max(`field1`),<br />      avg(`field1`)<br />by field2<br />| sort -field1Alias<br />| head 1000</pre>  | 
| [eval 命令](#supported-ppl-eval-command) | 修改或處理欄位的值，並將其存放在不同的欄位中。這有助於以數學方式修改資料欄、將字串函數套用至資料欄，或將日期函數套用至資料欄。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval field2 = `field1` * 2<br />| fields field1, field2<br />| head 20</pre>  | 
| [重新命名命令](#supported-ppl-rename-command) | 重新命名搜尋結果中的一個或多個欄位。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>rename field2 as field1<br />| fields field1</pre>  | 
| [head 命令](#supported-ppl-head-command) | 將顯示的查詢結果限制為前 N 列。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> fields `@message`<br />| head 20</pre>  | 
| [grok 命令](#supported-ppl-grok-command) | 根據規則表達式剖析具有 grok 模式的文字欄位，並將結果附加到搜尋結果。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> grok email '.+@%{HOSTNAME:host}'<br />| fields email</pre>  | 
| [top 命令](#supported-ppl-top-command) | 尋找欄位最常見的值。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> top 2 Field1 by Field2</pre>  | 
| [dedup 命令](#supported-ppl-dedup-command) | 根據您指定的欄位移除重複的項目。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>dedup field1<br />| fields field1, field2, field3</pre>  | 
| [join 命令](#supported-ppl-join-commands) | 將兩個資料集聯結在一起。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>source=customer<br />| join ON c_custkey = o_custkey orders<br />| head 10</pre>  | 
| [查詢命令](#supported-ppl-lookup-commands) | 新增或取代查詢索引 （維度表） 中的資料，以豐富您的搜尋資料。您可以使用維度資料表中的值來擴展索引的欄位，並在符合查詢條件時附加或取代值 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.png) 不支援 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>where orderType = 'Cancelled'<br />| lookup account_list, mkt_id AS mkt_code<br />  replace amount, account_name as name<br />| stats count(mkt_code), avg(amount)<br />  by name</pre>  | 
| [子查詢命令](#supported-ppl-subquery-commands) | 在 Piped Processing Language (PPL) 陳述式中執行複雜的巢狀查詢。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>where id in [<br />  subquery source=users<br />  | where user in [<br />    subquery source=actions<br />    | where action="login"<br />    | fields user<br />  ]<br />  | fields uid<br />]</pre>  | 
| [罕見命令](#supported-ppl-rare-command) | 尋找欄位清單中所有欄位頻率最低的值。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> rare Field1 by Field2</pre>  | 
| [趨勢線命令](#supported-ppl-trendline-commands) | 計算欄位的移動平均值。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> trendline sma(2, field1) as field1Alias</pre>  | 
| [eventstats 命令](#supported-ppl-eventstats-command) | 使用計算的摘要統計資料來豐富您的事件資料。它會分析事件中的指定欄位、運算各種統計指標，然後將這些結果做為新欄位附加到每個原始事件。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援 ( 除外`count()`) | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> eventstats sum(field1) by field2</pre>  | 
| [平面命令](#supported-ppl-flatten-command) | 扁平化欄位， 欄位必須為此類型： `struct<?,?> or array<struct<?,?>>` | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> source=table | flatten field1</pre>  | 
| [欄位摘要](#supported-ppl-field-summary-command) | 計算每個欄位的基本統計資料 （計數、相異計數、最小值、最大值、平均值、標準差和平均值）。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援 （每個查詢一個欄位） | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>where field1 != 200<br />| fieldsummary includefields=field1 nulls=true</pre>  | 
| [fillnull 命令](#supported-ppl-fillnull-command) | 使用您提供的值填入 null 欄位。它可用於一個或多個欄位。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>fields field1<br />| eval field2=field1<br />| fillnull value=0 field1</pre>  | 
| [expand 命令](#supported-ppl-expand-command) | 將包含多個值的欄位細分為不同的資料列，為指定欄位中的每個值建立新的資料列。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>expand employee<br />| stats max(salary) as max<br />  by state, company</pre>  | 
| [describe 命令](#supported-ppl-describe-command) | 取得資料表、結構描述和目錄結構和中繼資料的詳細資訊 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.png) 不支援 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre> describe schema.table</pre>  | 

## 函數
<a name="supported-ppl-functions"></a>


| PPL 函數 | Description | CloudWatch Logs | Amazon S3 | Security Lake | 範例 命令 | 
| --- | --- | --- | --- | --- | --- | 
| [PPL 字串函數](#supported-ppl-string-functions)<br />(`CONCAT`, `CONCAT_WS`, `LENGTH`, `LOWER`, `LTRIM`, `POSITION`, `REVERSE`, `RIGHT`, `RTRIM`, `SUBSTRING`, `TRIM`, `UPPER`) | PPL 中的內建函數，可以操作和轉換 PPL 查詢中的字串和文字資料。例如，轉換案例、合併字串、擷取部分和清除文字。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval col1Len = LENGTH(col1)<br />| fields col1Len</pre>  | 
| [PPL 日期和時間函數](#supported-ppl-date-time-functions)<br />(`DAY`, `DAYOFMONTH`, `DAY_OF_MONTH`,`DAYOFWEEK`, `DAY_OF_WEEK`, `DAYOFYEAR`, `DAY_OF_YEAR`, `DAYNAME`, `FROM_UNIXTIME`, `HOUR`, `HOUR_OF_DAY`, `LAST_DAY`, `LOCALTIMESTAMP`, `LOCALTIME`, `MAKE_DATE`, `MINUTE`, `MINUTE_OF_HOUR`, `MONTH`, `MONTHNAME`, `MONTH_OF_YEAR`, `NOW`, `QUARTER`, `SECOND`, `SECOND_OF_MINUTE`, `SUBDATE`, `SYSDATE`, `TIMESTAMP`, `UNIX_TIMESTAMP`, `WEEK`, `WEEKDAY`, `WEEK_OF_YEAR`, `DATE_ADD`, `DATE_SUB`, `TIMESTAMPADD`, `TIMESTAMPDIFF`, `UTC_TIMESTAMP`, `CURRENT_TIMEZONE`) | 用於處理和轉換 PPL 查詢中日期和時間戳記資料的內建函數。例如 **date\_add**、**date\_format**、**datediff** 和 **current\_date**。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval newDate = ADDDATE(DATE('2020-08-26'), 1)<br />| fields newDate</pre>  | 
| [PPL 條件函數](#supported-ppl-condition-functions)<br />(`EXISTS`, `IF`, `IFNULL`, `ISNOTNULL`, `ISNULL`, `NULLIF`) | 對多個資料列執行計算以產生單一摘要值的內建函數。例如，**總**和、**計數**、**平均值**、**最大值**和**最小值**。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval field2 = isnull(col1)<br />| fields field2, col1, field3  </pre>  | 
| [PPL 數學函數](#supported-ppl-math-functions)<br />(`ABS`, `ACOS`, `ASIN`, `ATAN`, `ATAN2`, `CEIL`, `CEILING`, `CONV`, `COS`, `COT`, `CRC32`, `DEGREES`, `E`, `EXP`, `FLOOR`, `LN`, `LOG`, `LOG2`, `LOG10`, `MOD`, `PI`. `POW`, `POWER`, `RADIANS`, `RAND`, `ROUND`, `SIGN`, `SIN`, `SQRT`, `CBRT`) | 用於在 PPL 查詢中執行數學計算和轉換的內建函數。例如：**abs** （絕對值）、**圓 **（圓數）、**sqrt** （平方根）、**pow** （功率計算） 和 **ceil** （四捨五入至最接近的整數）。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval field2 = ACOS(col1)<br />| fields col1</pre>  | 
| [PPL 表達式](#supported-ppl-expressions)<br />（算術運算子 (`+`、、`*`)`-`、述詞運算子 (`>. <`、`IN)`) | 表達式的內建函數，特別是值表達式，會傳回純量值。表達式有不同的類型和形式。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>where age > (25 + 5)<br />| fields age  </pre>  | 
| [PPL IP 地址函數](#supported-ppl-ip-address-functions)<br />(`CIDRMATCH`) | 用於處理 CIDR 等 IP 地址的內建函數。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>where cidrmatch(ip, '***********/24')<br />| fields ip </pre>  | 
| [PPL JSON 函數](#supported-ppl-json-functions)<br />(`ARRAY_LENGTH`, `ARRAY_LENGTH`, `JSON`, `JSON_ARRAY`, `JSON_EXTRACT`, `JSON_KEYS`, `JSON_OBJECT`, `JSON_VALID`, `TO_JSON_STRING`) | 處理 JSON 的內建函數，包括陣列、擷取和驗證。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval `json_extract('{"a":"b"}', '$.a')` = json_extract('{"a":"b"}', '$a')</pre>  | 
| [PPL Lambda 函數](#supported-ppl-lambda-functions)<br />(`EXISTS`, `FILTER`, `REDUCE`, `TRANSFORM`) | 處理 JSON 的內建函數，包括陣列、擷取和驗證。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.png) 不支援 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval array = json_array(1, -1, 2),<br />     result = filter(array, x -> x > 0)<br />| fields result</pre>  | 
| [PPL 密碼編譯雜湊函數](#supported-ppl-cryptographic-functions)<br />(`MD5`, `SHA1`, `SHA2`) | 內建函數，可讓您產生唯一的資料指紋，可用於驗證、比較或作為更複雜安全通訊協定的一部分。 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 | ![](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.png) 支援的 |  <pre>eval `MD5('hello')` = MD5('hello')<br />| fields `MD5('hello')`</pre>  | 

## 使用 OpenSearch PPL 的 CloudWatch Logs Insights 使用者其他資訊
<a name="supported-ppl-for-cloudwatch-users"></a>

雖然 CloudWatch Logs Insights 支援大多數 OpenSearch PPL 命令和函數，但目前不支援某些命令和函數。例如，它目前不支援 PPL 中的查詢命令。自 2025 年 6 月 2 日起，CloudWatch Logs Insights 現在支援 PPL 中的 JOIN、子查詢、 Flatten、 Fillnull、Expand、Cidrmatch 和 JSON 函數。如需支援查詢命令和函數的完整清單，請參閱上表中的 Amazon CloudWatch Logs 欄。

### 查詢和配額範例
<a name="sample-queries"></a>

以下內容適用於查詢 CloudWatch 資料的 CloudWatch Logs Insights 使用者和 OpenSearch 使用者。

如需從 OpenSearch Service 查詢 CloudWatch Logs 時所套用限制的相關資訊，請參閱《Amazon [CloudWatch Logs 使用者指南》中的 CloudWatch Logs 配額](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html)。 Amazon CloudWatch 限制包括您可以查詢的 CloudWatch Log 群組數量、您可以執行的並行查詢上限、查詢執行時間上限，以及結果中傳回的資料列數目上限。無論您使用哪種語言查詢 CloudWatch Logs （即 OpenSearch PPL、SQL 和 Logs Insights QL)，這些限制都相同。

### PPL 命令
<a name="supported-ppl-commands-details"></a>

**Topics**
+ [comment](#supported-ppl-comment)
+ [相互關聯命令](#supported-ppl-correlation-commands)
+ [dedup 命令](#supported-ppl-dedup-command)
+ [describe 命令](#supported-ppl-describe-command)
+ [eval 命令](#supported-ppl-eval-command)
+ [eventstats 命令](#supported-ppl-eventstats-command)
+ [expand 命令](#supported-ppl-expand-commands)
+ [explain 命令](#supported-ppl-explain-command)
+ [fillnull 命令](#supported-ppl-fillnull-command)
+ [field 命令](#supported-ppl-fields-command)
+ [平面命令](#supported-ppl-flatten-command)
+ [grok 命令](#supported-ppl-grok-command)
+ [head 命令](#supported-ppl-head-command)
+ [join 命令](#supported-ppl-join-commands)
+ [查詢命令](#supported-ppl-lookup-commands)
+ [剖析命令](#supported-ppl-parse-command)
+ [模式命令](#supported-ppl-patterns-command)
+ [罕見命令](#supported-ppl-rare-command)
+ [重新命名命令](#supported-ppl-rename-command)
+ [搜尋命令](#supported-ppl-search-command)
+ [sort 命令](#supported-ppl-sort-command)
+ [stats 命令](#supported-ppl-stats-command)
+ [子查詢命令](#supported-ppl-subquery-commands)
+ [top 命令](#supported-ppl-top-command)
+ [趨勢線命令](#supported-ppl-trendline-commands)
+ [其中 命令](#supported-ppl-where-command)
+ [欄位摘要](#supported-ppl-field-summary-command)
+ [expand 命令](#supported-ppl-expand-command)
+ [PPL 函數](#supported-ppl-functions-details)

#### comment
<a name="supported-ppl-comment"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

PPL 同時支援行註解和區塊註解。系統不會評估評論文字。

**行註解**  
行註解以兩個斜線 // 開頭，並以新行結尾。

範例：

```
os> source=accounts | top gender // finds most common gender of all the accounts
fetched rows / total rows = 2/2
+----------+
| gender   |
|----------|
| M        |
| F        |
+----------+
```

**區塊註解**  
區塊註解開頭為斜線後接星號 \\\*，結尾為星號後接斜線 \*/。

範例：

```
os> source=accounts | dedup 2 gender /* dedup the document with gender field keep 2 duplication */ | fields account_number, gender
fetched rows / total rows = 3/3
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 6                | M        |
| 13               | F        |
+------------------+----------+
```

#### 相互關聯命令
<a name="supported-ppl-correlation-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

您可以根據常見的維度和時間範圍來關聯不同的資料來源。

當您處理來自共用相同時段但未正式同步之各種垂直的大量資料時，這種相互關聯至關重要。

透過根據時間範圍和類似維度來關聯這些不同的資料來源，您可以充實資料並發現寶貴的洞見。

**範例**  
可觀測性網域有三種不同的資料來源：
+ 日誌
+ 指標
+ 追蹤

這些資料來源可能會共用共同維度。若要從一個資料來源轉換到另一個資料來源，您需要正確關聯它們。使用語意命名慣例，您可以識別跨日誌、追蹤和指標的共用元素。

範例：

```
{
  "@timestamp": "2018-07-02T22:23:00.186Z",
  "aws": {
    "elb": {
      "backend": {
        "http": {
          "response": {
            "status_code": 500
          }
        },
        "ip": "********",
        "port": "80"
      },
      ...
     "target_port": [
        "10.0.0.1:80"
      ],
      "target_status_code": [
        "500"
      ],
      "traceId": "Root=1-58337262-36d228ad5d99923122bbe354",
      "type": "http"
    }
  },
  "cloud": {
    "provider": "aws"
  },
  "http": {
    "request": {
    ...
  },
  "communication": {
    "source": {
      "address": "**************",
      "ip": "**************",
      "port": 2817
    }
  },
  "traceId": "Root=1-58337262-36d228ad5d99923122bbe354"
}
```

此範例顯示來自位於 AWS 上之服務的 ELB 日誌 AWS。它會顯示狀態碼為 500 的後端 HTTP 回應，指出錯誤。這可能會觸發警示或成為您定期監控程序的一部分。您的下一個步驟是收集有關此事件的相關資料，以進行徹底的調查。

雖然您可能會想查詢與時間範圍相關的所有資料，但這種方法可能會令人不知所措。最終，您可能會得到太多的資訊，花更多時間篩選掉不相關的資料，而不是識別根本原因。

反之，您可以透過關聯來自不同來源的資料，來使用更有針對性的方法。您可以使用這些維度進行相互關聯：
+ **IP** - `"ip": "10.0.0.1" | "ip": "**************"`
+ **連接埠** - `"port": 2817 | "target_port": "10.0.0.1:80"`

假設您可以存取其他追蹤和指標索引，並且熟悉結構描述結構，您可以建立更精確的相互關聯查詢。

以下是追蹤索引文件的範例，其中包含您可能想要關聯的 HTTP 資訊：

```
{
  "traceId": "c1d985bd02e1dbb85b444011f19a1ecc",
  "spanId": "55a698828fe06a42",
  "traceState": [],
  "parentSpanId": "",
  "name": "mysql",
  "kind": "CLIENT",
  "@timestamp": "2021-11-13T20:20:39+00:00",
  "events": [
    {
      "@timestamp": "2021-03-25T17:21:03+00:00",
       ...
    }
  ],
  "links": [
    {
      "traceId": "c1d985bd02e1dbb85b444011f19a1ecc",
      "spanId": "55a698828fe06a42w2",
      },
      "droppedAttributesCount": 0
    }
  ],
  "resource": {
    "service@name": "database",
    "telemetry@sdk@name": "opentelemetry",
    "host@hostname": "ip-172-31-10-8.us-west-2.compute.internal"
  },
  "status": {
    ...
  },
  "attributes": {
    "http": {
      "user_agent": {
        "original": "Mozilla/5.0"
      },
      "network": {
         ...
        }
      },
      "request": {
         ...
        }
      },
      "response": {
        "status_code": "200",
        "body": {
          "size": 500
        }
      },
      "client": {
        "server": {
          "socket": {
            "address": "***********",
            "domain": "example.com",
            "port": 80
          },
          "address": "***********",
          "port": 80
        },
        "resend_count": 0,
        "url": {
          "full": "http://example.com"
        }
      },
      "server": {
        "route": "/index",
        "address": "***********",
        "port": 8080,
        "socket": {
         ...
        },
        "client": {
         ...
         }
        },
        "url": {
         ...
        }
      }
    }
  }
}
```

在此方法中，您可以看到`ip`與 elb 日誌建立關聯的 `traceId`和 http 的用戶端/伺服器，以更好地了解系統的行為和條件。

**新的相互關聯查詢命令**  
以下是允許此類調查的新命令：

```
source alb_logs, traces | where alb_logs.ip="10.0.0.1" AND alb_logs.cloud.provider="aws"| 
correlate exact fields(traceId, ip) scope(@timestamp, 1D) mapping(alb_logs.ip = traces.attributes.http.server.address, alb_logs.traceId = traces.traceId )
```

以下是命令的每個部分的功能：

1. `source alb_logs, traces` - 這會選取您要關聯的資料來源。

1. `where ip="10.0.0.1" AND cloud.provider="aws"` - 這會縮小搜尋範圍。

1. `correlate exact fields(traceId, ip)` - 這會通知系統根據下列欄位的完全相符項目來關聯資料：
   + `ip` 欄位具有明確的篩選條件，因此會用於所有資料來源的相互關聯。
   + `traceId` 欄位沒有明確的篩選條件，因此會比對所有資料來源的相同 traceIds。

欄位名稱表示相互關聯命令內函數的邏輯意義。實際聯結條件取決於您提供的映射陳述式。

術語`exact`表示相互關聯陳述式需要所有欄位相符，才能滿足查詢陳述式。

該術語`approximate`將嘗試在最佳案例案例中進行比對，並且不會拒絕具有部分比對的資料列。

**處理不同的欄位映射**  
如果相同的邏輯欄位 （例如 `ip`) 在資料來源中有不同的名稱，您需要提供路徑欄位的明確映射。若要解決此問題，您可以擴展相互關聯條件，以符合具有類似邏輯意義的不同欄位名稱。以下是您可以執行此操作的方式：

```
alb_logs.ip = traces.attributes.http.server.address, alb_logs.traceId = traces.traceId    
```

對於參與相互關聯聯結的每個欄位，您應該提供相關的映射陳述式，其中包含此相互關聯命令要聯結的所有資料表。

**範例**  
在此範例中，有 2 個來源： `alb_logs, traces`

有 2 個欄位： `traceId, ip`

有兩個映射陳述式： `alb_logs.ip = traces.attributes.http.server.address, alb_logs.traceId = traces.traceId`

**調整相互關聯時間範圍**  
若要簡化執行引擎 （驅動程式） 完成的工作，您可以新增範圍陳述式。這會明確指示聯結查詢應為此搜尋範圍的時間。

`scope(@timestamp, 1D)` i

在此範例中，搜尋範圍著重於每日，因此在同一天出現的相互關聯會分組在一起。這種範圍界定機制可簡化並允許更好地控制結果，從而根據您的需求實現增量搜尋解決方案。

**支援驅動程式**  
新的相互關聯命令實際上是「隱藏」聯結命令。因此，只有下列 PPL 驅動程式支援此命令。在這些驅動程式中，相互關聯命令會直接翻譯為適當的 Catalyst Join 邏輯計畫。

**範例**  
`source alb_logs, traces, metrics | where ip="10.0.0.1" AND cloud.provider="aws"| correlate exact on (ip, port) scope(@timestamp, 2018-07-02T22:23:00, 1 D)`

**邏輯計畫：**

```
'Project [*]
+- 'Join Inner, ('ip && 'port)
   :- 'Filter (('ip === "10.0.0.1" & 'cloud.provider === "aws") & inTimeScope('@timestamp, "2018-07-02T22:23:00", "1 D"))
      +- 'UnresolvedRelation [alb_logs]
   +- 'Join Inner, ('ip & 'port)
      :- 'Filter (('ip === "10.0.0.1" & 'cloud.provider === "aws") & inTimeScope('@timestamp, "2018-07-02T22:23:00", "1 D"))
         +- 'UnresolvedRelation [traces]
      +- 'Filter (('ip === "10.0.0.1" & 'cloud.provider === "aws") & inTimeScope('@timestamp, "2018-07-02T22:23:00", "1 D"))
         +- 'UnresolvedRelation [metrics]
```

觸媒引擎會根據最有效率的聯結順序來最佳化此查詢。

#### dedup 命令
<a name="supported-ppl-dedup-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `dedup`命令，根據指定的欄位從搜尋結果中移除相同的文件。

**語法**  
使用下列語法：

```
dedup [int] <field-list> [keepempty=<bool>] [consecutive=<bool>] 
```

**`int`**
+ 選用。
+ 當您指定 <int> 時， `dedup`命令會保留每個組合的多個事件。<int> 的數字必須大於 0。如果您未指定數字，只會保留第一個發生的事件。所有其他重複項目都會從結果中移除。
+ 預設：1

**`keepempty`**
+ 選用。
+ 如果為 true， 會保留欄位清單中任何欄位具有 NULL 值或為 MISSING 的文件。
+ 預設：false

**`consecutive`**
+ 選用。
+ 如果為 true， 只會移除具有連續重複值組合的事件。
+ 預設：false

**`field-list`**
+ 強制性。
+ 欄位的逗號分隔清單。至少需要一個欄位。

**範例 1：除以一個欄位**  
此範例說明如何使用性別欄位對文件進行刪除。

PPL 查詢：

```
os> source=accounts | dedup gender | fields account_number, gender;
fetched rows / total rows = 2/2
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 13               | F        |
+------------------+----------+
```

**範例 2：保留 2 個重複的文件**  
此範例示範如何使用性別欄位刪除文件，並保留兩個重複項目。

PPL 查詢：

```
os> source=accounts | dedup 2 gender | fields account_number, gender;
fetched rows / total rows = 3/3
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 6                | M        |
| 13               | F        |
+------------------+----------+
```

**範例 3：預設保留或忽略空白欄位**  
此範例示範如何透過保留 null 值欄位來刪除文件。

PPL 查詢：

```
os> source=accounts | dedup email keepempty=true | fields account_number, email;
fetched rows / total rows = 4/4
+------------------+-----------------------+
| account_number   | email                 |
+------------------+-----------------------+
| 1                | john_doe@example.com  |
| 6                | jane_doe@example.com  |
| 13               | null                  |
| 18               | juan_li@example.com   |
+------------------+-----------------------+
```

此範例示範如何忽略空值欄位，對文件進行資料刪除。

PPL 查詢：

```
os> source=accounts | dedup email | fields account_number, email;
fetched rows / total rows = 3/3
+------------------+-----------------------+
| account_number   | email                 |
+------------------+-----------------------+
| 1                | john_doe@example.com  |
| 6                | jane_doe@example.com  |
| 18               | juan_li@example.com   |
+------------------+-----------------------+
```

**範例 4：連續文件中的 Dedup**  
此範例示範如何在連續文件中進行資料刪除。

PPL 查詢：

```
os> source=accounts | dedup gender consecutive=true | fields account_number, gender;
fetched rows / total rows = 3/3
+------------------+----------+
| account_number   | gender   |
+------------------+----------+
| 1                | M        |
| 13               | F        |
| 18               | M        |
+------------------+----------+
```

**其他範例**
+ `source = table | dedup a | fields a,b,c`
+ `source = table | dedup a,b | fields a,b,c`
+ `source = table | dedup a keepempty=true | fields a,b,c`
+ `source = table | dedup a,b keepempty=true | fields a,b,c`
+ `source = table | dedup 1 a | fields a,b,c`
+ `source = table | dedup 1 a,b | fields a,b,c`
+ `source = table | dedup 1 a keepempty=true | fields a,b,c`
+ `source = table | dedup 1 a,b keepempty=true | fields a,b,c`
+ `source = table | dedup 2 a | fields a,b,c`
+ `source = table | dedup 2 a,b | fields a,b,c`
+ `source = table | dedup 2 a keepempty=true | fields a,b,c`
+ `source = table | dedup 2 a,b keepempty=true | fields a,b,c`
+ `source = table | dedup 1 a consecutive=true| fields a,b,c` （不支援連續重複資料刪除）

**限制**
+ 針對 `| dedup 2 a, b keepempty=false`

  ```
  DataFrameDropColumns('_row_number_)
  +- Filter ('_row_number_ <= 2) // allowed duplication = 2
     +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
         +- Filter (isnotnull('a) AND isnotnull('b)) // keepempty=false
            +- Project
               +- UnresolvedRelation
  ```
+ 針對 `| dedup 2 a, b keepempty=true`

  ```
  Union
  :- DataFrameDropColumns('_row_number_)
  :  +- Filter ('_row_number_ <= 2)
  :     +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
  :        +- Filter (isnotnull('a) AND isnotnull('b))
  :           +- Project
  :              +- UnresolvedRelation
  +- Filter (isnull('a) OR isnull('b))
     +- Project
        +- UnresolvedRelation
  ```

#### describe 命令
<a name="supported-ppl-describe-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `describe`命令以取得資料表、結構描述和目錄結構和中繼資料的詳細資訊。以下是 `describe`命令的各種範例和使用案例。

**描述**
+ `describe table` 此命令等於 `DESCRIBE EXTENDED table` SQL 命令
+ `describe schema.table`
+ `describe schema.`table``
+ `describe catalog.schema.table`
+ `describe catalog.schema.`table``
+ `describe `catalog`.`schema`.`table``

#### eval 命令
<a name="supported-ppl-eval-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`eval` 命令會評估表達式，並將結果附加到搜尋結果。

**語法**  
使用下列語法：

```
eval <field>=<expression> ["," <field>=<expression> ]...    
```
+ `field`：強制性。如果欄位名稱不存在，則會新增新的欄位。如果欄位名稱已存在，則會覆寫它。
+  `expression`：強制性。系統支援的任何表達式。

**範例 1：建立新欄位**  
此範例說明如何為每個文件建立新`doubleAge`欄位。新的 `doubleAge`是年齡乘以 2 的評估結果。

PPL 查詢：

```
os> source=accounts | eval doubleAge = age * 2 | fields age, doubleAge ;
fetched rows / total rows = 4/4
+-------+-------------+
| age   | doubleAge   |
|-------+-------------|
| 32    | 64          |
| 36    | 72          |
| 28    | 56          |
| 33    | 66          |
+-------+-------------+
```

**範例 2：覆寫現有欄位**  
此範例顯示如何以年齡加 1 覆寫現有的年齡欄位。

PPL 查詢：

```
os> source=accounts | eval age = age + 1 | fields age ;
fetched rows / total rows = 4/4
+-------+
| age   |
|-------|
| 33    |
| 37    |
| 29    |
| 34    |
+-------+
```

**範例 3：使用 eval 中定義的欄位建立新的欄位**  
此範例說明如何使用 eval 命令中定義的`ddAge`欄位建立新的欄位。新欄位`ddAge`是 的評估結果`doubleAge`乘以 2，其中 `doubleAge` 是在 eval 命令中定義的。

PPL 查詢：

```
os> source=accounts | eval doubleAge = age * 2, ddAge = doubleAge * 2 | fields age, doubleAge, ddAge ;
fetched rows / total rows = 4/4
+-------+-------------+---------+
| age   | doubleAge   | ddAge   |
|-------+-------------+---------|
| 32    | 64          | 128     |
| 36    | 72          | 144     |
| 28    | 56          | 112     |
| 33    | 66          | 132     |
+-------+-------------+---------+
```

假設：`a`、`b`、 `c`是 中的現有欄位 `table`

**其他範例**
+ `source = table | eval f = 1 | fields a,b,c,f`
+ `source = table | eval f = 1` （輸出 a、b、c、f 欄位）
+ `source = table | eval n = now() | eval t = unix_timestamp(a) | fields n,t`
+ `source = table | eval f = a | where f > 1 | sort f | fields a,b,c | head 5`
+ `source = table | eval f = a * 2 | eval h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = b | stats avg(f) by h`
+ `source = table | eval f = ispresent(a)`
+ `source = table | eval r = coalesce(a, b, c) | fields r`
+ `source = table | eval e = isempty(a) | fields e`
+ `source = table | eval e = isblank(a) | fields e`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one', a = 2, 'two', a = 3, 'three', a = 4, 'four', a = 5, 'five', a = 6, 'six', a = 7, 'se7en', a = 8, 'eight', a = 9, 'nine')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else 'unknown')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else concat(a, ' is an incorrect binary digit'))`
+ `source = table | eval f = a in ('foo', 'bar') | fields f`
+ `source = table | eval f = a not in ('foo', 'bar') | fields f`

**評估與案例範例：**  


```
source = table | eval e = eval status_category =
case(a >= 200 AND a < 300, 'Success',
a >= 300 AND a < 400, 'Redirection',
a >= 400 AND a < 500, 'Client Error',
a >= 500, 'Server Error'
else 'Unknown')
```

**使用另一個案例評估範例：**  


假設：`a`、`b`、 `c`是 中的現有欄位 `table`

**其他範例**
+ `source = table | eval f = 1 | fields a,b,c,f`
+ `source = table | eval f = 1` （輸出 a、b、c、f 欄位）
+ `source = table | eval n = now() | eval t = unix_timestamp(a) | fields n,t`
+ `source = table | eval f = a | where f > 1 | sort f | fields a,b,c | head 5`
+ `source = table | eval f = a * 2 | eval h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = b | stats avg(f) by h`
+ `source = table | eval f = ispresent(a)`
+ `source = table | eval r = coalesce(a, b, c) | fields r`
+ `source = table | eval e = isempty(a) | fields e`
+ `source = table | eval e = isblank(a) | fields e`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one', a = 2, 'two', a = 3, 'three', a = 4, 'four', a = 5, 'five', a = 6, 'six', a = 7, 'se7en', a = 8, 'eight', a = 9, 'nine')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else 'unknown')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else concat(a, ' is an incorrect binary digit'))`
+ `source = table | eval f = a in ('foo', 'bar') | fields f`
+ `source = table | eval f = a not in ('foo', 'bar') | fields f`

**評估與案例範例：**  


```
source = table | eval e = eval status_category =
case(a >= 200 AND a < 300, 'Success',
a >= 300 AND a < 400, 'Redirection',
a >= 400 AND a < 500, 'Client Error',
a >= 500, 'Server Error'
else 'Unknown')
```

**使用另一個案例評估範例：**  


```
source = table |  where ispresent(a) |
eval status_category =
 case(a >= 200 AND a < 300, 'Success',
  a >= 300 AND a < 400, 'Redirection',
  a >= 400 AND a < 500, 'Client Error',
  a >= 500, 'Server Error'
  else 'Incorrect HTTP status code'
 )
 | stats count() by status_category
```

**限制**
+ 不支援覆寫現有欄位。嘗試執行此動作的查詢會擲回例外狀況，並顯示「參考「a」不明確」訊息。

  ```
  - `source = table | eval a = 10 | fields a,b,c`
  - `source = table | eval a = a * 2 | stats avg(a)`
  - `source = table | eval a = abs(a) | where a > 0`
  - `source = table | eval a = signum(a) | where a < 0`
  ```

#### eventstats 命令
<a name="supported-ppl-eventstats-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `eventstats`命令，透過計算的摘要統計資料來豐富您的事件資料。其運作方式是分析事件中的指定欄位、計算各種統計指標，然後將這些結果做為新欄位附加至每個原始事件。

**eventstats 的關鍵層面**

1. 它會在整個結果集或在定義的群組中執行計算。

1. 原始事件保持不變，新增新欄位以包含統計結果。

1. 命令對於比較分析、識別極端值或為個別事件提供額外的內容特別有用。

**統計資料和 eventstats 之間的差異**  
`stats` 和 `eventstats`命令都用於計算統計資料，但它們的操作方式和產生的內容有一些關鍵差異。

**輸出格式**
+ `stats`：產生只有計算統計資料的摘要資料表。
+ `eventstats`：將計算的統計資料新增為現有事件的新欄位，保留原始資料。

**事件保留**
+ `stats`：將結果設定為僅統計摘要，捨棄個別事件。
+ `eventstats`：保留所有原始事件，並使用計算的統計資料新增欄位。

**使用案例**
+ `stats`：最適合建立摘要報告或儀表板。通常用作總結結果的最終命令。
+ `eventstats`：當您需要以統計內容豐富事件以進行進一步分析或篩選時很有用。可用於搜尋中，以新增可用於後續命令的統計資料。

**語法**  
使用下列語法：

```
eventstats <aggregation>... [by-clause]    
```

**聚合**
+ 強制性。
+ 彙總函數。
+ 彙總的引數必須是 欄位。

**依 -clause**
+ 選用。
+ 語法: `by [span-expression,] [field,]...`
+ 依子句可包含純量函數和彙總函數等欄位和表達式。您也可以使用跨度子句，將特定欄位分割為相等間隔的儲存貯體。eventstats 命令接著會根據這些跨度儲存貯體執行彙總。
+ 預設：如果您未依子句指定 ，則 eventstats 命令會彙總整個結果集。

**span-expression**
+ 選用，最多一個。
+ 語法: `span(field_expr, interval_expr)`
+ 間隔表達式的單位預設為自然單位。不過，對於日期和時間類型欄位，您需要在使用日期/時間單位時，在間隔表達式中指定單位。

  例如，若要將欄位分割`age`為儲存貯體 10 年，請使用 `span(age, 10)`。對於以時間為基礎的欄位，您可以使用 將`timestamp`欄位分割為每小時間隔`span(timestamp, 1h)`。


**可用的時間單位**  

| 跨度間隔單位 | 
| --- | 
| 毫秒 (ms) | 
| 秒 （秒） | 
| 分鐘 (m、區分大小寫） | 
| 小時 (h) | 
| 天 (d) | 
| 週 (w) | 
| 月 (M、區分大小寫） | 
| 季度 (q) | 
| 年 (y) | 

**彙總函數**  


**`COUNT`**  
`COUNT` 會傳回 SELECT 陳述式所擷取資料列中的 expr 數量計數。

對於 CloudWatch Logs 使用查詢，`COUNT`不支援 。

範例：

```
os> source=accounts | eventstats count();
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+--------------------+------------+--------------------------+--------+-------+---------+
| account_number | balance  | firstname | lastname | age | gender | address            | employer   | email                    | city   | state | count() |
+----------------+----------+-----------+----------+-----+--------+--------------------+------------+--------------------------+--------+-------+---------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane       | AnyCorp    | janedoe@anycorp.com      | Brogan | IL    | 4       |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street | AnyCompany | marymajor@anycompany.com | Dante  | TN    | 4       |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street     | AnyOrg     |                          | Nogal  | VA    | 4       |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court  |            | juanli@exampleorg.com    | Orick  | MD    | 4       |
+----------------+----------+-----------+----------+-----+--------+--------------------+------------+--------------------------+--------+-------+---------+
```

**`SUM`**  
`SUM(expr)` 傳回 expr 的總和。

範例：

```
os> source=accounts | eventstats sum(age) by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+--------------------------+--------+-------+--------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer   | email                    | city   | state | sum(age) by gender |
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+--------------------------+--------+-------+--------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp    | janedoe@anycorp.com      | Brogan | IL    | 101                |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | AnyCompany | marymajor@anycompany.com | Dante  | TN    | 101                |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg     |                          | Nogal  | VA    | 28                 |
| 18             | 4180     | Juan      | Li       | 33  | M      | 467 Example Court     |            | juanli@exampleorg.com    | Orick  | MD    | 101                |
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+--------------------------+--------+-------+--------------------+
```

**`AVG`**  
`AVG(expr)` 傳回 expr 的平均值。

範例：

```
os> source=accounts | eventstats avg(age) by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+---------------------------+--------+-------+--------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | avg(age) by gender |
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+---------------------------+--------+-------+--------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 33.67              |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 33.67              |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 28.00              |
| 18             | 4180     | Juan      | Li       | 33  | M      | 467 Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 33.67              |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------+
```

**MAX**  
`MAX(expr)` 傳回 expr 的最大值。

範例

```
os> source=accounts | eventstats max(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | max(age)  |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 36        |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 36        |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 36        |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 36        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
```

**MIN**  
`MIN(expr)` 傳回 expr 的最小值。

範例

```
os> source=accounts | eventstats min(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | min(age)  |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 28        |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 28        |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | *** Any Street        | AnyOrg      |                          | Nogal  | VA    | 28        |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 28        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
```

**STDDEV\_SAMP**  
`STDDEV_SAMP(expr)` 傳回 expr 的範例標準差。

範例

```
os> source=accounts | eventstats stddev_samp(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | stddev_samp(age)       |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 3.304037933599835      |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 3.304037933599835      |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 3.304037933599835      |
| 18             | 4180     | Juan      | Li       | 33  | M      | 467 Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 3.304037933599835      |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
```

**STDDEV\_POP**  
`STDDEV_POP(expr)` 傳回 expr 的母群體標準差。

範例

```
os> source=accounts | eventstats stddev_pop(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | stddev_pop(age)        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 2.****************     |
| 6              | 5686     | Mary      | Major    | 36  | M      | *** Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 2.****************     |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | *** Any Street        | AnyOrg      |                          | Nogal  | VA    | 2.****************     |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 2.****************     |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
```

**PERCENTILE 或 PERCENTILE\_APPROX**  
`PERCENTILE(expr, percent)` 或 以指定的百分比`PERCENTILE_APPROX(expr, percent)`傳回 expr 的近似百分位數值。

**百分比**
+ 數字必須是介於 0 到 100 之間的常數。

範例

```
os> source=accounts | eventstats percentile(age, 90) by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | percentile(age, 90) by gender  |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 36                             |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 36                             |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 28                             |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 36                             |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------------------+
```

**範例 1：依群組計算欄位的平均值、總和和計數**  
此範例顯示依性別計算所有帳戶群組的平均存留期、總存留期和事件計數。

```
os> source=accounts | eventstats avg(age) as avg_age, sum(age) as sum_age, count() as count by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+-----------+-------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | avg_age   | sum_age   | count |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+-----------+-------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 33.666667 | 101       | 3     |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 33.666667 | 101       | 3     |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 28.000000 | 28        | 1     |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 33.666667 | 101       | 3     |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+-----------+-------+
```

**範例 2：依跨度計算計數**  
此範例會取得間隔 10 年的存留期計數。

```
os> source=accounts | eventstats count(age) by span(age, 10) as age_span
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+----------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | age_span |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+----------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 3        |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 3        |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 1        |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 3        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+----------+
```

**範例 3：依性別和跨度計算計數**  
此範例會依 5 年的間隔取得年齡計數，並依性別分組。

```
os> source=accounts | eventstats count() as cnt by span(age, 5) as age_span, gender
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                     | city   | state | cnt |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com       | Brogan | IL    | 2   |
| 6              | 5686     | Mary      | Majo     | 36  | M      | 671 Example Street    | Any Company | hattiebond@anycompany.com | Dante  | TN    | 1   |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | *** Any Street        | AnyOrg      |                           | Nogal  | VA    | 1   |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com     | Orick  | MD    | 2   |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
```

**Usage**
+ `source = table | eventstats avg(a)`
+ `source = table | where a < 50 | eventstats avg(c)`
+ `source = table | eventstats max(c) by b`
+ `source = table | eventstats count(c) by b | head 5`
+ `source = table | eventstats distinct_count(c)`
+ `source = table | eventstats stddev_samp(c)`
+ `source = table | eventstats stddev_pop(c)`
+ `source = table | eventstats percentile(c, 90)`
+ `source = table | eventstats percentile_approx(c, 99)`

**包含跨度的彙總**  

+ `source = table | eventstats count(a) by span(a, 10) as a_span`
+ `source = table | eventstats sum(age) by span(age, 5) as age_span | head 2`
+ `source = table | eventstats avg(age) by span(age, 20) as age_span, country | sort - age_span | head 2`

**時間範圍的彙總 （翻轉視窗調整函數）**  

+ `source = table | eventstats sum(productsAmount) by span(transactionDate, 1d) as age_date | sort age_date`
+ `source = table | eventstats sum(productsAmount) by span(transactionDate, 1w) as age_date, productId`

**依多個層級彙總群組**  

+ `source = table | eventstats avg(age) as avg_state_age by country, state | eventstats avg(avg_state_age) as avg_country_age by country`
+ `source = table | eventstats avg(age) as avg_city_age by country, state, city | eval new_avg_city_age = avg_city_age - 1 | eventstats avg(new_avg_city_age) as avg_state_age by country, state | where avg_state_age > 18 | eventstats avg(avg_state_age) as avg_adult_country_age by country`

#### expand 命令
<a name="supported-ppl-expand-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `expand`命令來扁平化 類型的欄位：
+ `Array<Any>`
+ `Map<Any>`

**語法**  
使用下列語法：

```
expand <field> [As alias]
```

**field**
+ 要擴展 （分解） 的欄位。必須為支援的類型。

**別名**
+ 選用。要使用的名稱，而非原始欄位名稱。

**Usage**  
`expand` 命令會為指定陣列或映射欄位中的每個元素產生資料列，其中：
+ 陣列元素會成為個別的資料列。
+ 映射索引鍵/值對會分成不同的資料列，每個索引鍵/值都以資料列表示。
+ 提供別名時，展開的值會以別名表示，而非原始欄位名稱。
+ 這可以與其他命令搭配使用，例如 `stats`、 和 `eval`，`parse`以在擴展後操作或擷取資料。

**範例**
+ `source = table | expand employee | stats max(salary) as max by state, company`
+ `source = table | expand employee as worker | stats max(salary) as max by state, company`
+ `source = table | expand employee as worker | eval bonus = salary * 3 | fields worker, bonus`
+ `source = table | expand employee | parse description '(?<email>.+@.+)' | fields employee, email`
+ `source = table | eval array=json_array(1, 2, 3) | expand array as uid | fields name, occupation, uid`
+ `source = table | expand multi_valueA as multiA | expand multi_valueB as multiB`

#### explain 命令
<a name="supported-ppl-explain-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`explain` 命令可協助您了解查詢執行計劃，讓您能夠分析和最佳化查詢，以獲得更好的效能。此簡介提供 explain 命令的用途及其在查詢最佳化中重要性的簡要概觀。

**Comment**
+ `source=accounts | top gender // finds most common gender of all the accounts` （行註解）
+ `source=accounts | dedup 2 gender /* dedup the document with gender field keep 2 duplication */ | fields account_number, gender` （區塊註解）

**描述**
+ `describe table` 此命令等於 `DESCRIBE EXTENDED table` SQL 命令
+ `describe schema.table`
+ `describe schema.`table``
+ `describe catalog.schema.table`
+ `describe catalog.schema.`table``
+ `describe `catalog`.`schema`.`table``

**說明**
+ `explain simple | source = table | where a = 1 | fields a,b,c`
+ `explain extended | source = table`
+ `explain codegen | source = table | dedup a | fields a,b,c`
+ `explain cost | source = table | sort a | fields a,b,c`
+ `explain formatted | source = table | fields - a`
+ `explain simple | describe table`

**欄位**
+ `source = table`
+ `source = table | fields a,b,c`
+ `source = table | fields + a,b,c`
+ `source = table | fields - b,c`
+ `source = table | eval b1 = b | fields - b1,c`

**欄位摘要**
+ `source = t | fieldsummary includefields=status_code nulls=false`
+ `source = t | fieldsummary includefields= id, status_code, request_path nulls=true`
+ `source = t | where status_code != 200 | fieldsummary includefields= status_code nulls=true`

**巢狀欄位**
+ `source = catalog.schema.table1, catalog.schema.table2 | fields A.nested1, B.nested1`
+ `source = catalog.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields int_col, struct_col.field1.subfield, struct_col2.field1.subfield`
+ `source = catalog.schema.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields int_col, struct_col.field1.subfield, struct_col2.field1.subfield`

**篩選條件**
+ `source = table | where a = 1 | fields a,b,c`
+ `source = table | where a >= 1 | fields a,b,c`
+ `source = table | where a < 1 | fields a,b,c`
+ `source = table | where b != 'test' | fields a,b,c`
+ `source = table | where c = 'test' | fields a,b,c | head 3`
+ `source = table | where ispresent(b)`
+ `source = table | where isnull(coalesce(a, b)) | fields a,b,c | head 3`
+ `source = table | where isempty(a)`
+ `source = table | where isblank(a)`
+ `source = table | where case(length(a) > 6, 'True' else 'False') = 'True'`
+ `source = table | where a not in (1, 2, 3) | fields a,b,c`
+ `source = table | where a between 1 and 4` - 注意：這會傳回 >= 1 和 <= 4，即 【1， 4】
+ `source = table | where b not between '2024-09-10' and '2025-09-10'` - 注意：這會傳回 b >= '\*\*\*\*\*\*\*\*\*\*' 和 b <= '2025-09-10'
+ `source = table | where cidrmatch(ip, '***********/24')`
+ `source = table | where cidrmatch(ipv6, '2003:db8::/32')`
+ `source = table | trendline sma(2, temperature) as temp_trend`

**IP 相關查詢**
+ `source = table | where cidrmatch(ip, '**************')`
+ `source = table | where isV6 = false and isValid = true and cidrmatch(ipAddress, '**************')`
+ `source = table | where isV6 = true | eval inRange = case(cidrmatch(ipAddress, '2003:***::/32'), 'in' else 'out') | fields ip, inRange`

**複雜篩選條件**  


```
source = table | eval status_category =
case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
else 'Incorrect HTTP status code')
| where case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
else 'Incorrect HTTP status code'
) = 'Incorrect HTTP status code'
```

```
source = table
| eval factor = case(a > 15, a - 14, isnull(b), a - 7, a < 3, a + 1 else 1)
| where case(factor = 2, 'even', factor = 4, 'even', factor = 6, 'even', factor = 8, 'even' else 'odd') = 'even'
| stats count() by factor
```

**具有邏輯條件的篩選條件**
+ `source = table | where c = 'test' AND a = 1 | fields a,b,c`
+ `source = table | where c != 'test' OR a > 1 | fields a,b,c | head 1`
+ `source = table | where c = 'test' NOT a > 1 | fields a,b,c`

**評估**  
假設：`a`、`b`、 `c`是 中的現有欄位 `table`
+ `source = table | eval f = 1 | fields a,b,c,f`
+ `source = table | eval f = 1` （輸出 a、b、c、f 欄位）
+ `source = table | eval n = now() | eval t = unix_timestamp(a) | fields n,t`
+ `source = table | eval f = a | where f > 1 | sort f | fields a,b,c | head 5`
+ `source = table | eval f = a * 2 | eval h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = b | stats avg(f) by h`
+ `source = table | eval f = ispresent(a)`
+ `source = table | eval r = coalesce(a, b, c) | fields r`
+ `source = table | eval e = isempty(a) | fields e`
+ `source = table | eval e = isblank(a) | fields e`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one', a = 2, 'two', a = 3, 'three', a = 4, 'four', a = 5, 'five', a = 6, 'six', a = 7, 'se7en', a = 8, 'eight', a = 9, 'nine')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else 'unknown')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else concat(a, ' is an incorrect binary digit'))`
+ `source = table | eval digest = md5(fieldName) | fields digest`
+ `source = table | eval digest = sha1(fieldName) | fields digest`
+ `source = table | eval digest = sha2(fieldName,256) | fields digest`
+ `source = table | eval digest = sha2(fieldName,512) | fields digest`

#### fillnull 命令
<a name="supported-ppl-fillnull-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**Description**  
使用 `fillnull`命令將 Null 值取代為搜尋結果一或多個欄位中的指定值。

**語法**  
使用下列語法：

```
fillnull [with <null-replacement> in <nullable-field>["," <nullable-field>]] | [using <source-field> = <null-replacement> [","<source-field> = <null-replacement>]]
```
+ null-replacement：必要。用來取代 null 值的值。
+ nullable-field：必要。欄位參考。此欄位中的 null 值將取代為 null 取代中指定的值。

**範例 1：填入一個欄位**  
此範例示範如何在單一欄位上使用 fillnull：

```
os> source=logs | fields status_code | eval input=status_code | fillnull with 0 in status_code;
| input | status_code |
|-------|-------------|
| 403   | 403         |
| 403   | 403         |
| NULL  | 0           |
| NULL  | 0           |
| 200   | 200         |
| 404   | 404         |
| 500   | 500         |
| NULL  | 0           |
| 500   | 500         |
| 404   | 404         |
| 200   | 200         |
| 500   | 500         |
| NULL  | 0           |
| NULL  | 0           |
| 404   | 404         |
```

**範例 2：套用至多個欄位的 fillnull**  
此範例顯示套用至多個欄位的 fillnull。

```
os> source=logs | fields request_path, timestamp | eval input_request_path=request_path, input_timestamp = timestamp | fillnull with '???' in request_path, timestamp;
| input_request_path | input_timestamp       | request_path | timestamp              |
|------------------------------------------------------------------------------------|
| /contact           | NULL                  | /contact     | ???                    |
| /home              | NULL                  | /home        | ???                    |
| /about             | 2023-10-01 10:30:00   | /about       | 2023-10-01 10:30:00    |
| /home              | 2023-10-01 10:15:00   | /home        | 2023-10-01 10:15:00    |
| NULL               | 2023-10-01 10:20:00   | ???          | 2023-10-01 10:20:00    |
| NULL               | 2023-10-01 11:05:00   | ???          | 2023-10-01 11:05:00    |
| /about             | NULL                  | /about       | ???                    |
| /home              | 2023-10-01 10:00:00   | /home        | 2023-10-01 10:00:00    |
| /contact           | NULL                  | /contact     | ???                    |
| NULL               | 2023-10-01 10:05:00   | ???          | 2023-10-01 10:05:00    |
| NULL               | 2023-10-01 10:50:00   | ???          | 2023-10-01 10:50:00    |
| /services          | NULL                  | /services    | ???                    |
| /home              | 2023-10-01 10:45:00   | /home        | 2023-10-01 10:45:00    |
| /services          | 2023-10-01 11:00:00   | /services    | 2023-10-01 11:00:00    |
| NULL               | 2023-10-01 10:35:00   | ???          | 2023-10-01 10:35:00    |
```

**範例 3：將 fillnull 套用至具有各種 null 取代值的多個欄位。**  
此範例顯示 fillnull，其中包含用於取代 null 的各種值。
+ `/error` 在 `request_path` 欄位中
+ `1970-01-01 00:00:00` 在 `timestamp` 欄位中

```
os> source=logs | fields request_path, timestamp | eval input_request_path=request_path, input_timestamp = timestamp | fillnull using request_path = '/error', timestamp='1970-01-01 00:00:00';

| input_request_path | input_timestamp       | request_path | timestamp              |
|------------------------------------------------------------------------------------|
| /contact           | NULL                  | /contact     | 1970-01-01 00:00:00    |
| /home              | NULL                  | /home        | 1970-01-01 00:00:00    |
| /about             | 2023-10-01 10:30:00   | /about       | 2023-10-01 10:30:00    |
| /home              | 2023-10-01 10:15:00   | /home        | 2023-10-01 10:15:00    |
| NULL               | 2023-10-01 10:20:00   | /error       | 2023-10-01 10:20:00    |
| NULL               | 2023-10-01 11:05:00   | /error       | 2023-10-01 11:05:00    |
| /about             | NULL                  | /about       | 1970-01-01 00:00:00    |
| /home              | 2023-10-01 10:00:00   | /home        | 2023-10-01 10:00:00    |
| /contact           | NULL                  | /contact     | 1970-01-01 00:00:00    |
| NULL               | 2023-10-01 10:05:00   | /error       | 2023-10-01 10:05:00    |
| NULL               | 2023-10-01 10:50:00   | /error       | 2023-10-01 10:50:00    |
| /services          | NULL                  | /services    | 1970-01-01 00:00:00    |
| /home              | 2023-10-01 10:45:00   | /home        | 2023-10-01 10:45:00    |
| /services          | 2023-10-01 11:00:00   | /services    | 2023-10-01 11:00:00    |
| NULL               | 2023-10-01 10:35:00   | /error       | 2023-10-01 10:35:00    |
```

#### field 命令
<a name="supported-ppl-fields-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `fields`命令來保留或移除搜尋結果中的欄位。

**語法**  
使用下列語法：

```
field [+|-] <field-list> 
```
+ `index`：選用。

  如果使用加號 (＋)，則只會保留欄位清單中指定的欄位。

  如果使用減號 (-)，則會移除欄位清單中指定的所有欄位。

  *預設*：\+
+ `field list`：強制性。要保留或移除的欄位逗號分隔清單。

**範例 1：從結果中選取指定的欄位**  
此範例示範如何從搜尋結果中擷取 `firstname`、 `account_number`和 `lastname` 欄位。

PPL 查詢：

```
os> source=accounts | fields account_number, firstname, lastname;
fetched rows / total rows = 4/4
+------------------+-------------+------------+
| account_number   | firstname   | lastname   |
|------------------+-------------+------------|
| 1                | Jane        | Doe        |
| 6                | John        | Doe        |
| 13               | Jorge       | Souza      |
| 18               | Juan        | Li         |
+------------------+-------------+------------+
```

**範例 2：從結果中移除指定的欄位**  
此範例示範如何從搜尋結果中移除 `account_number` 欄位。

PPL 查詢：

```
os> source=accounts | fields account_number, firstname, lastname | fields - account_number ;
fetched rows / total rows = 4/4
+-------------+------------+
| firstname   | lastname   |
|-------------+------------|
| Jane        | Doe        |
| John        | Doe        |
| Jorge       | Souza      |
| Juan        | Li         |
+-------------+------------+
```

**其他範例**
+ `source = table`
+ `source = table | fields a,b,c`
+ `source = table | fields + a,b,c`
+ `source = table | fields - b,c`
+ `source = table | eval b1 = b | fields - b1,c`

巢狀欄位範例：

```
`source = catalog.schema.table1, catalog.schema.table2 | fields A.nested1, B.nested1`
`source = catalog.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields  int_col, struct_col.field1.subfield, struct_col2.field1.subfield`
`source = catalog.schema.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields  int_col, struct_col.field1.subfield, struct_col2.field1.subfield`
```

#### 平面命令
<a name="supported-ppl-flatten-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用平面命令來展開下列類型的欄位：
+ `struct<?,?>`
+ `array<struct<?,?>>`

**語法**  
使用下列語法：

```
flatten <field>
```
+ *欄位*：要扁平化的欄位。欄位必須為支援的類型。

**結構描述**


| col\_name | data\_type | 
| --- | --- | 
| \_time | string | 
| 橋接器 | array<struct<length：bigint，name：string>> | 
| 城市 | string | 
| coor | struct<alt：bigint，lat：double，long：double> | 
| 國家/地區 | string | 

**資料**  



| \_time | 橋接器 | 城市 | coor | 國家/地區 | 
| --- | --- | --- | --- | --- | 
| 2024-09-13T12：00：00 | 【{801， Tower Bridge}， {928， London Bridge}】 | 倫敦 | {35、51.5074、-0.1278} | 英國 | 
| 2024-09-13T12：00：00 | 【{232， Pont Neuf}， {160， Pont Alexandre III}】 | 巴黎 | {35、48.8566、2.3522} | 法國 | 
| 2024-09-13T12：00：00 | 【{48， Rialto Bridge}， {11， Bridge of Sighs}】 | 維尼斯 | {2， 45.4408， 12.3155} | 義大利 | 
| 2024-09-13T12：00：00 | 【{\*\*\*、Charles Bridge}、{343、Legion Bridge}】 | 布拉格 | {200、50.0755、14.4378} | 捷克 | 
| 2024-09-13T12：00：00 | 【{375， Chain Bridge}， {333， Liberty Bridge}】 | 布達佩斯 | {96、47.4979、19.0402} | 匈牙利 | 
| 1990-09-13T12：00：00 | NULL | 華沙 | NULL | 波蘭 | 

**範例 1：平面化結構**  
此範例示範如何扁平化結構欄位。

PPL 查詢：

```
source=table | flatten coor
```


| \_time | 橋接器 | 城市 | 國家/地區 | alt | lat | long | 
| --- | --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12：00：00 | 【{801， Tower Bridge}， {928， London Bridge}】 | 倫敦 | 英國 | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12：00：00 | 【{232， Pont Neuf}， {160， Pont Alexandre III}】 | 巴黎 | 法國 | 35 | 48.8566 | 2.3522 | 
| 2024-09-13T12：00：00 | 【{48， Rialto Bridge}， {11， Bridge of Sighs}】 | 維尼斯 | 義大利 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12：00：00 | 【{516， Charles Bridge}， {343， Legion Bridge}】 | 布拉格 | 捷克 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12：00：00 | 【{375， Chain Bridge}， {333， Liberty Bridge}】 | 布達佩斯 | 匈牙利 | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12：00：00 | NULL | 華沙 | 波蘭 | NULL | NULL | NULL | 

**範例 2：平面陣列**  
此範例示範如何平面化結構欄位的陣列。

PPL 查詢：

```
source=table | flatten bridges
```


| \_time | 城市 | coor | 國家/地區 | length | name | 
| --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12：00：00 | 倫敦 | {35、51.5074、-0.1278} | 英國 | 801 | 塔橋 | 
| 2024-09-13T12：00：00 | 倫敦 | {35、51.5074、-0.1278} | 英國 | 928 | 倫敦大橋 | 
| 2024-09-13T12：00：00 | 巴黎 | {35、48.8566、2.3522} | 法國 | 232 | Pont Neuf | 
| 2024-09-13T12：00：00 | 巴黎 | {35、48.8566、2.3522} | 法國 | 160 | Pont Alexandre III | 
| 2024-09-13T12：00：00 | 維尼斯 | {2， 45.4408， 12.3155} | 義大利 | 48 | Rialto 橋接器 | 
| 2024-09-13T12：00：00 | 維尼斯 | {2， 45.4408， 12.3155} | 義大利 | 11 | 嘆號的橋接 | 
| 2024-09-13T12：00：00 | 布拉格 | {200、50.0755、14.4378} | 捷克 | 516 | 查爾斯大橋 | 
| 2024-09-13T12：00：00 | 布拉格 | {200、50.0755、14.4378} | 捷克 | 343 | Legion 橋接器 | 
| 2024-09-13T12：00：00 | 布達佩斯 | {96、47.4979、19.0402} | 匈牙利 | 375 | Chain Bridge | 
| 2024-09-13T12：00：00 | 布達佩斯 | {96、47.4979、19.0402} | 匈牙利 | 333 | 自由橋 | 
| 1990-09-13T12：00：00 | 華沙 | NULL | 波蘭 | NULL | NULL | 

**範例 3：平面化陣列和結構**  
此範例示範如何扁平化多個欄位。

PPL 查詢：

```
source=table | flatten bridges | flatten coor
```


| \_time | 城市 | 國家/地區 | length | name | alt | lat | long | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12：00：00 | 倫敦 | 英國 | 801 | 塔橋 | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12：00：00 | 倫敦 | 英國 | 928 | 倫敦大橋 | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12：00：00 | 巴黎 | 法國 | 232 | Pont Neuf | 35 | 48.8566 | 2.3522 | 
| 2024-09-13T12：00：00 | 巴黎 | 法國 | 160 | Pont Alexandre III | 35 | 48.8566 | 2.3522 | 
| 2024-09-13T12：00：00 | 維尼斯 | 義大利 | 48 | Rialto 橋接器 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12：00：00 | 維尼斯 | 義大利 | 11 | 嘆號的橋接 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12：00：00 | 布拉格 | 捷克 | 516 | 查爾斯大橋 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12：00：00 | 布拉格 | 捷克 | 343 | Legion 橋接器 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12：00：00 | 布達佩斯 | 匈牙利 | 375 | Chain Bridge | 96 | 47.4979 | 19.0402 | 
| 2024-09-13T12：00：00 | 布達佩斯 | 匈牙利 | 333 | 自由橋 | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12：00：00 | 華沙 | 波蘭 | NULL | NULL | NULL | NULL | NULL | 

#### grok 命令
<a name="supported-ppl-grok-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`grok` 命令會剖析具有 grok 模式的文字欄位，並將結果附加至搜尋結果。

**語法**  
使用下列語法：

```
grok <field> <pattern>
```

**field**
+ 強制性。
+ 欄位必須是文字欄位。

**pattern**
+ 強制性。
+ 用來從指定文字欄位擷取新欄位的 grok 模式。
+ 如果新的欄位名稱已存在，則會取代原始欄位。

**Grok 模式**  
grok 模式用於比對每個文件的文字欄位，以擷取新欄位。

**範例 1：建立新欄位**  
此範例示範如何`host`為每個文件建立新欄位。 `host`將是 `email` `@`欄位中 之後的主機名稱。剖析 null 欄位會傳回空字串。

```
os> source=accounts | grok email '.+@%{HOSTNAME:host}' | fields email, host ;
fetched rows / total rows = 4/4
+-------------------------+-------------+
| email                   | host        |
|-------------------------+-------------|
| jane_doe@example.com    | example.com |
| arnav_desai@example.net | example.net |
| null                    |             |
| juan_li@example.org     | example.org |
+-------------------------+-------------+
```

**範例 2：覆寫現有欄位**  
此範例示範如何在移除街道號碼的情況下覆寫現有`address`欄位。

```
os> source=accounts | grok address '%{NUMBER} %{GREEDYDATA:address}' | fields address ;
fetched rows / total rows = 4/4
+------------------+
| address          |
|------------------|
| Example Lane     |
| Any Street       |
| Main Street      |
| Example Court    |
+------------------+
```

**範例 3：使用 grok 剖析日誌**  
此範例示範如何使用 grok 剖析原始日誌。

```
os> source=apache | grok message '%{COMMONAPACHELOG}' | fields COMMONAPACHELOG, timestamp, response, bytes ;
fetched rows / total rows = 4/4
+-----------------------------------------------------------------------------------------------------------------------------+----------------------------+------------+---------+
| COMMONAPACHELOG                                                                                                             | timestamp                  | response   | bytes   |
|-----------------------------------------------------------------------------------------------------------------------------+----------------------------+------------+---------|
| 177.95.8.74 - upton5450 [28/Sep/2022:10:15:57 -0700] "HEAD /e-business/mindshare HTTP/1.0" 404 19927                        | 28/Sep/2022:10:15:57 -0700 | 404        | 19927   |
| 127.45.152.6 - pouros8756 [28/Sep/2022:10:15:57 -0700] "GET /architectures/convergence/niches/mindshare HTTP/1.0" 100 28722 | 28/Sep/2022:10:15:57 -0700 | 100        | 28722   |
| *************** - - [28/Sep/2022:10:15:57 -0700] "PATCH /strategize/out-of-the-box HTTP/1.0" 401 27439                      | 28/Sep/2022:10:15:57 -0700 | 401        | 27439   |
| ************** - - [28/Sep/2022:10:15:57 -0700] "POST /users HTTP/1.1" 301 9481                                             | 28/Sep/2022:10:15:57 -0700 | 301        | 9481    |
+-----------------------------------------------------------------------------------------------------------------------------+----------------------------+------------+---------+
```

**限制**  
grok 命令具有與剖析命令相同的限制。

#### head 命令
<a name="supported-ppl-head-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `head`命令，在搜尋順序的選擇性位移之後，傳回指定結果的前 N 個數目。

**語法**  
使用下列語法：

```
head [<size>] [from <offset>]
```

**<size>**
+ 選用整數。
+ 要傳回的結果數量。
+ 預設：10

**<offset>**
+ 選用 後的整數`from`。
+ 要略過的結果數目。
+ 預設：0

**範例 1：取得前 10 個結果**  
此範例示範如何從帳戶索引擷取最多 10 個結果。

PPL 查詢：

```
os> source=accounts | fields firstname, age | head;
fetched rows / total rows = 4/4
+-------------+-------+
| firstname   | age   |
|-------------+-------|
| Jane        | 32    |
| John        | 36    |
| Jorge       | 28    |
| Juan        | 33    |
+-------------+-------+
```

**範例 2：取得第一個 N 結果**  
此範例顯示帳戶索引的第一個 N 個結果。

PPL 查詢：

```
os> source=accounts | fields firstname, age | head 3;
fetched rows / total rows = 3/3
+-------------+-------+
| firstname   | age   |
|-------------+-------|
| Jane        | 32    |
| John        | 36    |
| Jorge       | 28    |
+-------------+-------+
```

**範例 3：偏移 M 後取得第一個 N 結果**  
此範例示範如何在從帳戶索引略過 M 結果之後擷取第一個 N 結果。

PPL 查詢：

```
os> source=accounts | fields firstname, age | head 3 from 1;
fetched rows / total rows = 3/3
+-------------+-------+
| firstname   | age   |
|-------------+-------|
| John        | 36    |
| Jorge       | 28    |
| Juan        | 33    |
+-------------+-------+
```

#### join 命令
<a name="supported-ppl-join-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

聯結命令可讓您根據常見欄位結合來自多個來源的資料，讓您執行複雜的分析，並從分散式資料集取得更深入的洞見

**結構描述**  
至少有兩個索引，`otel-v1-apm-span-*`（大型） 和 `otel-v1-apm-service-map`（小型）。

索引的相關欄位：

**`otel-v1-apm-span-*`**
+ traceId - 追蹤的唯一識別符。來自相同追蹤的所有範圍都會共用相同的 traceId。
+ spanId - 追蹤內跨度的唯一識別符，會在建立跨度時指派。
+ parentSpanId - 此跨度父範圍的 spanId。如果這是根跨度，則此欄位必須為空白。
+ durationInNanos - startTime 和 endTime 之間的差異。（以 UI `latency`為單位）
+ serviceName - 跨度來源的資源。
+ traceGroup - 追蹤根範圍的名稱。

**`otel-v1-apm-service-map`**
+ serviceName - 發出跨度的服務名稱。
+ destination.domain - 此用戶端所呼叫服務的 serviceName。
+ destination.resource - 此用戶端呼叫的範圍名稱 (API、操作等）。
+ target.domain - 用戶端呼叫之服務的 serviceName。
+ target.resource - 用戶端呼叫的範圍名稱 (API、操作等）。
+ traceGroupName - 啟動請求鏈的頂層跨度名稱。

**需求**  
**join** 支援計算下列項目：

對於每個服務，聯結服務映射索引上的跨度索引，以計算不同類型的篩選條件下的指標。

當依`order`服務的追蹤群組篩選時`client_cancel_order`，此範例查詢會計算延遲。

```
SELECT avg(durationInNanos)
FROM `otel-v1-apm-span-000001` t1
WHERE t1.serviceName = `order`
  AND ((t1.name in
          (SELECT target.resource
           FROM `otel-v1-apm-service-map`
           WHERE serviceName = `order`
             AND traceGroupName = `client_cancel_order`)
        AND t1.parentSpanId != NULL)
       OR (t1.parentSpanId = NULL
           AND t1.name = `client_cancel_order`))
  AND t1.traceId in
    (SELECT traceId
     FROM `otel-v1-apm-span-000001`
     WHERE serviceName = `order`)
```

**遷移至 PPL**  
join 命令的語法

```
SEARCH source=<left-table>
| <other piped command>
| [joinType] JOIN
    [leftAlias]
    ON joinCriteria
    <right-table>
| <other piped command>
```

**重寫**  


```
SEARCH source=otel-v1-apm-span-000001
| WHERE serviceName = 'order'
| JOIN left=t1 right=t2
    ON t1.traceId = t2.traceId AND t2.serviceName = 'order'
    otel-v1-apm-span-000001 -- self inner join
| EVAL s_name = t1.name -- rename to avoid ambiguous
| EVAL s_parentSpanId = t1.parentSpanId -- RENAME command would be better when it is supported
| EVAL s_durationInNanos = t1.durationInNanos 
| FIELDS s_name, s_parentSpanId, s_durationInNanos -- reduce colunms in join
| LEFT JOIN left=s1 right=t3
    ON s_name = t3.target.resource AND t3.serviceName = 'order' AND t3.traceGroupName = 'client_cancel_order'
    otel-v1-apm-service-map
| WHERE (s_parentSpanId IS NOT NULL OR (s_parentSpanId IS NULL AND s_name = 'client_cancel_order'))
| STATS avg(s_durationInNanos) -- no need to add alias if there is no ambiguous
```

**joinType**
+ 語法: `INNER | LEFT OUTER | CROSS`
+ 選用
+ 要執行的聯結類型。`INNER` 如果未指定，則預設為 。

**leftAlias**
+ 語法: `left = <leftAlias>`
+ 選用
+ 要與左側聯結端搭配使用的子查詢別名，以避免不明確命名。

**joinCriteria**
+ 語法: `<expression>`
+ 必要
+ 語法以 開頭`ON`。它可以是任何比較表達式。一般而言，聯結條件看起來像 `<leftAlias>.<leftField>=<rightAlias>.<rightField>`。

  例如：`l.id = r.id`。如果聯結條件包含多個條件，您可以在每個比較表達式之間指定 `AND`和 `OR`運算子。例如 `l.id = r.id AND l.email = r.email AND (r.age > 65 OR r.age < 18)`。

**更多 範例**  
從 SQL 查詢遷移 (TPC-H Q13)：

```
SELECT c_count, COUNT(*) AS custdist
FROM
  ( SELECT c_custkey, COUNT(o_orderkey) c_count
    FROM customer LEFT OUTER JOIN orders ON c_custkey = o_custkey
        AND o_comment NOT LIKE '%unusual%packages%'
    GROUP BY c_custkey
  ) AS c_orders
GROUP BY c_count
ORDER BY custdist DESC, c_count DESC;
```

由 PPL 聯結查詢重寫：

```
SEARCH source=customer
| FIELDS c_custkey
| LEFT OUTER JOIN
    ON c_custkey = o_custkey AND o_comment NOT LIKE '%unusual%packages%'
    orders
| STATS count(o_orderkey) AS c_count BY c_custkey
| STATS count() AS custdist BY c_count
| SORT - custdist, - c_count
```

限制：在右側聯結中不支援子搜尋。

如果支援子搜尋，您可以重寫上述 PPL 查詢，如下所示：

```
SEARCH source=customer
| FIELDS c_custkey
| LEFT OUTER JOIN
   ON c_custkey = o_custkey
   [
      SEARCH source=orders
      | WHERE o_comment NOT LIKE '%unusual%packages%'
      | FIELDS o_orderkey, o_custkey
   ]
| STATS count(o_orderkey) AS c_count BY c_custkey
| STATS count() AS custdist BY c_count
| SORT - custdist, - c_count
```

#### 查詢命令
<a name="supported-ppl-lookup-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `lookup`命令新增或取代查詢索引 （維度表） 中的資料，以豐富您的搜尋資料。此命令可讓您使用維度資料表中的值來延伸索引的欄位。您也可以使用它在符合查詢條件時附加或取代值。`lookup` 命令比 `Join`命令更適合使用靜態資料集來充實來源資料。

**語法**  
使用下列語法：

```
SEARCH source=<sourceIndex>
| <other piped command>
| LOOKUP <lookupIndex> (<lookupMappingField> [AS <sourceMappingField>])...
    [(REPLACE | APPEND) (<inputField> [AS <outputField>])...]
| <other piped command>
```

**lookupIndex**
+ 必要.
+ 查詢索引的名稱 （維度表）。

**lookupMappingField**
+ 必要.
+ 查詢索引中的映射索引鍵，類似於右側資料表中的聯結索引鍵。您可以指定多個欄位，以逗號分隔。

**sourceMappingField**
+ 選用。
+ 預設：<lookupMappingField>。
+ 來源查詢的映射金鑰，類似於左側的聯結金鑰。

**inputField**
+ 選用。
+ 預設：尋找相符值的查詢索引的所有欄位。
+ 查詢索引中的欄位，其中相符的值會套用至結果輸出。您可以指定多個欄位，以逗號分隔。

**outputField**
+ 選用。
+ 預設：`<inputField>`。
+ 輸出中的 欄位。您可以指定多個輸出欄位。如果您從來源查詢指定現有的欄位名稱，其值將由 inputField 的相符值取代或附加。如果您指定新的欄位名稱，則會將其新增至結果。

**取代 \| 附加**
+ 選用。
+ 預設：REPLACE
+ 指定如何處理相符的值。如果您指定 REPLACE，則 <lookupIndex> 欄位中相符的值會覆寫結果中的值。如果您指定 `APPEND`，則 <lookupIndex> 欄位中相符的值只會附加到結果中缺少的值。

**Usage**
+ lookUP <lookupIndex> id AS cid REPLACE 郵件 AS 電子郵件
+ lookUP <lookupIndex> 名稱 REPLACE 郵件 AS 電子郵件
+ lookUP <lookupIndex> id AS cid、name APPEND 地址、郵件 AS 電子郵件
+ lookUP <lookupIndex> ID

**範例**  
請參閱以下範例。

```
SEARCH source=<sourceIndex>
| WHERE orderType = 'Cancelled'
| LOOKUP account_list, mkt_id AS mkt_code REPLACE amount, account_name AS name
| STATS count(mkt_code), avg(amount) BY name
```

```
SEARCH source=<sourceIndex>
| DEDUP market_id
| EVAL category=replace(category, "-", ".")
| EVAL category=ltrim(category, "dvp.")
| LOOKUP bounce_category category AS category APPEND classification
```

```
SEARCH source=<sourceIndex>
| LOOKUP bounce_category category
```

#### 剖析命令
<a name="supported-ppl-parse-command"></a>

`parse` 命令會剖析具有規則表達式的文字欄位，並將結果附加到搜尋結果。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**語法**  
使用下列語法：

```
parse <field> <pattern>    
```

**`field`**
+ 強制性。
+ 欄位必須是文字欄位。

**`pattern`**
+ 必要字串。
+ 這是規則表達式模式，用於從指定文字欄位擷取新欄位。
+ 如果新的欄位名稱已存在，則會取代原始欄位。

**Regular expression (常規表達式)**  
規則表達式模式用於比對每個文件的整個文字欄位與 Java regex 引擎。表達式中的每個具名擷取群組都會成為新的`STRING`欄位。

**範例 1：建立新欄位**  
此範例示範如何`host`為每個文件建立新欄位。 `host`將是 `email` `@`欄位中 之後的主機名稱。剖析 null 欄位會傳回空字串。

PPL 查詢：

```
os> source=accounts | parse email '.+@(?<host>.+)' | fields email, host ;
fetched rows / total rows = 4/4
+-----------------------+-------------+
| email                 | host        |
|-----------------------+-------------|
| jane_doe@example.com  | example.com |
| john_doe@example.net  | example.net |
| null                  |             |
| juan_li@example.org   | example.org |
+-----------------------+-------------+
```

**範例 2：覆寫現有欄位**  
此範例示範如何在移除街道號碼的情況下覆寫現有`address`欄位。

PPL 查詢：

```
os> source=accounts | parse address '\d+ (?<address>.+)' | fields address ;
fetched rows / total rows = 4/4
+------------------+
| address          |
|------------------|
| Example Lane     |
| Example Street   |
| Example Avenue   |
| Example Court    |
+------------------+
```

**範例 3：依轉換的剖析欄位篩選和排序**  
此範例顯示如何排序`address`欄位中大於 500 的街道號碼。

PPL 查詢：

```
os> source=accounts | parse address '(?<streetNumber>\d+) (?<street>.+)' | where cast(streetNumber as int) > 500 | sort num(streetNumber) | fields streetNumber, street ;
fetched rows / total rows = 3/3
+----------------+----------------+
| streetNumber   | street         |
|----------------+----------------|
| ***            | Example Street |
| ***            | Example Avenue |
| 880            | Example Lane   |
+----------------+----------------+
```

**限制**  
剖析命令有一些限制：
+ 剖析定義的欄位無法再次剖析。

  下列命令無法運作：

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | parse street '\w+ (?<road>\w+)'
  ```
+ 剖析定義的欄位無法以其他命令覆寫。

  `where` 不符合任何文件，因為 `street`無法覆寫：

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval street='1' | where street='1' ;        
  ```
+ 剖析所使用的文字欄位無法覆寫。

  `street` 無法成功剖析 ，因為 `address` 被覆寫：

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval address='1' ;        
  ```
+ 在 `stats`命令中使用剖析定義的欄位後，就無法進行篩選或排序。

  `where` 下列命令中的 無法運作：

  ```
  source=accounts | parse email '.+@(?<host>.+)' | stats avg(age) by host | where host=pyrami.com ;        
  ```

#### 模式命令
<a name="supported-ppl-patterns-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`patterns` 命令會從文字欄位擷取日誌模式，並將結果附加至搜尋結果。依模式分組日誌可讓您更輕鬆地從大量日誌資料彙總統計資料，以進行分析和故障診斷。

**語法**  
使用下列語法：

```
patterns [new_field=<new-field-name>] [pattern=<pattern>] <field>    
```

**new-field-name**
+ 選用字串。
+ 這是擷取模式的新欄位名稱。
+ 預設值為 `patterns_field`。
+ 如果名稱已存在，則會取代原始欄位。

**pattern**
+ 選用字串。
+ 這是應該從文字欄位篩選出的字元規則運算式模式。
+ 如果不存在，預設模式為英數字元 (`[a-zA-Z\d]`)。

**field**
+ 強制性。
+ 欄位必須是文字欄位。

**範例 1：建立新欄位**  
此範例示範如何`email`針對每個文件使用 中的擷取標點符號。剖析 null 欄位會傳回空字串。

PPL 查詢：

```
os> source=accounts | patterns email | fields email, patterns_field ;
fetched rows / total rows = 4/4
+-----------------------+------------------+
| email                 | patterns_field   |
|-----------------------+------------------|
| jane_doe@example.com  | @.               |
| john_doe@example.net  | @.               |
| null                  |                  |
| juan_li@example.org   | @.               |
+-----------------------+------------------+
```

**範例 2：擷取日誌模式**  
此範例示範如何使用預設模式從原始日誌欄位擷取標點符號。

PPL 查詢：

```
os> source=apache | patterns message | fields message, patterns_field ;
fetched rows / total rows = 4/4
+-----------------------------------------------------------------------------------------------------------------------------+---------------------------------+
| message                                                                                                                     | patterns_field                  |
|-----------------------------------------------------------------------------------------------------------------------------+---------------------------------|
| 177.95.8.74 - upton5450 [28/Sep/2022:10:15:57 -0700] "HEAD /e-business/mindshare HTTP/1.0" 404 19927                        | ... -  [//::: -] " /-/ /."      |
| ************ - pouros8756 [28/Sep/2022:10:15:57 -0700] "GET /architectures/convergence/niches/mindshare HTTP/1.0" 100 28722 | ... -  [//::: -] " //// /."     |
| *************** - - [28/Sep/2022:10:15:57 -0700] "PATCH /strategize/out-of-the-box HTTP/1.0" 401 27439                      | ... - - [//::: -] " //--- /."   |
| ************** - - [28/Sep/2022:10:15:57 -0700] "POST /users HTTP/1.1" 301 9481                                             | ... - - [//::: -] " / /."       |
+-----------------------------------------------------------------------------------------------------------------------------+---------------------------------+
```

**範例 3：使用自訂 regex 模式擷取日誌模式**  
此範例示範如何使用使用者定義的模式，從原始日誌欄位擷取標點符號。

PPL 查詢：

```
os> source=apache | patterns new_field='no_numbers' pattern='[0-9]' message | fields message, no_numbers ;
fetched rows / total rows = 4/4
+-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------+
| message                                                                                                                     | no_numbers                                                                           |
|-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------|
| 177.95.8.74 - upton5450 [28/Sep/2022:10:15:57 -0700] "HEAD /e-business/mindshare HTTP/1.0" 404 19927                        | ... - upton [/Sep/::: -] "HEAD /e-business/mindshare HTTP/."                         |
| 127.45.152.6 - pouros8756 [28/Sep/2022:10:15:57 -0700] "GET /architectures/convergence/niches/mindshare HTTP/1.0" 100 28722 | ... - pouros [/Sep/::: -] "GET /architectures/convergence/niches/mindshare HTTP/."   |
| *************** - - [28/Sep/2022:10:15:57 -0700] "PATCH /strategize/out-of-the-box HTTP/1.0" 401 27439                      | ... - - [/Sep/::: -] "PATCH /strategize/out-of-the-box HTTP/."                       |
| ************** - - [28/Sep/2022:10:15:57 -0700] "POST /users HTTP/1.1" 301 9481                                             | ... - - [/Sep/::: -] "POST /users HTTP/."                                            |
+-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------+
```

**限制**  
模式命令具有與剖析命令相同的限制。

#### 罕見命令
<a name="supported-ppl-rare-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `rare`命令來尋找欄位清單中所有欄位最不常見的值元組。

**注意**  
群組區分欄位的每個不同值元組最多傳回 10 個結果。

**語法**  
使用下列語法：

```
rare [N] <field-list> [by-clause] rare_approx [N] <field-list> [by-clause]
```

**field-list**
+ 強制性。
+ 欄位名稱的逗號分隔清單。

**依 -clause**
+ 選用。
+ 要分組結果的一個或多個欄位。

**N**
+ 要傳回的結果數目。
+ 預設：10

**罕見\_大約**
+ 使用 [ HyperLogLog\+\+ 演算法預估基數](https://spark.apache.org/docs/latest/sql-ref-functions-builtin.html)的罕見 (n) 欄位近似計數。

**範例 1：尋找欄位中最不常見的值**  
此範例會尋找所有帳戶的最小共同性別。

PPL 查詢：

```
os> source=accounts | rare gender;
os> source=accounts | rare_approx 10 gender;
os> source=accounts | rare_approx gender;
fetched rows / total rows = 2/2
+----------+
| gender   |
|----------|
| F        |
| M        |
+----------+
```

**範例 2：尋找依性別組織的最低常見值**  
此範例會依性別尋找所有帳戶群組的最低共同年齡。

PPL 查詢：

```
os> source=accounts | rare 5 age by gender;
os> source=accounts | rare_approx 5 age by gender;
fetched rows / total rows = 4/4
+----------+-------+
| gender   | age   |
|----------+-------|
| F        | 28    |
| M        | 32    |
| M        | 33    |
| M        | 36    |
+----------+-------+
```

#### 重新命名命令
<a name="supported-ppl-rename-command"></a>

使用 `rename`命令來變更搜尋結果中一或多個欄位的名稱。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**語法**  
使用下列語法：

```
rename <source-field> AS <target-field>["," <source-field> AS <target-field>]...    
```

**來源欄位**
+ 強制性。
+ 這是您要重新命名的欄位名稱。

**target-field**
+ 強制性。
+ 這是您要重新命名的名稱。

**範例 1：重新命名一個欄位**  
此範例說明如何重新命名單一欄位。

PPL 查詢：

```
os> source=accounts | rename account_number as an | fields an;
fetched rows / total rows = 4/4
+------+
| an   |
|------|
| 1    |
| 6    |
| 13   |
| 18   |
+------+
```

**範例 2：重新命名多個欄位**  
此範例說明如何重新命名多個欄位。

PPL 查詢：

```
os> source=accounts | rename account_number as an, employer as emp | fields an, emp;
fetched rows / total rows = 4/4
+------+---------+
| an   | emp     |
|------+---------|
| 1    | Pyrami  |
| 6    | Netagy  |
| 13   | Quility |
| 18   | null    |
+------+---------+
```

**限制**
+ 不支援覆寫現有欄位：

  ```
  source=accounts | grok address '%{NUMBER} %{GREEDYDATA:address}' | fields address        
  ```

#### 搜尋命令
<a name="supported-ppl-search-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `search`命令從 索引擷取文件。`search` 命令只能用作 PPL 查詢中的第一個命令。

**語法**  
使用下列語法：

```
search source=[<remote-cluster>:]<index> [boolean-expression]    
```

**search**
+ 選用。
+ 可省略的搜尋關鍵字。

**index**
+ 強制性。
+ 搜尋命令必須指定要查詢的索引。
+ 對於跨叢集搜尋`<cluster name>:`，索引名稱可由 加上字首。

**bool-expression**
+ 選用。
+ 任何評估為布林值的表達式。

**範例 1：擷取所有資料**  
此範例顯示從帳戶索引擷取所有文件。

PPL 查詢：

```
os> source=accounts;
+------------------+-------------+----------------------+-----------+----------+--------+----------------+---------+-------+-----------------------+------------+
| account_number   | firstname   | address              | balance   | gender   | city   | employer       | state   | age   | email                 | lastname   |
|------------------+-------------+----------------------+-----------+----------+--------+----------------+---------+-------+-----------------------+------------|
| 1                | Jorge       | *** Any Lane         | 39225     | M        | Brogan | ExampleCorp    | IL      | 32    | jane_doe@example.com  | Souza      |
| 6                | John        | *** Example Street   | 5686      | M        | Dante  | AnyCorp        | TN      | 36    | john_doe@example.com  | Doe        |
| 13               | Jane        | *** Any Street       | *****     | F        | Nogal  | ExampleCompany | VA      | 28    | null                  | Doe        |
| 18               | Juan        | *** Example Court    | 4180      | M        | Orick  | null           | MD      | 33    | juan_li@example.org   | Li         |
+------------------+-------------+----------------------+-----------+----------+--------+----------------+---------+-------+-----------------------+------------+
```

**範例 2：使用 條件擷取資料**  
此範例顯示使用 從帳戶索引擷取所有文件。

PPL 查詢：

```
os> SEARCH source=accounts account_number=1 or gender="F";
+------------------+-------------+--------------------+-----------+----------+--------+----------------+---------+-------+-------------------------+------------+
| account_number   | firstname   | address            | balance   | gender   | city   | employer       | state   | age   | email                -  | lastname   |
|------------------+-------------+--------------------+-----------+----------+--------+----------------+---------+-------+-------------------------+------------|
| 1                | Jorge       | *** Any Lane       | *****     | M        | Brogan | ExampleCorp    | IL      | 32    | jorge_souza@example.com | Souza      |
| 13               | Jane        | *** Any Street     | *****     | F        | Nogal  | ExampleCompany | VA      | 28    | null                    | Doe        |
+------------------+-------------+--------------------+-----------+----------+--------+-----------------+---------+-------+------------------------+------------+
```

#### sort 命令
<a name="supported-ppl-sort-command"></a>

使用 `sort`命令，依指定的欄位排序搜尋結果。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**語法**  
使用下列語法：

```
sort <[+|-] sort-field>...
```

**[\+\|-]**
+ 選用。
+ 加號 【＋】 表示先有 NULL/MISSING 值的遞增順序。
+ 減號 【-】 表示 NULL/MISSING 值最後的遞減順序。
+ 預設：先以 NULL/MISSING 值遞增順序。

**sort-field**
+ 強制性。
+ 用於排序的欄位。

**範例 1：依一個欄位排序**  
此範例顯示如何以遞增順序排序具有存留期欄位的文件。

PPL 查詢：

```
os> source=accounts | sort age | fields account_number, age;
fetched rows / total rows = 4/4
+------------------+-------+
| account_number   | age   |
|------------------+-------|
| 13               | 28    |
| 1                | 32    |
| 18               | 33    |
| 6                | 36    |
+------------------+-------+
```

**範例 2：依一個欄位排序並傳回所有結果**  
此範例顯示如何以遞增順序排序具有存留期欄位的文件。

PPL 查詢：

```
os> source=accounts | sort age | fields account_number, age;
fetched rows / total rows = 4/4
+------------------+-------+
| account_number   | age   |
|------------------+-------|
| 13               | 28    |
| 1                | 32    |
| 18               | 33    |
| 6                | 36    |
+------------------+-------+
```

**範例 3：依欄位遞減排序**  
此範例示範如何以遞減順序排序具有存留期欄位的文件。

PPL 查詢：

```
os> source=accounts | sort - age | fields account_number, age;
fetched rows / total rows = 4/4
+------------------+-------+
| account_number   | age   |
|------------------+-------|
| 6                | 36    |
| 18               | 33    |
| 1                | 32    |
| 13               | 28    |
+------------------+-------+
```

**範例 4：依多個欄位排序**  
此範例顯示如何以遞增順序排序文件的性別欄位，並以遞減順序排序年齡欄位。

PPL 查詢：

```
os> source=accounts | sort + gender, - age | fields account_number, gender, age;
fetched rows / total rows = 4/4
+------------------+----------+-------+
| account_number   | gender   | age   |
|------------------+----------+-------|
| 13               | F        | 28    |
| 6                | M        | 36    |
| 18               | M        | 33    |
| 1                | M        | 32    |
+------------------+----------+-------+
```

**範例 5：依欄位排序包含 null 值**  
此範例示範如何依預設選項 （先遞增順序和 null) 排序雇主欄位。結果顯示 null 值位於第一列。

PPL 查詢：

```
os> source=accounts | sort employer | fields employer;
fetched rows / total rows = 4/4
+------------+
| employer   |
|------------|
| null       |
| AnyCompany |
| AnyCorp    |
| AnyOrgty   |
+------------+
```

#### stats 命令
<a name="supported-ppl-stats-command"></a>

使用 `stats`命令從搜尋結果計算彙總。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**NULL/MISSING 值處理**  



**NULL/MISSING 值處理**  

| 函式 | NULL | 缺少 | 
| --- | --- | --- | 
| COUNT | 未計數 | 未計數 | 
| SUM | Ignore | Ignore | 
| AVG | Ignore | Ignore | 
| MAX | Ignore | Ignore | 
| MIN | Ignore | Ignore | 

**語法**  
使用下列語法：

```
stats <aggregation>... [by-clause]    
```

**聚合**
+ 強制性。
+ 套用至欄位的彙總函數。

**依 -clause**
+ 選用。
+ 語法: `by [span-expression,] [field,]...`
+ 指定用於分組彙總結果的欄位和表達式。依項目可讓您使用欄位和表達式將彙總結果分組。您可以使用純量函數、彙總函數，甚至是跨度表達式，將特定欄位分割成相等間隔的儲存貯體。
+ 預設：如果未指定 `<by-clause>` ，則 stats 命令會傳回代表整個結果集中彙總的單一資料列。

**span-expression**  

+ 選用，最多一個。
+ 語法: `span(field_expr, interval_expr)`
+ 間隔表達式的單位預設為自然單位。如果 欄位是日期和時間類型欄位，且間隔是以日期/時間單位為單位，您可以在間隔表達式中指定單位。
+ 例如，將`age`欄位分割為儲存貯體 10 年，看起來像 `span(age, 10)`。若要將時間戳記欄位分割為每小時間隔，請使用 `span(timestamp, 1h)`。


**可用的時間單位**  

| 跨度間隔單位 | 
| --- | 
| 毫秒 (ms) | 
| 秒 （秒） | 
| 分鐘 (m、區分大小寫） | 
| 小時 (h) | 
| 天 (d) | 
| 週 (w) | 
| 月 (M、區分大小寫） | 
| 季度 (q) | 
| 年 (y) | 

**彙總函數**  


**`COUNT`**  
傳回 SELECT 陳述式所擷取資料列中的 expr 數量計數。

範例：

```
os> source=accounts | stats count();
fetched rows / total rows = 1/1
+-----------+
| count()   |
|-----------|
| 4         |
+-----------+
```

**`SUM`**  
使用 `SUM(expr)` 傳回 expr 的總和。

範例

```
os> source=accounts | stats sum(age) by gender;
fetched rows / total rows = 2/2
+------------+----------+
| sum(age)   | gender   |
|------------+----------|
| 28         | F        |
| 101        | M        |
+------------+----------+
```

**`AVG`**  
使用 `AVG(expr)`傳回 expr 的平均值。

範例

```
os> source=accounts | stats avg(age) by gender;
fetched rows / total rows = 2/2
+--------------------+----------+
| avg(age)           | gender   |
|--------------------+----------|
| 28.0               | F        |
| 33.666666666666664 | M        |
+--------------------+----------+
```

**`MAX`**  
使用 `MAX(expr)`傳回 expr 的最大值。

範例

```
os> source=accounts | stats max(age);
fetched rows / total rows = 1/1
+------------+
| max(age)   |
|------------|
| 36         |
+------------+
```

**`MIN`**  
使用 `MIN(expr)`傳回 expr 的最小值。

範例

```
os> source=accounts | stats min(age);
fetched rows / total rows = 1/1
+------------+
| min(age)   |
|------------|
| 28         |
+------------+
```

**`STDDEV_SAMP`**  
使用 `STDDEV_SAMP(expr)` 傳回 expr.

範例：

```
os> source=accounts | stats stddev_samp(age);
fetched rows / total rows = 1/1
+--------------------+
| stddev_samp(age)   |
|--------------------|
| 3.304037933599835  |
+--------------------+
```

**STDDEV\_POP**  
使用 `STDDEV_POP(expr)` 傳回 expr 的母群體標準差。

範例：

```
os> source=accounts | stats stddev_pop(age);
fetched rows / total rows = 1/1
+--------------------+
| stddev_pop(age)    |
|--------------------|
| 2.**************** |
+--------------------+
```

**接受**  
使用 `TAKE(field [, size])`傳回欄位的原始值。它不保證值的順序。

**field**
+ 強制性。
+ 欄位必須是文字欄位。

**size**
+ 選用整數。
+ 應傳回的值數目。
+ 預設為 10。

**範例**  


```
os> source=accounts | stats take(firstname);
fetched rows / total rows = 1/1
+-----------------------------+
| take(firstname)             |
|-----------------------------|
| [Jane, Mary, Nikki, Juan    |
+-----------------------------+
```

**PERCENTILE 或 PERCENTILE\_APPROX**  
使用 `PERCENTILE(expr, percent)`或 `PERCENTILE_APPROX(expr, percent)` 以指定百分比傳回 expr 的近似百分位數值。

**百分比**
+ 數字必須是介於 0 到 100 之間的常數。

**範例**  


```
os> source=accounts | stats percentile(age, 90) by gender;
fetched rows / total rows = 2/2
+-----------------------+----------+
| percentile(age, 90)   | gender   |
|-----------------------+----------|
| 28                    | F        |
| 36                    | M        |
+-----------------------+----------+
```

**範例 1：計算事件計數**  
此範例示範如何計算帳戶中的事件計數。

```
os> source=accounts | stats count();
fetched rows / total rows = 1/1
+-----------+
| count()   |
|-----------|
| 4         |
+-----------+
```

**範例 2：計算欄位的平均值**  
此範例示範如何計算所有帳戶的平均存留期。

```
os> source=accounts | stats avg(age);
fetched rows / total rows = 1/1
+------------+
| avg(age)   |
|------------|
| 32.25      |
+------------+
```

**範例 3：依群組計算欄位的平均值**  
此範例顯示如何計算所有帳戶的平均存留期，依性別分組。

```
os> source=accounts | stats avg(age) by gender;
fetched rows / total rows = 2/2
+--------------------+----------+
| avg(age)           | gender   |
|--------------------+----------|
| 28.0               | F        |
| 33.666666666666664 | M        |
+--------------------+----------+
```

**範例 4：依群組計算欄位的平均值、總和和計數**  
此範例顯示如何計算平均存留期、總存留期，以及依性別分組之所有帳戶的事件計數。

```
os> source=accounts | stats avg(age), sum(age), count() by gender;
fetched rows / total rows = 2/2
+--------------------+------------+-----------+----------+
| avg(age)           | sum(age)   | count()   | gender   |
|--------------------+------------+-----------+----------|
| 28.0               | 28         | 1         | F        |
| 33.666666666666664 | 101        | 3         | M        |
+--------------------+------------+-----------+----------+
```

**範例 5：計算欄位的最大值**  
此範例會計算所有帳戶的最長存留期。

```
os> source=accounts | stats max(age);
fetched rows / total rows = 1/1
+------------+
| max(age)   |
|------------|
| 36         |
+------------+
```

**範例 6：依群組計算欄位的最大值和最小值**  
此範例會計算所有帳戶的最大和最小存留期值，依性別分組。

```
os> source=accounts | stats max(age), min(age) by gender;
fetched rows / total rows = 2/2
+------------+------------+----------+
| max(age)   | min(age)   | gender   |
|------------+------------+----------|
| 28         | 28         | F        |
| 36         | 32         | M        |
+------------+------------+----------+
```

**範例 7：計算欄位的不同計數**  
若要取得欄位不同值的計數，您可以使用 `DISTINCT_COUNT`（或 `DC`) 函數，而非 `COUNT`。此範例會計算所有帳戶的性別欄位計數和相異計數。

```
os> source=accounts | stats count(gender), distinct_count(gender);
fetched rows / total rows = 1/1
+-----------------+--------------------------+
| count(gender)   | distinct_count(gender)   |
|-----------------+--------------------------|
| 4               | 2                        |
+-----------------+--------------------------+
```

**範例 8：依跨度計算計數**  
此範例會取得 10 年間隔的存留期計數。

```
os> source=accounts | stats count(age) by span(age, 10) as age_span
fetched rows / total rows = 2/2
+--------------+------------+
| count(age)   | age_span   |
|--------------+------------|
| 1            | 20         |
| 3            | 30         |
+--------------+------------+
```

**範例 9：依性別和跨度計算計數**  
此範例會計算依性別和年齡分組的記錄，為期 5 年。

```
os> source=accounts | stats count() as cnt by span(age, 5) as age_span, gender
fetched rows / total rows = 3/3
+-------+------------+----------+
| cnt   | age_span   | gender   |
|-------+------------+----------|
| 1     | 25         | F        |
| 2     | 30         | M        |
| 1     | 35         | M        |
+-------+------------+----------+
```

無論命令中指定的順序為何，跨度表達式一律會顯示為第一個分組索引鍵。

```
os> source=accounts | stats count() as cnt by gender, span(age, 5) as age_span
fetched rows / total rows = 3/3
+-------+------------+----------+
| cnt   | age_span   | gender   |
|-------+------------+----------|
| 1     | 25         | F        |
| 2     | 30         | M        |
| 1     | 35         | M        |
+-------+------------+----------+
```

**範例 10：計算計數並依性別和跨度取得電子郵件清單**  
此範例會依 10 年的間隔取得年齡計數，並依性別分組，此外，每列會取得最多 5 封電子郵件的清單。

```
os> source=accounts | stats count() as cnt, take(email, 5) by span(age, 5) as age_span, gender
fetched rows / total rows = 3/3
+-------+----------------------------------------------------+------------+----------+
| cnt   | take(email, 5)                                     | age_span   | gender   |
|-------+----------------------------------------------------+------------+----------|
| 1     | []                                                 | 25         | F        |
| 2     | [janedoe@anycompany.com,juanli@examplecompany.org] | 30         | M        |
| 1     | [marymajor@examplecorp.com]                        | 35         | M        |
+-------+----------------------------------------------------+------------+----------+
```

**範例 11：計算欄位的百分位數**  
此範例示範如何計算所有帳戶的百分位數 90 歲。

```
os> source=accounts | stats percentile(age, 90);
fetched rows / total rows = 1/1
+-----------------------+
| percentile(age, 90)   |
|-----------------------|
| 36                    |
+-----------------------+
```

**範例 12：依群組計算欄位的百分位數**  
此範例顯示如何依性別計算所有帳戶群組的第 90 個百分位數年齡。

```
os> source=accounts | stats percentile(age, 90) by gender;
fetched rows / total rows = 2/2
+-----------------------+----------+
| percentile(age, 90)   | gender   |
|-----------------------+----------|
| 28                    | F        |
| 36                    | M        |
+-----------------------+----------+
```

**範例 13：依性別和跨度計算百分位數**  
此範例會取得以 10 年為間隔的第 90 個百分位數，並依性別分組。

```
os> source=accounts | stats percentile(age, 90) as p90 by span(age, 10) as age_span, gender
fetched rows / total rows = 2/2
+-------+------------+----------+
| p90   | age_span   | gender   |
|-------+------------+----------|
| 28    | 20         | F        |
| 36    | 30         | M        |
+-------+------------+----------+
```

```
- `source = table | stats avg(a) `
- `source = table | where a < 50 | stats avg(c) `
- `source = table | stats max(c) by b`
- `source = table | stats count(c) by b | head 5`
- `source = table | stats distinct_count(c)`
- `source = table | stats stddev_samp(c)`
- `source = table | stats stddev_pop(c)`
- `source = table | stats percentile(c, 90)`
- `source = table | stats percentile_approx(c, 99)`
```

**包含跨度的彙總**  


```
- `source = table  | stats count(a) by span(a, 10) as a_span`
- `source = table  | stats sum(age) by span(age, 5) as age_span | head 2`
- `source = table  | stats avg(age) by span(age, 20) as age_span, country  | sort - age_span |  head 2`
```

**使用時間範圍的彙總 （翻轉視窗調整函數）**  


```
- `source = table | stats sum(productsAmount) by span(transactionDate, 1d) as age_date | sort age_date`
- `source = table | stats sum(productsAmount) by span(transactionDate, 1w) as age_date, productId`
```

**依多個層級彙總群組**  


```
- `source = table | stats avg(age) as avg_state_age by country, state | stats avg(avg_state_age) as avg_country_age by country`
- `source = table | stats avg(age) as avg_city_age by country, state, city | eval new_avg_city_age = avg_city_age - 1 | stats avg(new_avg_city_age) as avg_state_age by country, state | where avg_state_age > 18 | stats avg(avg_state_age) as avg_adult_country_age by country`
```

#### 子查詢命令
<a name="supported-ppl-subquery-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `subquery`命令在 Piped Processing Language (PPL) 陳述式中執行複雜的巢狀查詢。

```
source=logs | where field in [ subquery source=events | where condition | fields field ]
```

在此範例中，主要搜尋 (`source=logs`) 會依子查詢 () 的結果進行篩選`source=events`。

子查詢命令支援多層巢狀化，以進行複雜的資料分析。

**巢狀子查詢範例**  


```
source=logs | where id in [ subquery source=users | where user in [ subquery source=actions | where action="login" | fields user] | fields uid ]  
```

**InSubquery 用量**
+ `source = outer | where a in [ source = inner | fields b ]`
+ `source = outer | where (a) in [ source = inner | fields b ]`
+ `source = outer | where (a,b,c) in [ source = inner | fields d,e,f ]`
+ `source = outer | where a not in [ source = inner | fields b ]`
+ `source = outer | where (a) not in [ source = inner | fields b ]`
+ `source = outer | where (a,b,c) not in [ source = inner | fields d,e,f ]`
+ `source = outer a in [ source = inner | fields b ]` （使用子查詢進行搜尋篩選）
+ `source = outer a not in [ source = inner | fields b ]` （使用子查詢進行搜尋篩選）
+ `source = outer | where a in [ source = inner1 | where b not in [ source = inner2 | fields c ] | fields b ]` （巢狀）
+ `source = table1 | inner join left = l right = r on l.a = r.a AND r.a in [ source = inner | fields d ] | fields l.a, r.a, b, c` （作為聯結篩選條件）

**使用 IN-Subquery PPL 的 SQL 遷移範例**  
TPC-H Q4 （具有彙總的子查詢中）

```
select
  o_orderpriority,
  count(*) as order_count
from
  orders
where
  o_orderdate >= date '1993-07-01'
  and o_orderdate < date '1993-07-01' + interval '3' month
  and o_orderkey in (
    select
      l_orderkey
    from
      lineitem
    where l_commitdate < l_receiptdate
  )
group by
  o_orderpriority
order by
  o_orderpriority
```

由 PPL InSubquery 查詢重寫：

```
source = orders
| where o_orderdate >= "1993-07-01" and o_orderdate < "1993-10-01" and o_orderkey IN
  [ source = lineitem
    | where l_commitdate < l_receiptdate
    | fields l_orderkey
  ]
| stats count(1) as order_count by o_orderpriority
| sort o_orderpriority
| fields o_orderpriority, order_count
```

TPC-H Q20 （巢狀子查詢）

```
select
  s_name,
  s_address
from
  supplier,
  nation
where
  s_suppkey in (
    select
      ps_suppkey
    from
      partsupp
    where
      ps_partkey in (
        select
          p_partkey
        from
          part
        where
          p_name like 'forest%'
      )
  )
  and s_nationkey = n_nationkey
  and n_name = 'CANADA'
order by
  s_name
```

由 PPL InSubquery 查詢重寫：

```
source = supplier
| where s_suppkey IN [
    source = partsupp
    | where ps_partkey IN [
        source = part
        | where like(p_name, "forest%")
        | fields p_partkey
      ]
    | fields ps_suppkey
  ]
| inner join left=l right=r on s_nationkey = n_nationkey and n_name = 'CANADA'
  nation
| sort s_name
```

**ExistsSubquery 用量**  
假設：`a`、 `b`是資料表外部的欄位`c`、、 `d` 是資料表內部的欄位`e`、、 `f`是資料表內部的欄位2。
+ `source = outer | where exists [ source = inner | where a = c ]`
+ `source = outer | where not exists [ source = inner | where a = c ]`
+ `source = outer | where exists [ source = inner | where a = c and b = d ]`
+ `source = outer | where not exists [ source = inner | where a = c and b = d ]`
+ `source = outer exists [ source = inner | where a = c ]` （使用子查詢進行搜尋篩選）
+ `source = outer not exists [ source = inner | where a = c ]` （使用子查詢進行搜尋篩選）
+ `source = table as t1 exists [ source = table as t2 | where t1.a = t2.a ]` （資料表別名在存在的子查詢中很有用）
+ `source = outer | where exists [ source = inner1 | where a = c and exists [ source = inner2 | where c = e ] ]` （巢狀）
+ `source = outer | where exists [ source = inner1 | where a = c | where exists [ source = inner2 | where c = e ] ]` （巢狀）
+ `source = outer | where exists [ source = inner | where c > 10 ]` （不存在不相關）
+ `source = outer | where not exists [ source = inner | where c > 10 ]` （不存在不相關）
+ `source = outer | where exists [ source = inner ] | eval l = "nonEmpty" | fields l` （存在特殊不相關）

**ScalarSubquery 用量**  
假設：`a`、 `b`是資料表外部的欄位`c`、、 `d`是資料表內部的欄位`e`、、 `f`是資料表巢狀的欄位

**不相關的純量子查詢**  
在 Select 中：
+ `source = outer | eval m = [ source = inner | stats max(c) ] | fields m, a`
+ `source = outer | eval m = [ source = inner | stats max(c) ] + b | fields m, a`

在 中：
+ `source = outer | where a > [ source = inner | stats min(c) ] | fields a`

在搜尋篩選條件中：
+ `source = outer a > [ source = inner | stats min(c) ] | fields a`

**相關純量子查詢**  
在 Select 中：
+ `source = outer | eval m = [ source = inner | where outer.b = inner.d | stats max(c) ] | fields m, a`
+ `source = outer | eval m = [ source = inner | where b = d | stats max(c) ] | fields m, a`
+ `source = outer | eval m = [ source = inner | where outer.b > inner.d | stats max(c) ] | fields m, a`

在 中：
+ `source = outer | where a = [ source = inner | where outer.b = inner.d | stats max(c) ]`
+ `source = outer | where a = [ source = inner | where b = d | stats max(c) ]`
+ `source = outer | where [ source = inner | where outer.b = inner.d OR inner.d = 1 | stats count() ] > 0 | fields a`

在搜尋篩選條件中：
+ `source = outer a = [ source = inner | where b = d | stats max(c) ]`
+ `source = outer [ source = inner | where outer.b = inner.d OR inner.d = 1 | stats count() ] > 0 | fields a`

**巢狀純量子查詢**  

+ `source = outer | where a = [ source = inner | stats max(c) | sort c ] OR b = [ source = inner | where c = 1 | stats min(d) | sort d ]`
+ `source = outer | where a = [ source = inner | where c = [ source = nested | stats max(e) by f | sort f ] | stats max(d) by c | sort c | head 1 ]`

**（關係） 子查詢**  
`InSubquery`、 `ExistsSubquery`和 `ScalarSubquery` 都是子查詢表達式。但`RelationSubquery`不是子查詢表達式，而是在聯結或來源子句中常用的子查詢計畫。
+ `source = table1 | join left = l right = r [ source = table2 | where d > 10 | head 5 ]` （聯結右側的子查詢）
+ `source = [ source = table1 | join left = l right = r [ source = table2 | where d > 10 | head 5 ] | stats count(a) by b ] as outer | head 1`

**其他內容**  
`InSubquery`、 `ExistsSubquery`和 `ScalarSubquery`是`where`子句和搜尋篩選條件中常用的子查詢表達式。

其中命令：

```
| where <boolean expression> | ...    
```

搜尋篩選條件：

```
search source=* <boolean expression> | ...    
```

子查詢表達式可用於布林表達式：

```
| where orders.order_id in [ source=returns | where return_reason="damaged" | field order_id ]    
```

`orders.order_id in [ source=... ]` 是 `<boolean expression>`。

一般而言，我們將這種子查詢子句命名為`InSubquery`表達式。它是 `<boolean expression>`。

**具有不同聯結類型的子查詢**  
使用 `ScalarSubquery` 的範例：

```
source=employees
| join source=sales on employees.employee_id = sales.employee_id
| where sales.sale_amount > [ source=targets | where target_met="true" | fields target_value ]
```

與 InSubquery、ExistsSubquery 和 ScalarSubquery 不同，RelationSubquery 不是子查詢表達式。而是子查詢計劃。

```
SEARCH source=customer
| FIELDS c_custkey
| LEFT OUTER JOIN left = c, right = o ON c.c_custkey = o.o_custkey
   [
      SEARCH source=orders
      | WHERE o_comment NOT LIKE '%unusual%packages%'
      | FIELDS o_orderkey, o_custkey
   ]
| STATS ...
```

#### top 命令
<a name="supported-ppl-top-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `top`命令來尋找欄位清單中所有欄位值的最常見元組。

**語法**  
使用下列語法：

```
top [N] <field-list> [by-clause] top_approx [N] <field-list> [by-clause]
```

**N**
+ 要傳回的結果數量。
+ 預設：10

**field-list**
+ 強制性。
+ 欄位名稱的逗號分隔清單。

**依程式**
+ 選用。
+ 要分組結果的一個或多個欄位。

**top\_approx**
+ 使用 [ HyperLogLog\+\+ 演算法預估基數](https://spark.apache.org/docs/latest/sql-ref-functions-builtin.html)的 (n) 個熱門欄位的近似計數。

**範例 1：尋找欄位中最常見的值**  
此範例會尋找所有帳戶的最常見性別。

PPL 查詢：

```
os> source=accounts | top gender;
os> source=accounts | top_approx gender;
fetched rows / total rows = 2/2
+----------+
| gender   |
|----------|
| M        |
| F        |
+----------+
```

**範例 2：尋找欄位中最常見的值 （限制為 1)**  
此範例會尋找所有帳戶的單一最常見性別。

PPL 查詢：

```
os> source=accounts | top_approx 1 gender;
fetched rows / total rows = 1/1
+----------+
| gender   |
|----------|
| M        |
+----------+
```

**範例 3：尋找最常見的值，依性別分組**  
此範例會尋找所有帳戶的最常見存留期，依性別分組。

PPL 查詢：

```
os> source=accounts | top 1 age by gender;
os> source=accounts | top_approx 1 age by gender;
fetched rows / total rows = 2/2
+----------+-------+
| gender   | age   |
|----------+-------|
| F        | 28    |
| M        | 32    |
+----------+-------+
```

#### 趨勢線命令
<a name="supported-ppl-trendline-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `trendline`命令來計算欄位的移動平均值。

**語法**  
使用下列語法

```
TRENDLINE [sort <[+|-] sort-field>] SMA(number-of-datapoints, field) [AS alias] [SMA(number-of-datapoints, field) [AS alias]]... 
```

**[\+\|-]**
+ 選用。
+ 加號 【＋】 表示先有 NULL/MISSING 值的遞增順序。
+ 減號 【-】 代表 NULL/MISSING 值最後的遞減順序。
+ 預設：先以 NULL/MISSING 值遞增順序。

**sort-field**
+ 使用排序時為強制性。
+ 用於排序的欄位。

**number-of-datapoints**
+ 強制性。
+ 計算移動平均值的資料點數目。
+ 必須大於零。

**field**
+ 強制性。
+ 應計算移動平均值的欄位名稱。

**別名**
+ 選用。
+ 包含移動平均值的產生資料欄名稱。

僅支援簡易移動平均 (SMA) 類型。其計算方式如下：

```
f[i]: The value of field 'f' in the i-th data-point
n: The number of data-points in the moving window (period)
t: The current time index

SMA(t) = (1/n) * Σ(f[i]), where i = t-n+1 to t
```

**範例 1：計算一段時間溫度的簡單移動平均值**  
此範例使用兩個資料點計算溫度的簡單移動平均值。

PPL 查詢：

```
os> source=t | trendline sma(2, temperature) as temp_trend;
fetched rows / total rows = 5/5
+-----------+---------+--------------------+----------+
|temperature|device-id|           timestamp|temp_trend|
+-----------+---------+--------------------+----------+
|         12|     1492|2023-04-06 17:07:...|      NULL|
|         12|     1492|2023-04-06 17:07:...|      12.0|
|         13|      256|2023-04-06 17:07:...|      12.5|
|         14|      257|2023-04-06 17:07:...|      13.5|
|         15|      258|2023-04-06 17:07:...|      14.5|
+-----------+---------+--------------------+----------+
```

**範例 2：使用排序計算溫度時間的簡單移動平均值**  
此範例使用依 device-id 遞減排序的兩個和三個資料點，計算溫度的兩個簡單移動平均值。

PPL 查詢：

```
os> source=t | trendline sort - device-id sma(2, temperature) as temp_trend_2 sma(3, temperature) as temp_trend_3;
fetched rows / total rows = 5/5
+-----------+---------+--------------------+------------+------------------+
|temperature|device-id|           timestamp|temp_trend_2|      temp_trend_3|
+-----------+---------+--------------------+------------+------------------+
|         15|      258|2023-04-06 17:07:...|        NULL|              NULL|
|         14|      257|2023-04-06 17:07:...|        14.5|              NULL|
|         13|      256|2023-04-06 17:07:...|        13.5|              14.0|
|         12|     1492|2023-04-06 17:07:...|        12.5|              13.0|
|         12|     1492|2023-04-06 17:07:...|        12.0|12.333333333333334|
+-----------+---------+--------------------+------------+------------------+
```

#### 其中 命令
<a name="supported-ppl-where-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`where` 命令使用 bool-expression 來篩選搜尋結果。只有在 bool-expression 評估為 true 時，才會傳回結果。

**語法**  
使用下列語法：

```
where <boolean-expression>    
```

**bool-expression**
+ 選用。
+ 任何可以評估為布林值的表達式。

**範例 1：使用 條件篩選結果集**  
此範例示範如何從符合特定條件的帳戶索引擷取文件。

PPL 查詢：

```
os> source=accounts | where account_number=1 or gender="F" | fields account_number, gender;
fetched rows / total rows = 2/2
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 13               | F        |
+------------------+----------+
```

**其他範例**  


**具有邏輯條件的篩選條件**
+ `source = table | where c = 'test' AND a = 1 | fields a,b,c`
+ `source = table | where c != 'test' OR a > 1 | fields a,b,c | head 1`
+ `source = table | where c = 'test' NOT a > 1 | fields a,b,c`
+ `source = table | where a = 1 | fields a,b,c`
+ `source = table | where a >= 1 | fields a,b,c`
+ `source = table | where a < 1 | fields a,b,c`
+ `source = table | where b != 'test' | fields a,b,c`
+ `source = table | where c = 'test' | fields a,b,c | head 3`
+ `source = table | where ispresent(b)`
+ `source = table | where isnull(coalesce(a, b)) | fields a,b,c | head 3`
+ `source = table | where isempty(a)`
+ `source = table | where isblank(a)`
+ `source = table | where case(length(a) > 6, 'True' else 'False') = 'True'`
+ `source = table | where a between 1 and 4` - 注意：這會傳回 >= 1 和 <= 4，即 【1， 4】
+ `source = table | where b not between '2024-09-10' and '2025-09-10'` - 注意：這會傳回 b >= '\*\*\*\*\*\*\*\*\*\*' 和 b <= '2025-09-10'
+ `source = table | where cidrmatch(ip, '***********/24')`
+ `source = table | where cidrmatch(ipv6, '2003:db8::/32')`

```
source = table | eval status_category =
    case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
    else 'Incorrect HTTP status code')
    | where case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
    else 'Incorrect HTTP status code'
    ) = 'Incorrect HTTP status code'
```

```
source = table
    | eval factor = case(a > 15, a - 14, isnull(b), a - 7, a < 3, a + 1 else 1)
    | where case(factor = 2, 'even', factor = 4, 'even', factor = 6, 'even', factor = 8, 'even' else 'odd') = 'even'
    |  stats count() by factor
```

#### 欄位摘要
<a name="supported-ppl-field-summary-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `fieldsummary`命令來計算每個欄位的基本統計資料 （計數、相異計數、最小值、最大值、平均值、平均值），並判斷每個欄位的資料類型。此命令可與上述任何管道搭配使用，並將它們納入考量。

**語法**  
請使用下列語法。對於 CloudWatch Logs 使用案例，僅支援查詢中的一個欄位。

```
... | fieldsummary <field-list> (nulls=true/false)
```

**包含欄位**
+ 將統計資料收集到統一結果集的所有資料欄清單。

**Null**
+ 選用。
+  如果設定為 true，請在彙總計算中包含 null 值 （數值以 null 取代為零）。

**範例 1**  
PPL 查詢：

```
os> source = t | where status_code != 200 | fieldsummary includefields= status_code nulls=true
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| Fields           | COUNT       | COUNT_DISTINCT    |  MIN  |  MAX   |  AVG   |  MEAN   |        STDDEV       | NUlls | TYPEOF |
|------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| "status_code"    |      2      |         2         | 301   |   403  |  352.0 |  352.0  |  72.12489168102785  |  0    | "int"  |
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
```

**範例 2**  
PPL 查詢：

```
os> source = t | fieldsummary includefields= id, status_code, request_path nulls=true
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| Fields           | COUNT       | COUNT_DISTINCT    |  MIN  |  MAX   |  AVG   |  MEAN   |        STDDEV       | NUlls | TYPEOF |
|------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
|       "id"       |      6      |         6         | 1     |   6    |  3.5   |   3.5  |  1.8708286933869707  |  0    | "int"  |
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| "status_code"    |      4      |         3         | 200   |   403  |  184.0 |  184.0  |  161.16699413961905 |  2    | "int"  |
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| "request_path"   |      2      |         2         | /about| /home  |  0.0    |  0.0     |      0            |  2    |"string"|
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
```

#### expand 命令
<a name="supported-ppl-expand-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

使用 `expand`命令來扁平化 Array<Any> 或 Map<Any> 類型的欄位，為每個元素或鍵值對產生個別資料列。

**語法**  
使用下列語法：

```
expand <field> [As alias]
```

**field**
+ 要展開 （展開） 的欄位。
+ 欄位必須為支援的類型。

**別名**
+ 選用。
+ 要使用的名稱，而非原始欄位名稱。

**使用指引**  
expand 命令會為指定陣列或映射欄位中的每個元素產生資料列，其中：
+ 陣列元素會成為個別的資料列。
+ 映射索引鍵/值對會分成不同的資料列，每個索引鍵/值都以資料列表示。
+ 提供別名時，展開的值會以別名表示，而非原始欄位名稱。

您可以使用此命令搭配其他命令，例如 stats、eval 和 parse，來操作或擷取擴展後的資料。

**範例**
+ `source = table | expand employee | stats max(salary) as max by state, company `
+ `source = table | expand employee as worker | stats max(salary) as max by state, company `
+ `source = table | expand employee as worker | eval bonus = salary * 3 | fields worker, bonus` 
+ `source = table | expand employee | parse description '(?<email>.+@.+)' | fields employee, email` 
+ `source = table | eval array=json_array(1, 2, 3) | expand array as uid | fields name, occupation, uid `
+ `source = table | expand multi_valueA as multiA | expand multi_valueB as multiB` 

您可以使用 expand 命令搭配其他命令，例如 eval、stats 等。使用多個展開命令會為每個複合陣列或映射內的所有內部元素建立笛卡兒產品。

**有效的 SQL 下推查詢**  
expand 命令會使用 LATERAL VIEW explode 轉換為同等的 SQL 操作，以便在 SQL 查詢層級有效率地分解陣列或映射。

```
SELECT customer exploded_productId
FROM table
LATERAL VIEW explode(productId) AS exploded_productId
```

explode 命令提供下列功能：
+ 這是傳回新資料欄的資料欄操作。
+ 它會為分解欄中的每個元素建立新的資料列。
+ 內部 null 會被忽略為分解欄位的一部分 ( null 不會建立/分解任何資料列）。

#### PPL 函數
<a name="supported-ppl-functions-details"></a>

**Topics**
+ [PPL 條件函數](#supported-ppl-condition-functions)
+ [PPL 密碼編譯雜湊函數](#supported-ppl-cryptographic-functions)
+ [PPL 日期和時間函數](#supported-ppl-date-time-functions)
+ [PPL 表達式](#supported-ppl-expressions)
+ [PPL IP 地址函數](#supported-ppl-ip-address-functions)
+ [PPL JSON 函數](#supported-ppl-json-functions)
+ [PPL Lambda 函數](#supported-ppl-lambda-functions)
+ [PPL 數學函數](#supported-ppl-math-functions)
+ [PPL 字串函數](#supported-ppl-string-functions)
+ [PPL 類型轉換函數](#supported-ppl-type-conversion-functions)

##### PPL 條件函數
<a name="supported-ppl-condition-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### ISNULL
<a name="supported-ppl-condition-functions-isnull"></a>

**描述**：如果 欄位為 null，則`isnull(field)`傳回 true。

**引數類型：**
+ 所有支援的資料類型。

**傳回類型：**
+ BOOLEAN

**範例**：

```
os> source=accounts | eval result = isnull(employer) | fields result, employer, firstname
fetched rows / total rows = 4/4
+----------+-------------+-------------+
| result   | employer    | firstname   |
|----------+-------------+-------------|
| False    | AnyCompany  | Mary        |
| False    | ExampleCorp | Jane        |
| False    | ExampleOrg  | Nikki       |
| True     | null        | Juan        |
+----------+-------------+-------------+
```

##### ISNOTNULL
<a name="supported-ppl-condition-functions-isnotnull"></a>

**描述**：如果欄位不是 null，則`isnotnull(field)`傳回 true。

**引數類型：**
+ 所有支援的資料類型。

**傳回類型：**
+ BOOLEAN

**範例**：

```
os> source=accounts | where not isnotnull(employer) | fields account_number, employer
fetched rows / total rows = 1/1
+------------------+------------+
| account_number   | employer   |
|------------------+------------|
| 18               | null       |
+------------------+------------+
```

##### EXISTS
<a name="supported-ppl-condition-functions-exists"></a>

**範例**：

```
os> source=accounts | where exists(email) | fields account_number, email
fetched rows / total rows = 1/1
```

##### IFNULL
<a name="supported-ppl-condition-functions-ifnull"></a>

**描述**：`field2`如果 `field1`為 null，則`ifnull(field1, field2)`傳回 。

**引數類型：**
+ 所有支援的資料類型。
+ 如果兩個參數有不同的類型，則函數會失敗語意檢查。

**傳回類型：**
+ 任何

**範例**：

```
os> source=accounts | eval result = ifnull(employer, 'default') | fields result, employer, firstname
fetched rows / total rows = 4/4
+------------+------------+-------------+
| result     | employer   | firstname   |
|------------+------------+-------------|
| AnyCompany | AnyCompany | Mary        |
| ExampleCorp| ExampleCorp| Jane        |
| ExampleOrg | ExampleOrg | Nikki       |
| default    | null       | Juan        |
+------------+------------+-------------+
```

##### NULLIF
<a name="supported-ppl-condition-functions-nullif"></a>

**描述**：如果兩個參數相同，`nullif(field1, field2)`則傳回 null，否則傳回 field1。

**引數類型：**
+ 所有支援的資料類型。
+ 如果兩個參數有不同的類型，則函數會失敗語意檢查。

**傳回類型：**
+ 任何

**範例**：

```
os> source=accounts | eval result = nullif(employer, 'AnyCompany') | fields result, employer, firstname
fetched rows / total rows = 4/4
+----------------+----------------+-------------+
| result         | employer       | firstname   |
|----------------+----------------+-------------|
| null           | AnyCompany     | Mary        |
| ExampleCorp    | ExampleCorp    | Jane        |
| ExampleOrg     | ExampleOrg     | Nikki       |
| null           | null           | Juan        |
+----------------+----------------+-------------+
```

##### IF
<a name="supported-ppl-condition-functions-if"></a>

**描述**：`expr1`如果條件為 true，則`if(condition, expr1, expr2)`傳回 ，否則傳回 `expr2`。

**引數類型：**
+ 所有支援的資料類型。
+ 如果兩個參數有不同的類型，則函數會失敗語意檢查。

**傳回類型：**
+ 任何

**範例**：

```
os> source=accounts | eval result = if(true, firstname, lastname) | fields result, firstname, lastname
fetched rows / total rows = 4/4
+----------+-------------+----------+
| result   | firstname | lastname   |
|----------+-------------+----------|
| Jane     | Jane      | Doe        |
| Mary     | Mary      | Major      |
| Pat      | Pat       | Candella   |
| Dale     | Jorge     | Souza      |
+----------+-----------+------------+

os> source=accounts | eval result = if(false, firstname, lastname) | fields result, firstname, lastname
fetched rows / total rows = 4/4
+----------+-------------+------------+
| result   | firstname   | lastname   |
|----------+-------------+------------|
| Doe      | Jane        | Doe        |
| Major    | Mary        | Major      |
| Candella | Pat         | Candella   |
| Souza    | Jorge       | Souza      |
+----------+-------------+------------+

os> source=accounts | eval is_vip = if(age > 30 AND isnotnull(employer), true, false) | fields is_vip, firstname, lastname
fetched rows / total rows = 4/4
+----------+-------------+------------+
| is_vip   | firstname   | lastname   |
|----------+-------------+------------|
| True     | Jane        | Doe        |
| True     | Mary        | Major      |
| False    | Pat         | Candella   |
| False    | Jorge       | Souza      |
+----------+-------------+------------+
```

##### PPL 密碼編譯雜湊函數
<a name="supported-ppl-cryptographic-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### MD5
<a name="supported-ppl-cryptographic-functions-md5"></a>

MD5 會計算 MD5 摘要，並以 32 個字元的十六進位字串傳回值。

**用量**： `md5('hello')`

**引數類型：**
+ STRING

**傳回類型：**
+ STRING

**範例**：

```
os> source=people | eval `MD5('hello')` = MD5('hello') | fields `MD5('hello')`
fetched rows / total rows = 1/1
+----------------------------------+
| MD5('hello')                     |
|----------------------------------|
| <32 character hex string>        |
+----------------------------------+
```

##### SHA1
<a name="supported-ppl-cryptographic-functions-sha1"></a>

SHA1 傳回 SHA-1 的十六進位字串結果。

**用量**： `sha1('hello')`

**引數類型：**
+ STRING

**傳回類型：**
+ STRING

**範例**：

```
os> source=people | eval `SHA1('hello')` = SHA1('hello') | fields `SHA1('hello')`
fetched rows / total rows = 1/1
+------------------------------------------+
| SHA1('hello')                            |
|------------------------------------------|
| <40-character SHA-1 hash result>         |
+------------------------------------------+
```

##### SHA2
<a name="supported-ppl-cryptographic-functions-sha2"></a>

SHA2 傳回 SHA-2 系列雜湊函數 (SHA-224、SHA-256、SHA-384 和 SHA-512) 的十六進位字串結果。numBits 表示結果的所需位元長度，其值必須為 224、256、384、512

**用法：**
+ `sha2('hello',256)`
+ `sha2('hello',512)`

**引數類型：**
+ STRING、INTEGER

**傳回類型：**
+ STRING

**範例**：

```
os> source=people | eval `SHA2('hello',256)` = SHA2('hello',256) | fields `SHA2('hello',256)`
fetched rows / total rows = 1/1
+------------------------------------------------------------------+
| SHA2('hello',256)                                                |
|------------------------------------------------------------------|
| <64-character SHA-256 hash result>                               |
+------------------------------------------------------------------+

os> source=people | eval `SHA2('hello',512)` = SHA2('hello',512) | fields `SHA2('hello',512)`
fetched rows / total rows = 1/1
+------------------------------------------------------------------+
| SHA2('hello',512)                                                |                                                                |
|------------------------------------------------------------------|
| <128-character SHA-512 hash result>                              |
+------------------------------------------------------------------+
```

##### PPL 日期和時間函數
<a name="supported-ppl-date-time-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `DAY`
<a name="supported-ppl-date-time-functions-day"></a>

**用量**： `DAY(date)`擷取日期的月份日期，範圍介於 1 到 31。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**：`DAYOFMONTH`、 `DAY_OF_MONTH`

**範例**：

```
os> source=people | eval `DAY(DATE('2020-08-26'))` = DAY(DATE('2020-08-26')) | fields `DAY(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------+
| DAY(DATE('2020-08-26'))   |
|---------------------------|
| 26                        |
+---------------------------+
```

##### `DAYOFMONTH`
<a name="supported-ppl-date-time-functions-dayofmonth"></a>

**用量**： `DAYOFMONTH(date)`擷取日期的月份日期，範圍介於 1 到 31。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**：`DAY`、 `DAY_OF_MONTH`

**範例**：

```
os> source=people | eval `DAYOFMONTH(DATE('2020-08-26'))` = DAYOFMONTH(DATE('2020-08-26')) | fields `DAYOFMONTH(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+----------------------------------+
| DAYOFMONTH(DATE('2020-08-26'))   |
|----------------------------------|
| 26                               |
+----------------------------------+
```

##### `DAY_OF_MONTH`
<a name="supported-ppl-date-time-functions-day-of-month"></a>

**用量**： `DAY_OF_MONTH(DATE)`擷取日期的月份日期，範圍介於 1 到 31。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**：`DAY`、 `DAYOFMONTH`

**範例**：

```
os> source=people | eval `DAY_OF_MONTH(DATE('2020-08-26'))` = DAY_OF_MONTH(DATE('2020-08-26')) | fields `DAY_OF_MONTH(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+------------------------------------+
| DAY_OF_MONTH(DATE('2020-08-26'))   |
|------------------------------------|
| 26                                 |
+------------------------------------+
```

##### `DAYOFWEEK`
<a name="supported-ppl-date-time-functions-dayofweek"></a>

**用量**：`DAYOFWEEK(DATE)`傳回日期的工作日索引 (1 = 星期日，2 = 星期一，...，7 = 星期六）。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `DAY_OF_WEEK`

**範例**：

```
os> source=people | eval `DAYOFWEEK(DATE('2020-08-26'))` = DAYOFWEEK(DATE('2020-08-26')) | fields `DAYOFWEEK(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------------+
| DAYOFWEEK(DATE('2020-08-26'))   |
|---------------------------------|
| 4                               |
+---------------------------------+
```

##### `DAY_OF_WEEK`
<a name="supported-ppl-date-time-functions-day-of-week"></a>

**用量**：`DAY_OF_WEEK(DATE)`傳回日期的工作日索引 (1 = 星期日，2 = 星期一，...，7 = 星期六）。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `DAYOFWEEK`

**範例**：

```
os> source=people | eval `DAY_OF_WEEK(DATE('2020-08-26'))` = DAY_OF_WEEK(DATE('2020-08-26')) | fields `DAY_OF_WEEK(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-----------------------------------+
| DAY_OF_WEEK(DATE('2020-08-26'))   |
|-----------------------------------|
| 4                                 |
+-----------------------------------+
```

##### `DAYOFYEAR`
<a name="supported-ppl-date-time-functions-dayofyear"></a>

**用量**：`DAYOFYEAR(DATE)`傳回日期的年份日期，範圍介於 1 到 366。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `DAY_OF_YEAR`

**範例**：

```
os> source=people | eval `DAYOFYEAR(DATE('2020-08-26'))` = DAYOFYEAR(DATE('2020-08-26')) | fields `DAYOFYEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------------+
| DAYOFYEAR(DATE('2020-08-26'))   |
|---------------------------------|
| 239                             |
+---------------------------------+
```

##### `DAY_OF_YEAR`
<a name="supported-ppl-date-time-functions-day-of-year"></a>

**用量**：`DAY_OF_YEAR(DATE)`傳回日期的年份日期，範圍介於 1 到 366。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `DAYOFYEAR`

**範例**：

```
os> source=people | eval `DAY_OF_YEAR(DATE('2020-08-26'))` = DAY_OF_YEAR(DATE('2020-08-26')) | fields `DAY_OF_YEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-----------------------------------+
| DAY_OF_YEAR(DATE('2020-08-26'))   |
|-----------------------------------|
| 239                               |
+-----------------------------------+
```

##### `DAYNAME`
<a name="supported-ppl-date-time-functions-dayname"></a>

**用量**： `DAYNAME(DATE)` 傳回日期的工作日名稱，包括星期一、星期二、星期三、星期四、星期五、星期六和星期日。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：STRING

**範例**：

```
os> source=people | eval `DAYNAME(DATE('2020-08-26'))` = DAYNAME(DATE('2020-08-26')) | fields `DAYNAME(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-------------------------------+
| DAYNAME(DATE('2020-08-26'))   |
|-------------------------------|
| Wednesday                     |
+-------------------------------+
```

##### `FROM_UNIXTIME`
<a name="supported-ppl-date-time-functions-from-unixtime"></a>

**用量**：`FROM_UNIXTIME`傳回指定為時間戳記或字元字串值之引數的表示法。此函數會執行`UNIX_TIMESTAMP`函數的反向轉換。

如果您提供第二個引數， `FROM_UNIXTIME` 會使用它來格式化類似於 `DATE_FORMAT`函數的結果。

如果時間戳記不在 1970-01-01 00：00：00 到 3001-01-18 23：59：59.999999 (0 到 32536771199.999999 epoch 時間） 的範圍內，函數會傳回 `NULL`。

**引數類型**：DOUBLE、STRING

**傳回類型映射**：

DOUBLE -> TIMESTAMP

DOUBLE、STRING -> STRING

**範例**：

```
os> source=people | eval `FROM_UNIXTIME(1220249547)` = FROM_UNIXTIME(1220249547) | fields `FROM_UNIXTIME(1220249547)`
fetched rows / total rows = 1/1
+-----------------------------+
| FROM_UNIXTIME(1220249547)   |
|-----------------------------|
| 2008-09-01 06:12:27         |
+-----------------------------+

os> source=people | eval `FROM_UNIXTIME(1220249547, 'HH:mm:ss')` = FROM_UNIXTIME(1220249547, 'HH:mm:ss') | fields `FROM_UNIXTIME(1220249547, 'HH:mm:ss')`
fetched rows / total rows = 1/1
+-----------------------------------------+
| FROM_UNIXTIME(1220249547, 'HH:mm:ss')   |
|-----------------------------------------|
| 06:12:27                                |
+-----------------------------------------+
```

##### `HOUR`
<a name="supported-ppl-date-time-functions-hour"></a>

**用量**： `HOUR(TIME)` 擷取時間的小時值。

與一天中的標準時間不同，此函數中的時間值的範圍可以大於 23。因此， 的傳回值`HOUR(TIME)`可以大於 23。

**引數類型**：STRING/TIME/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `HOUR_OF_DAY`

**範例**：

```
os> source=people | eval `HOUR(TIME('01:02:03'))` = HOUR(TIME('01:02:03')) | fields `HOUR(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+--------------------------+
| HOUR(TIME('01:02:03'))   |
|--------------------------|
| 1                        |
+--------------------------+
```

##### `HOUR_OF_DAY`
<a name="supported-ppl-date-time-functions-hour-of-day"></a>

**用量**：從指定時間`HOUR_OF_DAY(TIME)`擷取小時值。

與一天中的標準時間不同，此函數中的時間值的範圍可以大於 23。因此， 的傳回值`HOUR_OF_DAY(TIME)`可以大於 23。

**引數類型**：STRING/TIME/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `HOUR`

**範例**：

```
os> source=people | eval `HOUR_OF_DAY(TIME('01:02:03'))` = HOUR_OF_DAY(TIME('01:02:03')) | fields `HOUR_OF_DAY(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+---------------------------------+
| HOUR_OF_DAY(TIME('01:02:03'))   |
|---------------------------------|
| 1                               |
+---------------------------------+
```

##### `LAST_DAY`
<a name="supported-ppl-date-time-functions-last-day"></a>

**用量**： `LAST_DAY` 傳回當月的最後一天，做為指定日期引數的 DATE 值。

**引數類型**：DATE/STRING/TIMESTAMP/TIME

**傳回類型**：DATE

**範例**：

```
os> source=people | eval `last_day('2023-02-06')` = last_day('2023-02-06') | fields `last_day('2023-02-06')`
fetched rows / total rows = 1/1
+--------------------------+
| last_day('2023-02-06')   |
|--------------------------|
| 2023-02-28               |
+--------------------------+
```

##### `LOCALTIMESTAMP`
<a name="supported-ppl-date-time-functions-localtimestamp"></a>

**用量**： `LOCALTIMESTAMP()` 是 的同義詞`NOW()`。

**範例**：

```
> source=people | eval `LOCALTIMESTAMP()` = LOCALTIMESTAMP() | fields `LOCALTIMESTAMP()`
fetched rows / total rows = 1/1
+---------------------+
| LOCALTIMESTAMP()    |
|---------------------|
| 2022-08-02 15:54:19 |
+---------------------+
```

##### `LOCALTIME`
<a name="supported-ppl-date-time-functions-localtime"></a>

**用量**： `LOCALTIME()` 是 的同義詞`NOW()`。

**範例**：

```
> source=people | eval `LOCALTIME()` = LOCALTIME() | fields `LOCALTIME()`
fetched rows / total rows = 1/1
+---------------------+
| LOCALTIME()         |
|---------------------|
| 2022-08-02 15:54:19 |
+---------------------+
```

##### `MAKE_DATE`
<a name="supported-ppl-date-time-functions-make-date"></a>

**用量**： 會根據指定的年、月和日值`MAKE_DATE`傳回日期值。所有引數都會四捨五入為整數。

**規格**：1. MAKE\_DATE（整數、整數、整數） -> 日期

**引數類型**：INTEGER、INTEGER、INTEGER

**傳回類型**：DATE

**範例**：

```
os> source=people | eval `MAKE_DATE(1945, 5, 9)` = MAKEDATE(1945, 5, 9) | fields `MAKEDATE(1945, 5, 9)`
fetched rows / total rows = 1/1
+------------------------+
| MAKEDATE(1945, 5, 9)   |
|------------------------|
| 1945-05-09             |
+------------------------+
```

##### `MINUTE`
<a name="supported-ppl-date-time-functions-minute"></a>

**用量**： `MINUTE(TIME)` 傳回指定時間的分鐘元件，以 0 到 59 範圍內的整數表示。

**引數類型**：STRING/TIME/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `MINUTE_OF_HOUR`

**範例**：

```
os> source=people | eval `MINUTE(TIME('01:02:03'))` =  MINUTE(TIME('01:02:03')) | fields `MINUTE(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+----------------------------+
| MINUTE(TIME('01:02:03'))   |
|----------------------------|
| 2                          |
+----------------------------+
```

##### `MINUTE_OF_HOUR`
<a name="supported-ppl-date-time-functions-minute-of-hour"></a>

**用量**： `MINUTE_OF_HOUR(TIME)` 傳回指定時間的分鐘元件，以 0 到 59 範圍內的整數表示。

**引數類型**：STRING/TIME/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `MINUTE`

**範例**：

```
os> source=people | eval `MINUTE_OF_HOUR(TIME('01:02:03'))` =  MINUTE_OF_HOUR(TIME('01:02:03')) | fields `MINUTE_OF_HOUR(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+------------------------------------+
| MINUTE_OF_HOUR(TIME('01:02:03'))   |
|------------------------------------|
| 2                                  |
+------------------------------------+
```

##### `MONTH`
<a name="supported-ppl-date-time-functions-month"></a>

**用量**：以整數`MONTH(DATE)`傳回指定日期的月份，範圍介於 1 到 12 （其中 1 代表 1 月，12 代表 12 月）。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `MONTH_OF_YEAR`

**範例**：

```
os> source=people | eval `MONTH(DATE('2020-08-26'))` =  MONTH(DATE('2020-08-26')) | fields `MONTH(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-----------------------------+
| MONTH(DATE('2020-08-26'))   |
|-----------------------------|
| 8                           |
+-----------------------------+
```

##### `MONTHNAME`
<a name="supported-ppl-date-time-functions-monthname"></a>

**用量**：以整數`MONTHNAME(DATE)`傳回指定日期的月份，範圍介於 1 到 12 （其中 1 代表 1 月，12 代表 12 月）。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `MONTH_OF_YEAR`

**範例**：

```
os> source=people | eval `MONTHNAME(DATE('2020-08-26'))` = MONTHNAME(DATE('2020-08-26')) | fields `MONTHNAME(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------------+
| MONTHNAME(DATE('2020-08-26'))   |
|---------------------------------|
| August                          |
+---------------------------------+
```

##### `MONTH_OF_YEAR`
<a name="supported-ppl-date-time-functions-month-of-year"></a>

**用量**：以整數`MONTH_OF_YEAR(DATE)`傳回指定日期的月份，範圍介於 1 到 12 （其中 1 代表 1 月，12 代表 12 月）。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `MONTH`

**範例**：

```
os> source=people | eval `MONTH_OF_YEAR(DATE('2020-08-26'))` =  MONTH_OF_YEAR(DATE('2020-08-26')) | fields `MONTH_OF_YEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-------------------------------------+
| MONTH_OF_YEAR(DATE('2020-08-26'))   |
|-------------------------------------|
| 8                                   |
+-------------------------------------+
```

##### `NOW`
<a name="supported-ppl-date-time-functions-now"></a>

**用量**： 以 'YYYY-MM-DD hh：mm：ss' 格式`TIMESTAMP`的值`NOW`傳回目前的日期和時間。此值以叢集時區表示。

**注意**  
`NOW()` 會傳回常數時間，指出陳述式何時開始執行。這與 不同`SYSDATE()`，它會傳回確切的執行時間。

**傳回類型**：TIMESTAMP

**規格**：NOW() -> TIMESTAMP

**範例**：

```
os> source=people | eval `value_1` = NOW(), `value_2` = NOW() | fields `value_1`, `value_2`
fetched rows / total rows = 1/1
+---------------------+---------------------+
| value_1             | value_2             |
|---------------------+---------------------|
| 2022-08-02 15:39:05 | 2022-08-02 15:39:05 |
+---------------------+---------------------+
```

##### `QUARTER`
<a name="supported-ppl-date-time-functions-quarter"></a>

**用量**： `QUARTER(DATE)`傳回指定日期的年份季度為整數，範圍介於 1 到 4。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**範例**：

```
os> source=people | eval `QUARTER(DATE('2020-08-26'))` = QUARTER(DATE('2020-08-26')) | fields `QUARTER(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-------------------------------+
| QUARTER(DATE('2020-08-26'))   |
|-------------------------------|
| 3                             |
+-------------------------------+
```

##### `SECOND`
<a name="supported-ppl-date-time-functions-second"></a>

**用量**： `SECOND(TIME)` 以整數傳回指定時間的第二個元件，範圍介於 0 到 59。

**引數類型**：STRING/TIME/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `SECOND_OF_MINUTE`

**範例**：

```
os> source=people | eval `SECOND(TIME('01:02:03'))` = SECOND(TIME('01:02:03')) | fields `SECOND(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+----------------------------+
| SECOND(TIME('01:02:03'))   |
|----------------------------|
| 3                          |
+----------------------------+
```

##### `SECOND_OF_MINUTE`
<a name="supported-ppl-date-time-functions-second-of-minute"></a>

**用量**： 以整數`SECOND_OF_MINUTE(TIME)`傳回指定時間的第二個元件，範圍介於 0 到 59。

**引數類型**：STRING/TIME/TIMESTAMP

**傳回類型**：INTEGER

**同義詞**： `SECOND`

**範例**：

```
os> source=people | eval `SECOND_OF_MINUTE(TIME('01:02:03'))` = SECOND_OF_MINUTE(TIME('01:02:03')) | fields `SECOND_OF_MINUTE(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+--------------------------------------+
| SECOND_OF_MINUTE(TIME('01:02:03'))   |
|--------------------------------------|
| 3                                    |
+--------------------------------------+
```

##### `SUBDATE`
<a name="supported-ppl-date-time-functions-subdate"></a>

**用量**：從指定日期`SUBDATE(DATE, DAYS)`減去第二個引數 （例如 `DATE`或 `DAYS`)。

**引數類型**：DATE/TIMESTAMP、LONG

**傳回類型映射**：(DATE、LONG) -> DATE

**Antonyms**： `ADDDATE`

**範例**：

```
os> source=people | eval `'2008-01-02' - 31d` = SUBDATE(DATE('2008-01-02'), 31), `'2020-08-26' - 1` = SUBDATE(DATE('2020-08-26'), 1), `ts '2020-08-26 01:01:01' - 1` = SUBDATE(TIMESTAMP('2020-08-26 01:01:01'), 1) | fields `'2008-01-02' - 31d`, `'2020-08-26' - 1`, `ts '2020-08-26 01:01:01' - 1`
fetched rows / total rows = 1/1
+----------------------+--------------------+--------------------------------+
| '2008-01-02' - 31d   | '2020-08-26' - 1   | ts '2020-08-26 01:01:01' - 1   |
|----------------------+--------------------+--------------------------------|
| 2007-12-02 00:00:00  | 2020-08-25         | 2020-08-25 01:01:01            |
+----------------------+--------------------+--------------------------------+
```

##### `SYSDATE`
<a name="supported-ppl-date-time-functions-sysdate"></a>

**用量**： 以 'YYYY-MM-DD hh：mm：ss.nnnnnn' 格式`TIMESTAMP`的值`SYSDATE()`傳回目前的日期和時間。

`SYSDATE()`會傳回其執行的確切時間。這與 NOW() 不同，它會傳回常數時間，指出陳述式何時開始執行。

**選用引數類型**：INTEGER (0 到 6) - 指定傳回值中分數秒的位數。

**傳回類型**：TIMESTAMP

**範例**：

```
os> source=people | eval `SYSDATE()` = SYSDATE() | fields `SYSDATE()`
fetched rows / total rows = 1/1
+----------------------------+
| SYSDATE()                  |
|----------------------------|
| 2022-08-02 15:39:05.123456 |
+----------------------------+
```

##### `TIMESTAMP`
<a name="supported-ppl-date-time-functions-timestamp"></a>

**用量**： `TIMESTAMP(EXPR)` 建構時間戳記類型，並以輸入字串`expr`做為時間戳記。

使用單一引數， `TIMESTAMP(expr)` 會從輸入建構時間戳記。如果 `expr` 是字串，則會解譯為時間戳記。對於非字串引數，函數`expr`會使用 UTC 時區轉換為時間戳記。當 `expr` 是`TIME`值時，函數會在轉換之前套用今天的日期。

與兩個引數搭配使用時， 會將時間表達式 (`expr2`) `TIMESTAMP(expr1, expr2)`新增至日期或時間戳記表達式 (`expr1`)，並將結果傳回為時間戳記值。

**引數類型**：STRING/DATE/TIME/TIMESTAMP

**傳回類型映射**：

(STRING/DATE/TIME/時間戳記） -> 時間戳記

(STRING/DATE/TIME/TIMESTAMP、STRING/DATE/TIME/TIMESTAMP) -> 時間戳記

**範例**：

```
os> source=people | eval `TIMESTAMP('2020-08-26 13:49:00')` = TIMESTAMP('2020-08-26 13:49:00'), `TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42'))` = TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42')) | fields `TIMESTAMP('2020-08-26 13:49:00')`, `TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42'))`
fetched rows / total rows = 1/1
+------------------------------------+------------------------------------------------------+
| TIMESTAMP('2020-08-26 13:49:00')   | TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42'))   |
|------------------------------------+------------------------------------------------------|
| 2020-08-26 13:49:00                | 2020-08-27 02:04:42                                  |
+------------------------------------+------------------------------------------------------+
```

##### `UNIX_TIMESTAMP`
<a name="supported-ppl-date-time-functions-unix-timestamp"></a>

**用量**： 將指定日期引數`UNIX_TIMESTAMP`轉換為 Unix 時間 （自 1970 年初開始的 Epoch 起的秒數）。如果未提供引數，則會傳回目前的 Unix 時間。

日期引數可以是 `DATE`、`TIMESTAMP`字串或下列其中一種格式的數字：`YYMMDD`、`YYYYMMDD`、 `YYMMDDhhmmss`或 `YYYYMMDDhhmmss`。如果引數包含時間元件，則可能選擇性地包含小數秒。

如果引數的格式無效，或超出 1970-01-01 00：00：00 到 3001-01-18 23：59：59.999999 (0 到 32536771199.999999) 的範圍，則函數會傳回 `NULL`。

函數接受 `DATE`、 `TIMESTAMP`或 `DOUBLE`作為引數類型，或不接受引數。它一律會傳回代表 Unix 時間戳記`DOUBLE`的值。

對於反向轉換，您可以使用 FROM\_UNIXTIME 函數。

**引數類型**：<NONE>/DOUBLE/DATE/TIMESTAMP

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `UNIX_TIMESTAMP(double)` = UNIX_TIMESTAMP(20771122143845), `UNIX_TIMESTAMP(timestamp)` = UNIX_TIMESTAMP(TIMESTAMP('1996-11-15 17:05:42')) | fields `UNIX_TIMESTAMP(double)`, `UNIX_TIMESTAMP(timestamp)`
fetched rows / total rows = 1/1
+--------------------------+-----------------------------+
| UNIX_TIMESTAMP(double)   | UNIX_TIMESTAMP(timestamp)   |
|--------------------------+-----------------------------|
| 3404817525.0             | 848077542.0                 |
+--------------------------+-----------------------------+
```

##### `WEEK`
<a name="supported-ppl-date-time-functions-week"></a>

**用量**：`WEEK(DATE)`傳回指定日期的週數。

**引數類型**：DATE/TIMESTAMP/STRING

**傳回類型**：INTEGER

**同義詞**： `WEEK_OF_YEAR`

**範例**：

```
os> source=people | eval `WEEK(DATE('2008-02-20'))` = WEEK(DATE('2008-02-20')) | fields `WEEK(DATE('2008-02-20'))`
fetched rows / total rows = 1/1
+----------------------------+
| WEEK(DATE('2008-02-20'))   |
|----------------------------|
| 8                          |
+----------------------------+
```

##### `WEEKDAY`
<a name="supported-ppl-date-time-functions-weekday"></a>

**用量**：`WEEKDAY(DATE)`傳回日期的工作日索引 (0 = 星期一，1 = 星期二，...，6 = 星期日）。

它類似於 `dayofweek`函數，但每天會傳回不同的索引。

**引數類型**：STRING/DATE/TIME/TIMESTAMP

**傳回類型**：INTEGER

**範例**：

```
os> source=people | eval `weekday(DATE('2020-08-26'))` = weekday(DATE('2020-08-26')) | eval `weekday(DATE('2020-08-27'))` = weekday(DATE('2020-08-27')) | fields `weekday(DATE('2020-08-26'))`, `weekday(DATE('2020-08-27'))`
fetched rows / total rows = 1/1
+-------------------------------+-------------------------------+
| weekday(DATE('2020-08-26'))   | weekday(DATE('2020-08-27'))   |
|-------------------------------+-------------------------------|
| 2                             | 3                             |
+-------------------------------+-------------------------------+
```

##### `WEEK_OF_YEAR`
<a name="supported-ppl-date-time-functions-week-of-year"></a>

**用量**：`WEEK_OF_YEAR(DATE)`傳回指定日期的週數。

**引數類型**：DATE/TIMESTAMP/STRING

**傳回類型**：INTEGER

**同義詞**： `WEEK`

**範例**：

```
os> source=people | eval `WEEK_OF_YEAR(DATE('2008-02-20'))` = WEEK(DATE('2008-02-20'))| fields `WEEK_OF_YEAR(DATE('2008-02-20'))`
fetched rows / total rows = 1/1
+------------------------------------+
| WEEK_OF_YEAR(DATE('2008-02-20'))   |
|------------------------------------|
| 8                                  |
+------------------------------------+
```

##### `YEAR`
<a name="supported-ppl-date-time-functions-year"></a>

**用量**： `YEAR(DATE)`傳回日期的年份，範圍介於 1000 到 9999 之間，或傳回 "zero" 日期的年份。

**引數類型**：STRING/DATE/TIMESTAMP

**傳回類型**：INTEGER

**範例**：

```
os> source=people | eval `YEAR(DATE('2020-08-26'))` = YEAR(DATE('2020-08-26')) | fields `YEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+----------------------------+
| YEAR(DATE('2020-08-26'))   |
|----------------------------|
| 2020                       |
+----------------------------+
```

##### `DATE_ADD`
<a name="supported-ppl-date-time-functions-date-add"></a>

**用量**： 會將指定的間隔`DATE_ADD(date, INTERVAL expr unit)`新增至指定的日期。

**引數類型**：DATE、INTERVAL

**傳回類型**：DATE

**Antonyms**： `DATE_SUB`

**範例**：

```
os> source=people | eval `'2020-08-26' + 1d` = DATE_ADD(DATE('2020-08-26'), INTERVAL 1 DAY) | fields `'2020-08-26' + 1d`
fetched rows / total rows = 1/1
+---------------------+
| '2020-08-26' + 1d   |
|---------------------|
| 2020-08-27          |
+---------------------+
```

##### `DATE_SUB`
<a name="supported-ppl-date-time-functions-date-sub"></a>

**用量**：從日期`DATE_SUB(date, INTERVAL expr unit)`減去間隔 expr。

**引數類型**：DATE、INTERVAL

**傳回類型**：DATE

**Antonyms**： `DATE_ADD`

**範例**：

```
os> source=people | eval `'2008-01-02' - 31d` = DATE_SUB(DATE('2008-01-02'), INTERVAL 31 DAY) | fields `'2008-01-02' - 31d`
fetched rows / total rows = 1/1
+---------------------+
| '2008-01-02' - 31d  |
|---------------------|
| 2007-12-02          |
+---------------------+
```

##### `TIMESTAMPADD`
<a name="supported-ppl-date-time-functions-timestampadd"></a>

**用量**：在將指定時間間隔新增至指定日期後傳回`TIMESTAMP`值。

**引數**：
+ 間隔：Interval （秒、分鐘、小時、日、週、月、季度、年） 
+ 整數：INTEGER 
+ 日期：DATE、TIMESTAMP 或 STRING

如果您提供 `STRING`做為日期引數，請將其格式化為有效的 `TIMESTAMP`。函數會自動將`DATE`引數轉換為 `TIMESTAMP`。

**範例**：

```
os> source=people | eval `TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00')` = TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00') | eval `TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00')` = TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00') | fields `TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00')`, `TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00')`
fetched rows / total rows = 1/1
+----------------------------------------------+--------------------------------------------------+
| TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00') | TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00') |
|----------------------------------------------+--------------------------------------------------|
| 2000-01-18 00:00:00                          | 1999-10-01 00:00:00                              |
+----------------------------------------------+--------------------------------------------------+
```

##### `TIMESTAMPDIFF`
<a name="supported-ppl-date-time-functions-timestampdiff"></a>

**用量**：以指定的間隔單位`TIMESTAMPDIFF(interval, start, end)`傳回開始和結束日期/時間之間的差異。

**引數**：
+ 間隔：Interval （秒、分鐘、小時、日、週、月、季度、年） 
+ start：DATE、TIMESTAMP 或 STRING 
+ 結束：DATE、TIMESTAMP 或 STRING

函數會在適當`TIMESTAMP`時自動將引數轉換為 。將`STRING`引數格式化為有效的 `TIMESTAMP`。

**範例**：

```
os> source=people | eval `TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00')` = TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00') | eval `TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00'))` = TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00')) | fields `TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00')`, `TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00'))`
fetched rows / total rows = 1/1
+-------------------------------------------------------------------+-------------------------------------------------------------------------------------------+
| TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00') | TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00')) |
|-------------------------------------------------------------------+-------------------------------------------------------------------------------------------|
| 4                                                                 | -23                                                                                       |
+-------------------------------------------------------------------+-------------------------------------------------------------------------------------------+
```

##### `UTC_TIMESTAMP`
<a name="supported-ppl-date-time-functions-utc-timestamp"></a>

**用量**： 以 'YYYY-MM-DD hh：mm：ss' 的值`UTC_TIMESTAMP`傳回目前的 UTC 時間戳記。

**傳回類型**：TIMESTAMP

**規格**：UTC\_TIMESTAMP() -> TIMESTAMP

**範例**：

```
> source=people | eval `UTC_TIMESTAMP()` = UTC_TIMESTAMP() | fields `UTC_TIMESTAMP()`
fetched rows / total rows = 1/1
+---------------------+
| UTC_TIMESTAMP()     |
|---------------------|
| 2022-10-03 17:54:28 |
+---------------------+
```

##### `CURRENT_TIMEZONE`
<a name="supported-ppl-date-time-functions-current-timezone"></a>

**用量**：`CURRENT_TIMEZONE`傳回目前的本機時區。

**傳回類型**：STRING

**範例**：

```
> source=people | eval `CURRENT_TIMEZONE()` = CURRENT_TIMEZONE() | fields `CURRENT_TIMEZONE()`
fetched rows / total rows = 1/1
+------------------------+
| CURRENT_TIMEZONE()     |
|------------------------|
| America/Chicago        |
+------------------------+
```

##### PPL 表達式
<a name="supported-ppl-expressions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

運算式，特別是值運算式，會傳回純量值。表達式有不同的類型和形式。例如，有常值作為原子表達式和算術、述詞和函數表達式建置在上面。您可以在不同的子句中使用表達式，例如在 `Filter`和 `Stats`命令中使用算術表達式。

**運算子**

算術表達式是由數值常值和二進位算術運算子形成的表達式，如下所示：

1. `+`：新增。

1. `-`：減去。

1. `*`：乘以。

1. `/`：除以 （對於整數，結果是捨棄分數部分的整數）

1. `%`：Modulo （僅與整數搭配使用；結果是分割的其餘部分）

**優先順序**

使用括號來控制算術運算子的優先順序。否則，會先執行優先順序較高的運算子。

**類型轉換**

查詢運算子簽章時，會執行隱含類型轉換。例如，實數`+`的整數會比對`+(double,double)`產生實數的簽章。此規則也適用於函數呼叫。

不同類型的算術表達式範例：

```
os> source=accounts | where age > (25 + 5) | fields age ;
fetched rows / total rows = 3/3
+-------+
| age   |
|-------|
| 32    |
| 36    |
| 33    |
+-------+
```

**述詞運算子**  
述詞運算子是評估為 true 的表達式。`MISSING` 和 `NULL`值比較遵循下列規則：
+ `MISSING` 值僅等於`MISSING`值，且小於其他值。
+ `NULL` 值等於`NULL`值、大於`MISSING`值，但小於所有其他值。

**運算子**


**述詞運算子**  

| 名稱 | 描述 | 
| --- | --- | 
| > | 大於運算子 | 
| >= | 大於或等於運算子 | 
| < | 小於運算子 | 
| \!= | 不等於運算子 | 
| <= | 小於或等於運算子 | 
| = | 等於運算子 | 
| LIKE | 簡單模式比對 | 
| IN | NULL 值測試 | 
| AND | AND 運算子 | 
| OR | OR 運算子 | 
| XOR | XOR 運算子 | 
| NOT | NOT NULL 值測試 | 

您可以比較日期時間。比較不同的日期時間類型 （例如 `DATE`和 `TIME`) 時，兩者都會轉換為 `DATETIME`。下列規則適用於轉換：
+  `TIME` 適用於今天的日期。
+ `DATE` 會在午夜解譯。

**基本述詞運算子**  
比較運算子的範例：

```
os> source=accounts | where age > 33 | fields age ;
fetched rows / total rows = 1/1
+-------+
| age   |
|-------|
| 36    |
+-------+
```

**`IN`**  
值清單中運算`IN`子測試欄位的範例：

```
os> source=accounts | where age in (32, 33) | fields age ;
fetched rows / total rows = 2/2
+-------+
| age   |
|-------|
| 32    |
| 33    |
+-------+
```

**`OR`**  
`OR` 運算子的範例：

```
os> source=accounts | where age = 32 OR age = 33 | fields age ;
fetched rows / total rows = 2/2
+-------+
| age   |
|-------|
| 32    |
| 33    |
+-------+
```

**`NOT`**  
`NOT` 運算子的範例：

```
os> source=accounts | where age not in (32, 33) | fields age ;
fetched rows / total rows = 2/2
+-------+
| age   |
|-------|
| 36    |
| 28    |
+-------+
```

##### PPL IP 地址函數
<a name="supported-ppl-ip-address-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `CIDRMATCH`
<a name="supported-ppl-address-functions-cidrmatch"></a>

**用量**：`CIDRMATCH(ip, cidr)`檢查指定的 IP 地址是否在指定的 cidr 範圍內。

**引數類型：**
+ STRING、STRING
+ 傳回類型：BOOLEAN

**範例**：

```
os> source=ips | where cidrmatch(ip, '***********/24') | fields ip
fetched rows / total rows = 1/1
+--------------+
| ip           |
|--------------|
| ***********  |
+--------------+

os> source=ipsv6 | where cidrmatch(ip, '2003:db8::/32') | fields ip
fetched rows / total rows = 1/1
+-----------------------------------------+
| ip                                      |
|-----------------------------------------|
| 2003:0db8:****:****:****:****:****:0000 |
+-----------------------------------------+
```

**注意**  
`ip` 可以是 IPv4 或 IPv6 地址。
`cidr` 可以是 IPv4 或 IPv6 區塊。
`ip` 和 `cidr` 必須是 IPv4 或 IPv6。
`ip` 和 `cidr` 都必須有效且非空白/非空。

##### PPL JSON 函數
<a name="supported-ppl-json-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `JSON`
<a name="supported-ppl-json-functions-json"></a>

**用量**： 會`json(value)`評估字串是否可以剖析為 JSON 格式。如果原始字串是有效的 JSON，則函數會傳回原始字串，如果無效，則傳回 null。

**引數類型**：STRING

**傳回類型**：STRING/NULL。有效 JSON 物件格式的 STRING 表達式。

**範例**：

```
os> source=people | eval `valid_json()` = json('[1,2,3,{"f1":1,"f2":[5,6]},4]') | fields valid_json
fetched rows / total rows = 1/1
+---------------------------------+
| valid_json                      |
+---------------------------------+
| [1,2,3,{"f1":1,"f2":[5,6]},4]   |
+---------------------------------+

os> source=people | eval `invalid_json()` = json('{"invalid": "json"') | fields invalid_json
fetched rows / total rows = 1/1
+----------------+
| invalid_json   |
+----------------+
| null           |
+----------------+
```

##### `JSON_OBJECT`
<a name="supported-ppl-json-functions-json-object"></a>

**用量**：從鍵/值對的成員`json_object(<key>, <value>[, <key>, <value>]...)`傳回 JSON 物件。

**引數類型：**
+ <key> 必須是 STRING。
+ <value> 可以是任何資料類型。

**傳回類型**：JSON\_OBJECT。有效 JSON 物件的 StructType 表達式。

**範例**：

```
os> source=people | eval result = json_object('key', 123.45) | fields result
fetched rows / total rows = 1/1
+------------------+
| result           |
+------------------+
| {"key":123.45}   |
+------------------+

os> source=people | eval result = json_object('outer', json_object('inner', 123.45)) | fields result
fetched rows / total rows = 1/1
+------------------------------+
| result                       |
+------------------------------+
| {"outer":{"inner":123.45}}   |
+------------------------------+
```

##### `JSON_ARRAY`
<a name="supported-ppl-json-functions-json-array"></a>

**用量**： 使用值清單`json_array(<value>...)`建立 JSON ARRAY。

**引數類型**： `<value>`可以是任何類型的值，例如字串、數字或布林值。

**傳回類型**：ARRAY。有效 JSON 陣列的任何支援資料類型的陣列。

**範例**：

```
os> source=people | eval `json_array` = json_array(1, 2, 0, -1, 1.1, -0.11)
fetched rows / total rows = 1/1
+------------------------------+
| json_array                   |
+------------------------------+
| [1.0,2.0,0.0,-1.0,1.1,-0.11] |
+------------------------------+

os> source=people | eval `json_array_object` = json_object("array", json_array(1, 2, 0, -1, 1.1, -0.11))
fetched rows / total rows = 1/1
+----------------------------------------+
| json_array_object                      |
+----------------------------------------+
| {"array":[1.0,2.0,0.0,-1.0,1.1,-0.11]} |
+----------------------------------------+
```

##### `TO_JSON_STRING`
<a name="supported-ppl-json-functions-to-json-string"></a>

**用量**：`to_json_string(jsonObject)`傳回具有指定 json 物件值的 JSON 字串。

**引數類型**：JSON\_OBJECT 

**傳回類型**：STRING

**範例**：

```
os> source=people | eval `json_string` = to_json_string(json_array(1, 2, 0, -1, 1.1, -0.11)) | fields json_string
fetched rows / total rows = 1/1
+--------------------------------+
| json_string                    |
+--------------------------------+
| [1.0,2.0,0.0,-1.0,1.1,-0.11]   |
+--------------------------------+

os> source=people | eval `json_string` = to_json_string(json_object('key', 123.45)) | fields json_string
fetched rows / total rows = 1/1
+-----------------+
| json_string     |
+-----------------+
| {'key', 123.45} |
+-----------------+
```

##### `ARRAY_LENGTH`
<a name="supported-ppl-json-functions-array-length"></a>

**用量**：`array_length(jsonArray)`傳回最外部陣列中的元素數目。

**引數類型**：ARRAY。ARRAY 或 JSON\_ARRAY 物件。

**傳回類型**：INTEGER

**範例**：

```
os> source=people | eval `json_array` = json_array_length(json_array(1,2,3,4)), `empty_array` = json_array_length(json_array())
fetched rows / total rows = 1/1
+--------------+---------------+
| json_array   | empty_array   |
+--------------+---------------+
| 4            | 0             |
+--------------+---------------+
```

##### `JSON_EXTRACT`
<a name="supported-ppl-json-functions-json-extract"></a>

**用量**： 根據指定的 JSON 路徑，從 JSON 字串`json_extract(jsonStr, path)`擷取 JSON 物件。如果輸入 JSON 字串無效，函數會傳回 null。

**引數類型**：STRING、STRING

**傳回類型**：STRING
+ 有效 JSON 物件格式的 STRING 表達式。
+ `NULL` 會在 JSON 無效時傳回。

**範例**：

```
os> source=people | eval `json_extract('{"a":"b"}', '$.a')` = json_extract('{"a":"b"}', '$a')
fetched rows / total rows = 1/1
+----------------------------------+
| json_extract('{"a":"b"}', 'a')   |
+----------------------------------+
| b                                |
+----------------------------------+

os> source=people | eval `json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[1].b')` = json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[1].b')
fetched rows / total rows = 1/1
+-----------------------------------------------------------+
| json_extract('{"a":[{"b":1.0},{"b":2.0}]}', '$.a[1].b')   |
+-----------------------------------------------------------+
| 2.0                                                       |
+-----------------------------------------------------------+

os> source=people | eval `json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[*].b')` = json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[*].b')
fetched rows / total rows = 1/1
+-----------------------------------------------------------+
| json_extract('{"a":[{"b":1.0},{"b":2.0}]}', '$.a[*].b')   |
+-----------------------------------------------------------+
| [1.0,2.0]                                                 |
+-----------------------------------------------------------+

os> source=people | eval `invalid_json` = json_extract('{"invalid": "json"')
fetched rows / total rows = 1/1
+----------------+
| invalid_json   |
+----------------+
| null           |
+----------------+
```

##### `JSON_KEYS`
<a name="supported-ppl-json-functions-json-keys"></a>

**用量**：`json_keys(jsonStr)`傳回最外部 JSON 物件的所有索引鍵做為陣列。

**引數類型**：STRING。有效 JSON 物件格式的 STRING 表達式。

**傳回類型**：ARRAY【STRING】。函數`NULL`會傳回任何其他有效的 JSON 字串、空字串或無效的 JSON。

**範例**：

```
os> source=people | eval `keys` = json_keys('{"f1":"abc","f2":{"f3":"a","f4":"b"}}')
fetched rows / total rows = 1/1
+------------+
| keus       |
+------------+
| [f1, f2]   |
+------------+

os> source=people | eval `keys` = json_keys('[1,2,3,{"f1":1,"f2":[5,6]},4]')
fetched rows / total rows = 1/1
+--------+
| keys   |
+--------+
| null   |
+--------+
```

##### `JSON_VALID`
<a name="supported-ppl-json-functions-json-valid"></a>

**用量**：`json_valid(jsonStr)`評估 JSON 字串是否使用有效的 JSON 語法，並傳回 TRUE 或 FALSE。

**引數類型**：STRING

**傳回類型**：BOOLEAN

**範例**：

```
os> source=people | eval `valid_json` = json_valid('[1,2,3,4]'), `invalid_json` = json_valid('{"invalid": "json"') | feilds `valid_json`, `invalid_json`
fetched rows / total rows = 1/1
+--------------+----------------+
| valid_json   | invalid_json   |
+--------------+----------------+
| True         | False          |
+--------------+----------------+

os> source=accounts | where json_valid('[1,2,3,4]') and isnull(email) | fields account_number, email
fetched rows / total rows = 1/1
+------------------+---------+
| account_number   | email   |
|------------------+---------|
| 13               | null    |
+------------------+---------+
```

##### PPL Lambda 函數
<a name="supported-ppl-lambda-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `EXISTS`
<a name="supported-ppl-lambda-functions-exists"></a>

**用量**：`exists(array, lambda)`評估 Lambda 述詞是否保留陣列中的一或多個元素。

**引數類型**：ARRAY、LAMBDA

**傳回類型**：BOOLEAN。`TRUE` 如果陣列中至少有一個元素符合 Lambda 述詞，則傳回 ，否則傳回 `FALSE`。

**範例**：

```
 os> source=people | eval array = json_array(1, -1, 2), result = exists(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| true      |
+-----------+

os> source=people | eval array = json_array(-1, -3, -2), result = exists(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| false     |
+-----------+
```

##### `FILTER`
<a name="supported-ppl-lambda-functions-filter"></a>

**用量**：使用指定的 Lambda 函數`filter(array, lambda)`篩選輸入陣列。

**引數類型**：ARRAY、LAMBDA

**傳回類型**：ARRAY。包含輸入陣列中符合 Lambda 述詞之所有元素的 ARRAY。

**範例**：

```
 os> source=people | eval array = json_array(1, -1, 2), result = filter(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| [1, 2]    |
+-----------+

os> source=people | eval array = json_array(-1, -3, -2), result = filter(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| []        |
+-----------+
```

##### `TRANSFORM`
<a name="supported-ppl-lambda-functions-transform"></a>

**用量**： 使用 Lambda `transform(array, lambda)`轉換函數轉換陣列中的元素。如果使用二進位 Lambda 函數，第二個引數表示 元素的索引。這類似於功能程式設計`map`中的 。

**引數類型**：ARRAY、LAMBDA

**傳回類型**：ARRAY。包含將 Lambda 轉換函數套用至輸入陣列中每個元素之結果的 ARRAY。

**範例**：

```
os> source=people | eval array = json_array(1, 2, 3), result = transform(array, x -> x + 1) | fields result
fetched rows / total rows = 1/1
+--------------+
| result       |
+--------------+
| [2, 3, 4]    |
+--------------+

os> source=people | eval array = json_array(1, 2, 3), result = transform(array, (x, i) -> x + i) | fields result
fetched rows / total rows = 1/1
+--------------+
| result       |
+--------------+
| [1, 3, 5]    |
+--------------+
```

##### `REDUCE`
<a name="supported-ppl-lambda-functions-reduce"></a>

**用量**：套用 Lambda 函數，將陣列`reduce(array, start, merge_lambda, finish_lambda)`減少為單一值。函數會將 merge\_lambda 套用至開始值和所有陣列元素，然後將 `finish_lambda` 套用至結果。

**引數類型**：ARRAY、 ANY、LAMBDA、LAMBDA

**傳回類型**： ANY。將 Lambda 函數套用至開始值和輸入陣列的最終結果。

**範例**：

```
 os> source=people | eval array = json_array(1, 2, 3), result = reduce(array, 0, (acc, x) -> acc + x) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| 6         |
+-----------+

os> source=people | eval array = json_array(1, 2, 3), result = reduce(array, 10, (acc, x) -> acc + x) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| 16        |
+-----------+

os> source=people | eval array = json_array(1, 2, 3), result = reduce(array, 0, (acc, x) -> acc + x, acc -> acc * 10) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| 60        |
+-----------+
```

##### PPL 數學函數
<a name="supported-ppl-math-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `ABS`
<a name="supported-ppl-math-functions-abs"></a>

**用量**： `ABS(x) `計算 x 的絕對值。

**引數類型：**INTEGER/LONG/FLOAT/DOUBLE

**傳回類型：**INTEGER/LONG/FLOAT/DOUBLE

**範例**：

```
os> source=people | eval `ABS(-1)` = ABS(-1) | fields `ABS(-1)`
fetched rows / total rows = 1/1
+-----------+
| ABS(-1)   |
|-----------|
| 1         |
+-----------+
```

##### `ACOS`
<a name="supported-ppl-math-functions-acos"></a>

**用量**： `ACOS(x)` 計算 x 的電弧餘弦。`NULL` 如果 x 不在 -1 到 1 的範圍內，則傳回 。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `ACOS(0)` = ACOS(0) | fields `ACOS(0)`
fetched rows / total rows = 1/1
+--------------------+
| ACOS(0)            |
|--------------------|
| 1.5707963267948966 |
+--------------------+
```

##### `ASIN`
<a name="supported-ppl-math-functions-asin"></a>

**用量**： `asin(x)` 計算 x 的電弧正弦。`NULL` 如果 x 不在 -1 到 1 的範圍內，則傳回 。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `ASIN(0)` = ASIN(0) | fields `ASIN(0)`
fetched rows / total rows = 1/1
+-----------+
| ASIN(0)   |
|-----------|
| 0.0       |
+-----------+
```

##### `ATAN`
<a name="supported-ppl-math-functions-atan"></a>

**用量**： `ATAN(x)` 計算 x 的電弧切線。 `atan(y, x)`計算 y / x 的電弧切線，但兩個引數的符號都會決定結果的四分之一。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `ATAN(2)` = ATAN(2), `ATAN(2, 3)` = ATAN(2, 3) | fields `ATAN(2)`, `ATAN(2, 3)`
fetched rows / total rows = 1/1
+--------------------+--------------------+
| ATAN(2)            | ATAN(2, 3)         |
|--------------------+--------------------|
| 1.1071487177940904 | 0.5880026035475675 |
+--------------------+--------------------+
```

##### `ATAN2`
<a name="supported-ppl-math-functions-atan2"></a>

**用量**： `ATAN2(y, x)`會計算 y/x 的電弧切線，但兩個引數的符號都會決定結果的四分之一。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `ATAN2(2, 3)` = ATAN2(2, 3) | fields `ATAN2(2, 3)`
fetched rows / total rows = 1/1
+--------------------+
| ATAN2(2, 3)        |
|--------------------|
| 0.5880026035475675 |
+--------------------+
```

##### `CBRT`
<a name="supported-ppl-math-functions-cbrt"></a>

**用量**： `CBRT` 計算數字的立方體根。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE：

INTEGER/LONG/FLOAT/DOUBLE -> 雙

**範例**：

```
opensearchsql> source=location | eval `CBRT(8)` = CBRT(8), `CBRT(9.261)` = CBRT(9.261), `CBRT(-27)` = CBRT(-27) | fields `CBRT(8)`, `CBRT(9.261)`, `CBRT(-27)`;
fetched rows / total rows = 2/2
+-----------+---------------+-------------+
| CBRT(8)   | CBRT(9.261)   | CBRT(-27)   |
|-----------+---------------+-------------|
| 2.0       | 2.1           | -3.0        |
| 2.0       | 2.1           | -3.0        |
+-----------+---------------+-------------+
```

##### `CEIL`
<a name="supported-ppl-math-functions-ceil"></a>

**用量**：`CEILING`函數的別名。 `CEILING(T)`採用值 T 的上限。

**限制**：`CEILING`只有在 IEEE 754 雙類型在儲存時顯示小數時，才會如預期運作。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：LONG

**範例**：

```
os> source=people | eval `CEILING(0)` = CEILING(0), `CEILING(50.00005)` = CEILING(50.00005), `CEILING(-50.00005)` = CEILING(-50.00005) | fields `CEILING(0)`, `CEILING(50.00005)`, `CEILING(-50.00005)`
fetched rows / total rows = 1/1
+--------------+---------------------+----------------------+
| CEILING(0)   | CEILING(50.00005)   | CEILING(-50.00005)   |
|--------------+---------------------+----------------------|
| 0            | 51                  | -50                  |
+--------------+---------------------+----------------------+

os> source=people | eval `CEILING(3147483647.12345)` = CEILING(3147483647.12345), `CEILING(113147483647.12345)` = CEILING(113147483647.12345), `CEILING(3147483647.00001)` = CEILING(3147483647.00001) | fields `CEILING(3147483647.12345)`, `CEILING(113147483647.12345)`, `CEILING(3147483647.00001)`
fetched rows / total rows = 1/1
+-----------------------------+-------------------------------+-----------------------------+
| CEILING(3147483647.12345)   | CEILING(113147483647.12345)   | CEILING(3147483647.00001)   |
|-----------------------------+-------------------------------+-----------------------------|
| 3147483648                  | 113147483648                  | 3147483648                  |
+-----------------------------+-------------------------------+-----------------------------+
```

##### `CONV`
<a name="supported-ppl-math-functions-conv"></a>

**用量**： 將數字 x 從基礎`CONV(x, a, b)`轉換為 b 基礎。

**引數類型**：x：STRING、a：INTEGER、b：INTEGER

**傳回類型**：STRING

**範例**：

```
os> source=people | eval `CONV('12', 10, 16)` = CONV('12', 10, 16), `CONV('2C', 16, 10)` = CONV('2C', 16, 10), `CONV(12, 10, 2)` = CONV(12, 10, 2), `CONV(1111, 2, 10)` = CONV(1111, 2, 10) | fields `CONV('12', 10, 16)`, `CONV('2C', 16, 10)`, `CONV(12, 10, 2)`, `CONV(1111, 2, 10)`
fetched rows / total rows = 1/1
+----------------------+----------------------+-------------------+---------------------+
| CONV('12', 10, 16)   | CONV('2C', 16, 10)   | CONV(12, 10, 2)   | CONV(1111, 2, 10)   |
|----------------------+----------------------+-------------------+---------------------|
| c                    | 44                   | 1100              | 15                  |
+----------------------+----------------------+-------------------+---------------------+
```

##### `COS`
<a name="supported-ppl-math-functions-cos"></a>

**用量**： `COS(x)`計算 x 的餘弦，其中 x 以弧度表示。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型：**DOUBLE

**範例**：

```
os> source=people | eval `COS(0)` = COS(0) | fields `COS(0)`
fetched rows / total rows = 1/1
+----------+
| COS(0)   |
|----------|
| 1.0      |
+----------+
```

##### `COT`
<a name="supported-ppl-math-functions-cot"></a>

**用量**： `COT(x)` 計算 x 的餘切。如果 x out-of-range的錯誤。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `COT(1)` = COT(1) | fields `COT(1)`
fetched rows / total rows = 1/1
+--------------------+
| COT(1)             |
|--------------------|
| 0.6420926159343306 |
+--------------------+
```

##### `CRC32`
<a name="supported-ppl-math-functions-crc32"></a>

**用量**： `CRC32`計算循環冗餘檢查值，並傳回 32 位元的未簽署值。

**引數類型**：STRING

**傳回類型**：LONG

**範例**：

```
os> source=people | eval `CRC32('MySQL')` = CRC32('MySQL') | fields `CRC32('MySQL')`
fetched rows / total rows = 1/1
+------------------+
| CRC32('MySQL')   |
|------------------|
| 3259397556       |
+------------------+
```

##### `DEGREES`
<a name="supported-ppl-math-functions-degrees"></a>

**用量**： 將 x 從弧度`DEGREES(x)`轉換為度數。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `DEGREES(1.57)` = DEGREES(1.57) | fields `DEGREES(1.57)`
fetched rows / total rows  = 1/1
+-------------------+
| DEGREES(1.57)     |
|-------------------|
| 89.95437383553924 |
+-------------------+
```

##### `E`
<a name="supported-ppl-math-functions-e"></a>

**用量**：`E()`傳回 Euler 的號碼。

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `E()` = E() | fields `E()`
fetched rows / total rows = 1/1
+-------------------+
| E()               |
|-------------------|
| 2.718281828459045 |
+-------------------+
```

##### `EXP`
<a name="supported-ppl-math-functions-exp"></a>

**用量**： `EXP(x)`傳回提高到 x 能力的 e。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `EXP(2)` = EXP(2) | fields `EXP(2)`
fetched rows / total rows = 1/1
+------------------+
| EXP(2)           |
|------------------|
| 7.38905609893065 |
+------------------+
```

##### `FLOOR`
<a name="supported-ppl-math-functions-floor"></a>

**用量**：`FLOOR(T)`採用值 T 的下限。

**限制**：`FLOOR`只有在 IEEE 754 雙重類型在儲存時顯示小數時，才能如預期運作。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：LONG

**範例**：

```
os> source=people | eval `FLOOR(0)` = FLOOR(0), `FLOOR(50.00005)` = FLOOR(50.00005), `FLOOR(-50.00005)` = FLOOR(-50.00005) | fields `FLOOR(0)`, `FLOOR(50.00005)`, `FLOOR(-50.00005)`
fetched rows / total rows = 1/1
+------------+-------------------+--------------------+
| FLOOR(0)   | FLOOR(50.00005)   | FLOOR(-50.00005)   |
|------------+-------------------+--------------------|
| 0          | 50                | -51                |
+------------+-------------------+--------------------+

os> source=people | eval `FLOOR(3147483647.12345)` = FLOOR(3147483647.12345), `FLOOR(113147483647.12345)` = FLOOR(113147483647.12345), `FLOOR(3147483647.00001)` = FLOOR(3147483647.00001) | fields `FLOOR(3147483647.12345)`, `FLOOR(113147483647.12345)`, `FLOOR(3147483647.00001)`
fetched rows / total rows = 1/1
+---------------------------+-----------------------------+---------------------------+
| FLOOR(3147483647.12345)   | FLOOR(113147483647.12345)   | FLOOR(3147483647.00001)   |
|---------------------------+-----------------------------+---------------------------|
| 3147483647                | 113147483647                | 3147483647                |
+---------------------------+-----------------------------+---------------------------+

os> source=people | eval `FLOOR(282474973688888.022)` = FLOOR(282474973688888.022), `FLOOR(9223372036854775807.022)` = FLOOR(9223372036854775807.022), `FLOOR(9223372036854775807.0000001)` = FLOOR(9223372036854775807.0000001) | fields `FLOOR(282474973688888.022)`, `FLOOR(9223372036854775807.022)`, `FLOOR(9223372036854775807.0000001)`
fetched rows / total rows = 1/1
+------------------------------+----------------------------------+--------------------------------------+
| FLOOR(282474973688888.022)   | FLOOR(9223372036854775807.022)   | FLOOR(9223372036854775807.0000001)   |
|------------------------------+----------------------------------+--------------------------------------|
| 282474973688888              | 9223372036854775807              | 9223372036854775807                  |
+------------------------------+----------------------------------+--------------------------------------+
```

##### `LN`
<a name="supported-ppl-math-functions-ln"></a>

**用量**：`LN(x)`傳回 x 的自然對數。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `LN(2)` = LN(2) | fields `LN(2)`
fetched rows / total rows = 1/1
+--------------------+
| LN(2)              |
|--------------------|
| 0.6931471805599453 |
+--------------------+
```

##### `LOG`
<a name="supported-ppl-math-functions-log"></a>

**用量**：`LOG(x)`傳回 x 的自然對數，這是 x. log(B， x) 的基本 e 對數，相當於 log(x)/log(B)。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `LOG(2)` = LOG(2), `LOG(2, 8)` = LOG(2, 8) | fields `LOG(2)`, `LOG(2, 8)`
fetched rows / total rows = 1/1
+--------------------+-------------+
| LOG(2)             | LOG(2, 8)   |
|--------------------+-------------|
| 0.6931471805599453 | 3.0         |
+--------------------+-------------+
```

##### `LOG2`
<a name="supported-ppl-math-functions-log2"></a>

**用量**： `LOG2(x)` 等於 `log(x)`/`log(2)`。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `LOG2(8)` = LOG2(8) | fields `LOG2(8)`
fetched rows / total rows = 1/1
+-----------+
| LOG2(8)   |
|-----------|
| 3.0       |
+-----------+
```

##### `LOG10`
<a name="supported-ppl-math-functions-log10"></a>

**用量**： `LOG10(x)` 等於 `log(x)`/`log(10)`。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `LOG10(100)` = LOG10(100) | fields `LOG10(100)`
fetched rows / total rows = 1/1
+--------------+
| LOG10(100)   |
|--------------|
| 2.0          |
+--------------+
```

##### `MOD`
<a name="supported-ppl-math-functions-mod"></a>

**用量**： `MOD(n, m)` 計算 n 除以 m 的其餘數字。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：如果 m 是非零值，則 n 和 m 類型之間的類型會更寬。如果 m 等於 0，則傳回 NULL。

**範例**：

```
os> source=people | eval `MOD(3, 2)` = MOD(3, 2), `MOD(3.1, 2)` = MOD(3.1, 2) | fields `MOD(3, 2)`, `MOD(3.1, 2)`
fetched rows / total rows = 1/1
+-------------+---------------+
| MOD(3, 2)   | MOD(3.1, 2)   |
|-------------+---------------|
| 1           | 1.1           |
+-------------+---------------+
```

##### `PI`
<a name="supported-ppl-math-functions-pi"></a>

**用量**：`PI() `傳回常數 pi。

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `PI()` = PI() | fields `PI()`
fetched rows / total rows = 1/1
+-------------------+
| PI()              |
|-------------------|
| 3.141592653589793 |
+-------------------+
```

##### `POW`
<a name="supported-ppl-math-functions-pow"></a>

**用量**： `POW(x, y)` 計算 x 的值，提高到 y 的倍數。輸入錯誤會傳回`NULL`結果。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**同義詞**： `POWER(_, _)`

**範例**：

```
os> source=people | eval `POW(3, 2)` = POW(3, 2), `POW(-3, 2)` = POW(-3, 2), `POW(3, -2)` = POW(3, -2) | fields `POW(3, 2)`, `POW(-3, 2)`, `POW(3, -2)`
fetched rows / total rows = 1/1
+-------------+--------------+--------------------+
| POW(3, 2)   | POW(-3, 2)   | POW(3, -2)         |
|-------------+--------------+--------------------|
| 9.0         | 9.0          | 0.1111111111111111 |
+-------------+--------------+--------------------+
```

##### POWER
<a name="supported-ppl-math-functions-power"></a>

**用量**： `POWER(x, y)` 計算 x 的值，提高到 y 的倍數。輸入錯誤會傳回`NULL`結果。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**同義詞**： `POW(_, _)`

**範例**：

```
os> source=people | eval `POWER(3, 2)` = POWER(3, 2), `POWER(-3, 2)` = POWER(-3, 2), `POWER(3, -2)` = POWER(3, -2) | fields `POWER(3, 2)`, `POWER(-3, 2)`, `POWER(3, -2)`
fetched rows / total rows = 1/1
+---------------+----------------+--------------------+
| POWER(3, 2)   | POWER(-3, 2)   | POWER(3, -2)       |
|---------------+----------------+--------------------|
| 9.0           | 9.0            | 0.1111111111111111 |
+---------------+----------------+--------------------+
```

##### `RADIANS`
<a name="supported-ppl-math-functions-radians"></a>

**用量**： 將 x 從度數`RADIANS(x)`轉換為弧度。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型**：DOUBLE

**範例**：

```
os> source=people | eval `RADIANS(90)` = RADIANS(90) | fields `RADIANS(90)`
fetched rows / total rows  = 1/1
+--------------------+
| RADIANS(90)        |
|--------------------|
| 1.5707963267948966 |
+--------------------+
```

##### `RAND`
<a name="supported-ppl-math-functions-rand"></a>

**用量**：`RAND()`/`RAND(N)` 傳回範圍 0 <= 值 < 1.0 的隨機浮點值。如果您指定整數 N，函數會在執行之前初始化種子。這種行為的一個含義是，使用相同的引數 N，每次都會`rand(N)`傳回相同的值，產生可重複的資料欄值序列。

**引數類型**：INTEGER

**傳回類型**：FLOAT

**範例**：

```
os> source=people | eval `RAND(3)` = RAND(3) | fields `RAND(3)`
fetched rows / total rows = 1/1
+------------+
| RAND(3)    |
|------------|
| 0.73105735 |
+------------+
```

##### `ROUND`
<a name="supported-ppl-math-functions-round"></a>

**用量**：將引數 x `ROUND(x, d)`四捨五入為小數位數。如果您未指定 d，則預設為 0。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型映射**：
+ （整數/長 【，整數】) -> 長
+ （浮點數/雙 【，整數】) -> 長

**範例**：

```
os> source=people | eval `ROUND(12.34)` = ROUND(12.34), `ROUND(12.34, 1)` = ROUND(12.34, 1), `ROUND(12.34, -1)` = ROUND(12.34, -1), `ROUND(12, 1)` = ROUND(12, 1) | fields `ROUND(12.34)`, `ROUND(12.34, 1)`, `ROUND(12.34, -1)`, `ROUND(12, 1)`
fetched rows / total rows = 1/1
+----------------+-------------------+--------------------+----------------+
| ROUND(12.34)   | ROUND(12.34, 1)   | ROUND(12.34, -1)   | ROUND(12, 1)   |
|----------------+-------------------+--------------------+----------------|
| 12.0           | 12.3              | 10.0               | 12             |
+----------------+-------------------+--------------------+----------------+
```

##### `SIGN`
<a name="supported-ppl-math-functions-sign"></a>

**用量**： `SIGN`傳回引數的符號 -1、0 或 1，取決於數字是負數、零或正數。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型：**INTEGER

**範例**：

```
os> source=people | eval `SIGN(1)` = SIGN(1), `SIGN(0)` = SIGN(0), `SIGN(-1.1)` = SIGN(-1.1) | fields `SIGN(1)`, `SIGN(0)`, `SIGN(-1.1)`
fetched rows / total rows = 1/1
+-----------+-----------+--------------+
| SIGN(1)   | SIGN(0)   | SIGN(-1.1)   |
|-----------+-----------+--------------|
| 1         | 0         | -1           |
+-----------+-----------+--------------+
```

##### `SIN`
<a name="supported-ppl-math-functions-sin"></a>

**用量**： `sin(x)` 計算 x 的正弦，其中 x 以弧度表示。

**引數類型：**INTEGER/LONG/FLOAT/DOUBLE

**傳回類型：**DOUBLE

**範例**：

```
os> source=people | eval `SIN(0)` = SIN(0) | fields `SIN(0)`
fetched rows / total rows = 1/1
+----------+
| SIN(0)   |
|----------|
| 0.0      |
+----------+
```

##### `SQRT`
<a name="supported-ppl-math-functions-sqrt"></a>

**用量**： `SQRT` 計算非負數的平方根。

**引數類型：**INTEGER/LONG/FLOAT/DOUBLE

**傳回類型映射：**
+ （非負值） INTEGER/LONG/FLOAT/DOUBLE -> DOUBLE
+ （負） INTEGER/LONG/FLOAT/DOUBLE -> NULL

**範例**：

```
os> source=people | eval `SQRT(4)` = SQRT(4), `SQRT(4.41)` = SQRT(4.41) | fields `SQRT(4)`, `SQRT(4.41)`
fetched rows / total rows = 1/1
+-----------+--------------+
| SQRT(4)   | SQRT(4.41)   |
|-----------+--------------|
| 2.0       | 2.1          |
+-----------+--------------+
```

##### PPL 字串函數
<a name="supported-ppl-string-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `CONCAT`
<a name="supported-ppl-string-functions-concat"></a>

**用量**： 最多可`CONCAT(str1, str2, ...., str_9)`將 9 個字串加在一起。

**引數類型：**
+ STRING、STRING、....、STRING
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `CONCAT('hello', 'world')` = CONCAT('hello', 'world'), `CONCAT('hello ', 'whole ', 'world', '!')` = CONCAT('hello ', 'whole ', 'world', '!') | fields `CONCAT('hello', 'world')`, `CONCAT('hello ', 'whole ', 'world', '!')`
fetched rows / total rows = 1/1
+----------------------------+--------------------------------------------+
| CONCAT('hello', 'world')   | CONCAT('hello ', 'whole ', 'world', '!')   |
|----------------------------+--------------------------------------------|
| helloworld                 | hello whole world!                         |
+----------------------------+--------------------------------------------+
```

##### `CONCAT_WS`
<a name="supported-ppl-string-functions-concat-ws"></a>

**用量**：使用指定的分隔符號串`CONCAT_WS(sep, str1, str2)`連兩個或多個字串。

**引數類型：**
+ STRING、STRING、....、STRING
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `CONCAT_WS(',', 'hello', 'world')` = CONCAT_WS(',', 'hello', 'world') | fields `CONCAT_WS(',', 'hello', 'world')`
fetched rows / total rows = 1/1
+------------------------------------+
| CONCAT_WS(',', 'hello', 'world')   |
|------------------------------------|
| hello,world                        |
+------------------------------------+
```

##### `LENGTH`
<a name="supported-ppl-string-functions-length"></a>

**用量**： `length(str)` 傳回以位元組為單位的輸入字串長度。

**引數類型：**
+ STRING
+ 傳回類型：INTEGER

**範例**：

```
os> source=people | eval `LENGTH('helloworld')` = LENGTH('helloworld') | fields `LENGTH('helloworld')`
fetched rows / total rows = 1/1
+------------------------+
| LENGTH('helloworld')   |
|------------------------|
| 10                     |
+------------------------+
```

##### `LOWER`
<a name="supported-ppl-string-functions-lower"></a>

**用量**： 將輸入字串`lower(string)`轉換為小寫。

**引數類型：**
+ STRING
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `LOWER('helloworld')` = LOWER('helloworld'), `LOWER('HELLOWORLD')` = LOWER('HELLOWORLD') | fields `LOWER('helloworld')`, `LOWER('HELLOWORLD')`
fetched rows / total rows = 1/1
+-----------------------+-----------------------+
| LOWER('helloworld')   | LOWER('HELLOWORLD')   |
|-----------------------+-----------------------|
| helloworld            | helloworld            |
+-----------------------+-----------------------+
```

##### `LTRIM`
<a name="supported-ppl-string-functions-ltrim"></a>

**用量**：從輸入字串`ltrim(str)`中移除前置空格字元。

**引數類型：**
+ STRING
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `LTRIM('   hello')` = LTRIM('   hello'), `LTRIM('hello   ')` = LTRIM('hello   ') | fields `LTRIM('   hello')`, `LTRIM('hello   ')`
fetched rows / total rows = 1/1
+---------------------+---------------------+
| LTRIM('   hello')   | LTRIM('hello   ')   |
|---------------------+---------------------|
| hello               | hello               |
+---------------------+---------------------+
```

##### `POSITION`
<a name="supported-ppl-string-functions-position"></a>

**用量**：`POSITION(substr IN str)`傳回字串中第一次出現子字串的位置。如果子字串不在字串中，則傳回 0。如果任何引數為 NULL，則傳回 NULL。

**引數類型：**
+ STRING、STRING
+ 傳回類型 INTEGER

**範例**：

```
os> source=people | eval `POSITION('world' IN 'helloworld')` = POSITION('world' IN 'helloworld'), `POSITION('invalid' IN 'helloworld')`= POSITION('invalid' IN 'helloworld')  | fields `POSITION('world' IN 'helloworld')`, `POSITION('invalid' IN 'helloworld')`
fetched rows / total rows = 1/1
+-------------------------------------+---------------------------------------+
| POSITION('world' IN 'helloworld')   | POSITION('invalid' IN 'helloworld')   |
|-------------------------------------+---------------------------------------|
| 6                                   | 0                                     |
+-------------------------------------+---------------------------------------+
```

##### `REVERSE`
<a name="supported-ppl-string-functions-reverse"></a>

**用量**：`REVERSE(str)`傳回輸入字串的反向字串。

**引數類型：**
+ STRING
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `REVERSE('abcde')` = REVERSE('abcde') | fields `REVERSE('abcde')`
fetched rows / total rows = 1/1
+--------------------+
| REVERSE('abcde')   |
|--------------------|
| edcba              |
+--------------------+
```

##### `RIGHT`
<a name="supported-ppl-string-functions-right"></a>

**用量**： 會從輸入字串`right(str, len)`傳回最右邊的字元。如果子字串不在字串中，則傳回 0。如果任何引數為 NULL，則傳回 NULL。

**引數類型：**
+ STRING、INTEGER
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `RIGHT('helloworld', 5)` = RIGHT('helloworld', 5), `RIGHT('HELLOWORLD', 0)` = RIGHT('HELLOWORLD', 0) | fields `RIGHT('helloworld', 5)`, `RIGHT('HELLOWORLD', 0)`
fetched rows / total rows = 1/1
+--------------------------+--------------------------+
| RIGHT('helloworld', 5)   | RIGHT('HELLOWORLD', 0)   |
|--------------------------+--------------------------|
| world                    |                          |
+--------------------------+--------------------------+
```

##### `RTRIM`
<a name="supported-ppl-string-functions-rtrim"></a>

**用量**：從輸入字串`rtrim(str)`修剪結尾空格字元。

**引數類型：**
+ STRING
+ 傳回類型：**STRING**

**範例**：

```
os> source=people | eval `RTRIM('   hello')` = RTRIM('   hello'), `RTRIM('hello   ')` = RTRIM('hello   ') | fields `RTRIM('   hello')`, `RTRIM('hello   ')`
fetched rows / total rows = 1/1
+---------------------+---------------------+
| RTRIM('   hello')   | RTRIM('hello   ')   |
|---------------------+---------------------|
|    hello            | hello               |
+---------------------+---------------------+
```

##### `SUBSTRING`
<a name="supported-ppl-string-functions-substring"></a>

**用量**： `substring(str, start)`或 會`substring(str, start, length)`傳回輸入字串的子字串。沒有指定長度，它會從開始位置傳回整個字串。

**引數類型：**
+ STRING、INTEGER、INTEGER
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `SUBSTRING('helloworld', 5)` = SUBSTRING('helloworld', 5), `SUBSTRING('helloworld', 5, 3)` = SUBSTRING('helloworld', 5, 3) | fields `SUBSTRING('helloworld', 5)`, `SUBSTRING('helloworld', 5, 3)`
fetched rows / total rows = 1/1
+------------------------------+---------------------------------+
| SUBSTRING('helloworld', 5)   | SUBSTRING('helloworld', 5, 3)   |
|------------------------------+---------------------------------|
| oworld                       | owo                             |
+------------------------------+---------------------------------+
```

##### `TRIM`
<a name="supported-ppl-string-functions-trim"></a>

**用量**：從輸入字串`trim(string)`中移除前置和結尾空格。

**引數類型：**
+ STRING
+ 傳回類型：**STRING**

**範例**：

```
os> source=people | eval `TRIM('   hello')` = TRIM('   hello'), `TRIM('hello   ')` = TRIM('hello   ') | fields `TRIM('   hello')`, `TRIM('hello   ')`
fetched rows / total rows = 1/1
+--------------------+--------------------+
| TRIM('   hello')   | TRIM('hello   ')   |
|--------------------+--------------------|
| hello              | hello              |
+--------------------+--------------------+
```

##### `UPPER`
<a name="supported-ppl-string-functions-upper"></a>

**用量**： 將輸入字串`upper(string)`轉換為大寫。

**引數類型：**
+ STRING
+ 傳回類型：STRING

**範例**：

```
os> source=people | eval `UPPER('helloworld')` = UPPER('helloworld'), `UPPER('HELLOWORLD')` = UPPER('HELLOWORLD') | fields `UPPER('helloworld')`, `UPPER('HELLOWORLD')`
fetched rows / total rows = 1/1
+-----------------------+-----------------------+
| UPPER('helloworld')   | UPPER('HELLOWORLD')   |
|-----------------------+-----------------------|
| HELLOWORLD            | HELLOWORLD            |
+-----------------------+-----------------------+
```

##### PPL 類型轉換函數
<a name="supported-ppl-type-conversion-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `TRIM`
<a name="supported-ppl-conversion-functions-cast"></a>

**用量**： 會將 `cast(expr as dateType)`轉換為 `expr` ，`dataType`並傳回 的值`dataType`。

適用下列轉換規則：


**類型轉換規則**  

| Src/Target | STRING | NUMBER | BOOLEAN | TIMESTAMP | DATE | TIME | 
| --- | --- | --- | --- | --- | --- | --- | 
| STRING |  | Note1 | Note1 | TIMESTAMP() | DATE() | TIME() | 
| NUMBER | Note1 |  | v！=0 | N/A | N/A | N/A | 
| BOOLEAN | Note1 | v？1：0 |  | N/A | N/A | N/A | 
| TIMESTAMP | Note1 | N/A | N/A |  | DATE() | TIME() | 
| DATE | Note1 | N/A | N/A | N/A |  | N/A | 
| TIME | Note1 | N/A | N/A | N/A | N/A |  | 

**轉換為字串範例：**

```
os> source=people | eval `cbool` = CAST(true as string), `cint` = CAST(1 as string), `cdate` = CAST(CAST('2012-08-07' as date) as string) | fields `cbool`, `cint`, `cdate`
fetched rows / total rows = 1/1
+---------+--------+------------+
| cbool   | cint   | cdate      |
|---------+--------+------------|
| true    | 1      | 2012-08-07 |
+---------+--------+------------+
```

**轉換為數字範例：**

```
os> source=people | eval `cbool` = CAST(true as int), `cstring` = CAST('1' as int) | fields `cbool`, `cstring`
fetched rows / total rows = 1/1
+---------+-----------+
| cbool   | cstring   |
|---------+-----------|
| 1       | 1         |
+---------+-----------+
```

**迄今為止的範例：**

```
os> source=people | eval `cdate` = CAST('2012-08-07' as date), `ctime` = CAST('01:01:01' as time), `ctimestamp` = CAST('2012-08-07 01:01:01' as timestamp) | fields `cdate`, `ctime`, `ctimestamp`
fetched rows / total rows = 1/1
+------------+----------+---------------------+
| cdate      | ctime    | ctimestamp          |
|------------+----------+---------------------|
| 2012-08-07 | 01:01:01 | 2012-08-07 01:01:01 |
+------------+----------+---------------------+
```

**鏈結轉換範例：**

```
os> source=people | eval `cbool` = CAST(CAST(true as string) as boolean) | fields `cbool`
fetched rows / total rows = 1/1
+---------+
| cbool   |
|---------|
| True    |
+---------+
```