

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 지원되는 PPL 명령
<a name="supported-ppl"></a>

다음 표에는 CloudWatch Logs, Amazon S3 또는 Security Lake 쿼리용으로 OpenSearch Dashboards에서 지원되는 PPL 명령과 CloudWatch Logs Insights에서 지원되는 명령이 나와 있습니다. CloudWatch Logs Insights는 CloudWatch Logs를 쿼리할 때 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 명령 | 설명 | CloudWatch Logs | Amazon S3 | Security Lake |  명령 예제 | 
| --- | --- | --- | --- | --- | --- | 
| [fields 명령](#supported-ppl-fields-command) | 프로젝션이 필요한 필드 세트를 표시합니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre> fields field1, field2</pre>  | 
| [where 명령](#supported-ppl-where-command) | 지정한 조건에 따라 데이터를 필터링합니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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>  | 
| [parse 명령](#supported-ppl-parse-command) | 문자열에서 정규식(regex) 패턴을 추출하고 추출된 패턴을 표시합니다. 추출된 패턴을 사용하여 새 필드를 생성하거나 데이터를 필터링할 수 있습니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre>parse `field1` ".*/(?<field2>[^/]+$)"<br />| where field2 = "requestId"<br />| fields field2, `field2`<br />| head 1000</pre>  | 
| [patterns 명령](#supported-ppl-patterns-command) | 텍스트 필드에서 로그 패턴을 추출하고 검색 결과에 결과를 추가합니다. 로그를 패턴별로 그룹화하면 분석 및 문제 해결을 위해 대량의 로그 데이터에서 통계를 더 쉽게 집계할 수 있습니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.png) 지원되지 않음 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre>eval field2 = `field1` * 2<br />| fields field1, field2<br />| head 20</pre>  | 
| [rename 명령](#supported-ppl-rename-command) | 검색 결과에서 하나 이상의 필드 이름을 바꿉니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre>source=customer<br />| join ON c_custkey = o_custkey orders<br />| head 10</pre>  | 
| [lookup 명령](#supported-ppl-lookup-commands) | 조회 인덱스(차원 테이블)의 데이터를 추가하거나 대체하여 검색 데이터를 보강합니다. 인덱스의 필드를 차원 테이블의 값으로 확장하거나, 조회 조건이 일치할 때 값을 추가하거나 바꿀 수 있습니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.png) 지원되지 않음 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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>  | 
| [subquery 명령](#supported-ppl-subquery-commands) | 파이프 처리 언어(PPL) 문 내에서 복잡한 중첩 쿼리를 수행합니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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>  | 
| [rare 명령](#supported-ppl-rare-command) | 필드 목록에 있는 모든 필드의 가장 빈도가 낮은 값을 찾습니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre> rare Field1 by Field2</pre>  | 
| [trendline 명령](#supported-ppl-trendline-commands) | 필드의 이동 평균을 계산합니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨(`count()` 제외) | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre> eventstats sum(field1) by field2</pre>  | 
| [flatten 명령](#supported-ppl-flatten-command) | 필드를 평면화합니다. 필드는 `struct<?,?> or array<struct<?,?>>` 유형이어야 합니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre> source=table | flatten field1</pre>  | 
| [필드 요약](#supported-ppl-field-summary-command) | 각 필드(count, distinct count, min, max, avg, stddev, mean)의 기본 통계를 계산합니다. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨(쿼리당 필드 1개) | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.png) 지원되지 않음 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 |  <pre> describe schema.table</pre>  | 

## 함수
<a name="supported-ppl-functions"></a>


| PPL 함수 | 설명 | 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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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`) | 여러 행에서 계산을 수행하여 단일 요약 값을 생성하는 내장 함수입니다. 예: **sum**, **count**, **avg**, **max**, **min**. | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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**(절대값), **round**(숫자 반올림), **sqrt**(제곱근), **pow**(제곱 계산), **ceil**(가장 가까운 정수로 반올림). | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.png) 지원되지 않음 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.png) 지원됨 | ![](http://docs.aws.amazon.com/ko_kr/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)을 참조하세요. 제한에는 쿼리할 수 있는 CloudWatch Log 그룹 수, 실행할 수 있는 최대 동시 쿼리 수, 최대 쿼리 실행 시간 및 결과에 반환된 최대 행 수가 포함됩니다. CloudWatch Logs를 쿼리하는 데 사용하는 언어(즉, OpenSearch PPL, SQL 및 Logs Insights QL)에 관계없이 제한은 동일합니다.

### PPL 명령
<a name="supported-ppl-commands-details"></a>

**Topics**
+ [설명](#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)
+ [fields 명령](#supported-ppl-fields-command)
+ [flatten 명령](#supported-ppl-flatten-command)
+ [grok 명령](#supported-ppl-grok-command)
+ [head 명령](#supported-ppl-head-command)
+ [join 명령](#supported-ppl-join-commands)
+ [lookup 명령](#supported-ppl-lookup-commands)
+ [parse 명령](#supported-ppl-parse-command)
+ [patterns 명령](#supported-ppl-patterns-command)
+ [rare 명령](#supported-ppl-rare-command)
+ [rename 명령](#supported-ppl-rename-command)
+ [search 명령](#supported-ppl-search-command)
+ [sort 명령](#supported-ppl-sort-command)
+ [stats 명령](#supported-ppl-stats-command)
+ [subquery 명령](#supported-ppl-subquery-commands)
+ [top 명령](#supported-ppl-top-command)
+ [trendline 명령](#supported-ppl-trendline-commands)
+ [where 명령](#supported-ppl-where-command)
+ [필드 요약](#supported-ppl-field-summary-command)
+ [expand 명령](#supported-ppl-expand-command)
+ [PPL 함수](#supported-ppl-functions-details)

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

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

일반적인 차원과 기간에 따라 다양한 데이터 소스를 상호 연관시킬 수 있습니다.

이 상관 관계는 동일한 기간을 공유하지만 공식적으로 동기화되지 않은 다양한 수직 요소의 대량 데이터를 처리할 때 매우 중요합니다.

이러한 다양한 데이터 소스를 기간 및 유사한 차원에 따라 상호 연관시켜 데이터를 보강하고 중요한 인사이트를 도출할 수 있습니다.

**예제**  
관찰성 도메인에는 세 가지 개별 데이터 소스가 있습니다.
+ 로그
+ Metrics
+ 트레이스

이러한 데이터 소스는 공통 차원을 공유할 수 있습니다. 한 데이터 소스에서 다른 데이터 소스로 전환하려면 데이터 소스의 상관 관계를 올바르게 지정해야 합니다. 시맨틱 명명 규칙을 사용하여 로그, 트레이스 및 지표에서 공유 요소를 식별할 수 있습니다.

예제:

```
{
  "@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** - `"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": {
         ...
        }
      }
    }
  }
}
```

이 접근 방식에서는 시스템의 동작과 조건을 이해하는 데 도움이 되는 elb 로그와 상호 연관될 수 있는 `traceId`와 http의 클라이언트/서버 `ip`를 살펴볼 수 있습니다.

**새 상관 관계 쿼리 명령**  
다음은 이러한 유형의 조사를 허용하는 새로운 명령입니다.

```
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    
```

상관 관계 조인에 참여하는 각 필드에 대해 이 상관 관계 명령으로 조인할 모든 테이블이 포함된 관련 매핑 문을 제공해야 합니다.

**예제**  
이 예에는 두 가지 소스(`alb_logs, traces`)가 있습니다.

2개의 필드(`traceId, ip`)가 있습니다.

2개의 매핑 문(`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]
```

catalyst 엔진은 가장 효율적인 조인 순서에 따라 이 쿼리를 최적화합니다.

#### dedup 명령
<a name="supported-ppl-dedup-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`dedup` 명령을 사용하여 지정된 필드를 기반으로 검색 결과에서 동일한 문서를 제거합니다.

**구문**  
다음 구문을 사용합니다.

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

**`int`**
+ 선택 사항.
+ `dedup` 명령은 <int>를 지정할 때 각 조합에 대해 여러 이벤트를 유지합니다. <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: 연속 문서 중복 제거**  
이 예에서는 연속 문서를 중복 제거하는 방법을 보여줍니다.

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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#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`

**case를 사용한 평가 예:**  


```
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')
```

**다른 case를 사용한 평가 예:**  


가정: `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`

**case를 사용한 평가 예:**  


```
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')
```

**다른 case를 사용한 평가 예:**  


```
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
```

**제한 사항**
+ 기존 필드 재정의는 지원되지 않습니다. 쿼리에서 이렇게 하려고 시도하면 'Reference 'a' is ambiguous' 메시지와 함께 예외가 발생합니다.

  ```
  - `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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`eventstats` 명령을 사용하여 계산된 요약 통계로 이벤트 데이터를 보강합니다. 이벤트 내에 지정된 필드를 분석하고 다양한 통계 측정값을 계산한 다음, 그 결과를 각 원래 이벤트에 새 필드로 추가하는 식으로 작동합니다.

**eventstats의 주요 측면**

1. 전체 결과 집합 또는 정의된 그룹 내에서 계산을 수행합니다.

1. 원래 이벤트는 그대로 유지되며 통계 결과를 포함하도록 새 필드가 추가됩니다.

1. 명령은 비교 분석, 이상치 식별 또는 개별 이벤트에 대한 추가 컨텍스트 제공에 특히 유용합니다.

**통계와 이벤트 통계의 차이**  
`stats` 및 `eventstats` 명령은 모두 통계를 계산하는 데 사용되지만, 작동 방식과 생성되는 항목에 몇 가지 중요한 차이점이 있습니다.

**출력 형식**
+ `stats`: 계산된 통계만 포함된 요약 테이블을 생성합니다.
+ `eventstats`: 계산된 통계를 기존 이벤트에 새 필드로 추가하여 원래 데이터를 보존합니다.

**이벤트 보존**
+ `stats`: 결과 세트를 통계 요약으로만 줄여 개별 이벤트를 삭제합니다.
+ `eventstats`: 모든 원래 이벤트를 유지하고 계산된 통계와 함께 새 필드를 추가합니다.

**사용 사례**
+ `stats`: 요약 보고서 또는 대시보드를 생성하는 데 가장 적합합니다. 결과를 요약하는 최종 명령으로 자주 사용됩니다.
+ `eventstats`: 추가 분석 또는 필터링을 위해 통계 컨텍스트로 이벤트를 보강해야 할 때 유용합니다. 검색 중 후속 명령에 사용할 수 있는 통계를 추가하는 데 사용할 수 있습니다.

**구문**  
다음 구문을 사용합니다.

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

**aggregation**
+ 필수.
+ 새 집계 함수.
+ 집계의 인수는 필드여야 합니다.

**by-clause**
+ 선택 사항.
+ 구문: `by [span-expression,] [field,]...`
+ by 절에는 스칼라 함수 및 집계 함수와 같은 필드와 표현식이 포함될 수 있습니다. span 절을 사용하여 특정 필드를 동일한 간격의 버킷으로 분할할 수도 있습니다. 그런 다음 eventstats 명령은 이러한 span 버킷을 기반으로 집계를 수행합니다.
+ 기본값: by 절을 지정하지 않으면 eventstats 명령이 전체 결과 집합에 걸쳐 집계됩니다.

**span 표현식**
+ 선택 사항, 최대 1개.
+ 구문: `span(field_expr, interval_expr)`
+ interval 표현식의 단위는 기본적으로 자연 단위입니다. 단, 날짜 및 시간 유형 필드의 경우 날짜/시간 단위를 사용할 때 간격 표현식에 단위를 지정해야 합니다.

  예를 들어 `age` 필드를 10년 단위의 버킷으로 분할하려면 `span(age, 10)`을 사용합니다. 시간 기반 필드의 경우 `span(timestamp, 1h)`을 사용하여 `timestamp` 필드를 시간별 간격으로 분할할 수 있습니다.


**사용 가능한 시간 단위**  

| 범위 간격 단위 | 
| --- | 
| 밀리초(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   |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
```

**사용법**
+ `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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`expand` 명령을 사용하여 다음 유형의 필드를 평면화합니다.
+ `Array<Any>`
+ `Map<Any>`

**구문**  
다음 구문을 사용합니다.

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

**필드**
+ 확장할 필드입니다. 지원되는 유형이어야 합니다.

**별칭**
+ 선택 사항. 원래 필드 이름 대신 사용할 이름입니다.

**사용법**  
이 `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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`explain` 명령은 쿼리 실행 계획을 이해하는 데 도움이 되므로 쿼리를 분석하고 최적화하여 성능을 높일 수 있습니다. 이 소개에서는 쿼리 최적화에서 설명 명령의 용도와 중요도에 대한 간략한 개요를 제공합니다.

**설명**
+ `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`

**Eval**  
가정: `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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**설명**  
`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-replacement에 지정된 값으로 대체됩니다.

**예 1: 단일 필드의 Fillnull**  
이 예는 단일 필드에서 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: 다양한 null 대체 값을 사용하여 여러 필드에 적용된 Fillnull.**  
이 예에서는 null을 대체하는 데 사용되는 다양한 값이 있는 fillnull을 보여줍니다.
+ `request_path` 필드의 `/error`
+ `timestamp` 필드의 `1970-01-01 00:00:00`

```
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    |
```

#### fields 명령
<a name="supported-ppl-fields-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`fields` 명령을 사용하여 검색 결과에서 필드를 유지하거나 제거합니다.

**구문**  
다음 구문을 사용합니다.

```
field [+|-] <field-list> 
```
+ `index`: 선택 사항입니다.

  더하기(\+)를 사용하는 경우 필드 목록에 지정된 필드만 유지됩니다.

  마이너스(-)를 사용하면 필드 목록에 지정된 모든 필드가 제거됩니다.

  *기본*값: \+
+ `field list`: 필수입니다. 쉼표로 구분된, 유지하거나 제거할 필드의 목록입니다.

**예 1: 결과에서 지정된 필드 선택**  
이 예에서는 검색 결과에서 `account_number`, `firstname` 및 `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`
```

#### flatten 명령
<a name="supported-ppl-flatten-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

flatten 명령을 사용하여 다음 유형의 필드를 확장합니다.
+ `struct<?,?>`
+ `array<struct<?,?>>`

**구문**  
다음 구문을 사용합니다.

```
flatten <field>
```
+ *field*: 평면화할 필드입니다. 필드는 지원되는 유형이어야 합니다.

**스키마**


| col\_name | data\_type | 
| --- | --- | 
| \_time | 문자열 | 
| bridges | array<struct<length:bigint,name:string>> | 
| city | 문자열 | 
| coor | struct<alt:bigint,lat:double,long:double> | 
| country | 문자열 | 

**데이터**  



| \_time | bridges | city | coor | country | 
| --- | --- | --- | --- | --- | 
| 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}] | Venice | {2, 45.4408, 12.3155} | 이탈리아 | 
| 2024-09-13T12:00:00 | [{\*\*\*, Charles Bridge}, {343, Legion Bridge}] | Prague | {200, 50.0755, 14.4378} | 체코 공화국 | 
| 2024-09-13T12:00:00 | [{375, Chain Bridge}, {333, Liberty Bridge}] | Budapest | {96, 47.4979, 19.0402} | 헝가리 | 
| 1990-09-13T12:00:00 | NULL | Warsaw | NULL | 폴란드 | 

**예 1: 구문 평면화**  
이 예에서는 구문 필드를 평면화하는 방법을 보여줍니다.

PPL 쿼리:

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


| \_time | bridges | city | country | 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}] | Venice | 이탈리아 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12:00:00 | [{516, Charles Bridge}, {343, Legion Bridge}] | Prague | 체코 공화국 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12:00:00 | [{375, Chain Bridge}, {333, Liberty Bridge}] | Budapest | 헝가리 | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12:00:00 | NULL | Warsaw | 폴란드 | NULL | NULL | NULL | 

**예 2: 배열 평면화**  
이 예에서는 구문 필드 배열을 평면화하는 방법을 보여줍니다.

PPL 쿼리:

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


| \_time | city | coor | country | length | 이름 | 
| --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12:00:00 | 런던 | {35, 51.5074, -0.1278} | 영국 | 801 | Tower Bridge | 
| 2024-09-13T12:00:00 | 런던 | {35, 51.5074, -0.1278} | 영국 | 928 | London Bridge | 
| 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 | Venice | {2, 45.4408, 12.3155} | 이탈리아 | 48 | Rialto Bridge | 
| 2024-09-13T12:00:00 | Venice | {2, 45.4408, 12.3155} | 이탈리아 | 11 | Bridge of Sighs | 
| 2024-09-13T12:00:00 | Prague | {200, 50.0755, 14.4378} | 체코 공화국 | 516 | Charles Bridge | 
| 2024-09-13T12:00:00 | Prague | {200, 50.0755, 14.4378} | 체코 공화국 | 343 | Legion Bridge | 
| 2024-09-13T12:00:00 | Budapest | {96, 47.4979, 19.0402} | 헝가리 | 375 | Chain Bridge | 
| 2024-09-13T12:00:00 | Budapest | {96, 47.4979, 19.0402} | 헝가리 | 333 | Liberty Bridge | 
| 1990-09-13T12:00:00 | Warsaw | NULL | 폴란드 | NULL | NULL | 

**예 3: 배열 및 구문 평면화**  
이 예에서는 여러 필드를 평면화하는 방법을 보여줍니다.

PPL 쿼리:

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


| \_time | city | country | length | 이름 | alt | lat | long | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12:00:00 | 런던 | 영국 | 801 | Tower Bridge | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12:00:00 | 런던 | 영국 | 928 | London Bridge | 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 | Venice | 이탈리아 | 48 | Rialto Bridge | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12:00:00 | Venice | 이탈리아 | 11 | Bridge of Sighs | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12:00:00 | Prague | 체코 공화국 | 516 | Charles Bridge | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12:00:00 | Prague | 체코 공화국 | 343 | Legion Bridge | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12:00:00 | Budapest | 헝가리 | 375 | Chain Bridge | 96 | 47.4979 | 19.0402 | 
| 2024-09-13T12:00:00 | Budapest | 헝가리 | 333 | Liberty Bridge | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12:00:00 | Warsaw | 폴란드 | NULL | NULL | NULL | NULL | NULL | 

#### grok 명령
<a name="supported-ppl-grok-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`grok` 명령은 grok 패턴으로 텍스트 필드를 구문 분석하고 그 결과를 검색 결과에 추가합니다.

**구문**  
다음 구문을 사용합니다.

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

**필드**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

join 명령을 사용하면 공통 필드를 기반으로 여러 소스의 데이터를 결합하여 복잡한 분석을 수행하고 분산 데이터 세트에서 심층적인 인사이트를 얻을 수 있습니다.

**스키마**  
인덱스는 최소 `otel-v1-apm-span-*`(large)와 `otel-v1-apm-service-map`(small)이 있습니다.

인덱스의 관련 필드:

**`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
```

#### lookup 명령
<a name="supported-ppl-lookup-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`lookup` 명령을 사용하여 조회 인덱스(차원 테이블)의 데이터를 추가하거나 대체하여 검색 데이터를 보강합니다. 이 명령을 사용하면 인덱스의 필드를 차원 테이블의 값으로 확장할 수 있습니다. 조회 조건이 충족되면 이를 사용하여 값을 추가하거나 바꿀 수도 있습니다. 정적 데이터 세트로 소스 데이터를 보강하는 `Join` 명령보다 `lookup` 명령이 더 적합합니다.

**구문**  
다음 구문을 사용합니다.

```
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 \| APPEND**
+ 선택 사항.
+ 기본값: REPLACE
+ 일치하는 값을 처리하는 방법을 지정합니다. REPLACE를 지정하면 <lookupIndex> 필드의 일치하는 값이 결과의 값을 덮어씁니다. `APPEND`를 지정하면 <lookupIndex> 필드의 일치하는 값이 결과에서 누락된 값에만 추가됩니다.

**사용법**
+ LOOKUP <lookupIndex> id AS cid REPLACE mail AS email
+ LOOKUP <lookupIndex> name REPLACE mail AS email
+ LOOKUP <lookupIndex> id AS cid, name APPEND address, mail AS email
+ 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
```

#### parse 명령
<a name="supported-ppl-parse-command"></a>

`parse` 명령은 정규식을 사용하여 텍스트 필드를 구문 분석하고 검색 결과에 결과를 추가합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**구문**  
다음 구문을 사용합니다.

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

**`field`**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**`pattern`**
+ 필수 문자열입니다.
+ 지정된 텍스트 필드에서 새 필드를 추출하는 데 사용되는 정규식 패턴입니다.
+ 새 필드 이름이 이미 사용 중인 경우 원래 필드를 대체합니다.

**정규식**  
정규식 패턴은 Java 정규식 엔진을 사용하여 각 문서의 전체 텍스트 필드를 매칭하는 데 사용됩니다. 표현식의 각 명명된 캡처 그룹은 새 `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   |
+----------------+----------------+
```

**제한 사항**  
parse 명령에는 몇 가지 제한 사항이 있습니다.
+ parse로 정의된 필드는 다시 구문 분석할 수 없습니다.

  다음 명령은 작동하지 않습니다.

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | parse street '\w+ (?<road>\w+)'
  ```
+ parse로 정의된 필드는 다른 명령으로 재정의할 수 없습니다.

  `street`를 재정의할 수 없으므로 `where`는 문서와 매칭되지 않습니다.

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval street='1' | where street='1' ;        
  ```
+ parse에 사용되는 텍스트 필드는 재정의할 수 없습니다.

  `address`가 재정의되므로 `street`는 성공적으로 구문 분석되지 않습니다.

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval address='1' ;        
  ```
+ parse로 정의된 필드는 `stats` 명령에서 사용한 후 필터링하거나 정렬할 수 없습니다.

  다음 명령의 `where`는 작동하지 않습니다.

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

#### patterns 명령
<a name="supported-ppl-patterns-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`patterns` 명령은 텍스트 필드에서 로그 패턴을 추출하고 그 결과를 검색 결과에 추가합니다. 로그를 패턴별로 그룹화하면 분석 및 문제 해결을 위해 대량의 로그 데이터에서 통계를 더 쉽게 집계할 수 있습니다.

**구문**  
다음 구문을 사용합니다.

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

**new-field-name**
+ 선택 사항인 문자열입니다.
+ 추출된 패턴에 해당하는 새 필드의 이름입니다.
+ 기본값은 `patterns_field`입니다.
+ 해당 이름이 이미 사용 중인 경우 원래 필드를 대체합니다.

**pattern**
+ 선택 사항인 문자열입니다.
+ 텍스트 필드에서 필터링해야 하는 정규식 문자 패턴입니다.
+ 없는 경우 기본 패턴은 영숫자 문자(`[a-zA-Z\d]`)입니다.

**필드**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**예 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: 사용자 지정 정규식 패턴을 사용하여 로그 패턴 추출**  
이 예에서는 사용자 정의 패턴을 사용하여 원시 로그 필드에서 구두점을 추출하는 방법을 보여줍니다.

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/."                                            |
+-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------+
```

**제한 사항**  
patterns 명령에는 구문 분석 명령과 동일한 제한 사항이 있습니다.

#### rare 명령
<a name="supported-ppl-rare-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`rare` 명령을 사용하여 필드 목록에서 모든 필드 값의 가장 덜 흔한 튜플을 찾습니다.

**참고**  
그룹별 필드의 개별 값 튜플마다 최대 10개의 결과가 반환됩니다.

**구문**  
다음 구문을 사용합니다.

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

**field-list**
+ 필수.
+ 쉼표로 구분된 필드 이름의 목록입니다.

**by-clause**
+ 선택 사항.
+ 결과를 그룹화할 하나 이상의 필드입니다.

**N**
+ 반환할 결과 수.
+ 기본값: 10

**rare\_approx**
+ [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    |
+----------+-------+
```

#### rename 명령
<a name="supported-ppl-rename-command"></a>

`rename` 명령을 사용하여 검색 결과에서 하나 이상의 필드 이름을 변경합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**구문**  
다음 구문을 사용합니다.

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

**source-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        
  ```

#### search 명령
<a name="supported-ppl-search-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`search` 명령을 사용하여 인덱스에서 문서를 검색합니다. `search` 명령은 PPL 쿼리에서 첫 번째 명령으로만 사용할 수 있습니다.

**구문**  
다음 구문을 사용합니다.

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

**검색**
+ 선택 사항.
+ 생략할 수 있는 검색 키워드입니다.

**인덱스**
+ 필수.
+ search 명령은 쿼리할 인덱스를 지정해야 합니다.
+ 클러스터 간 검색을 위해 `<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` 명령을 사용하여 지정된 필드를 기준으로 검색 결과를 정렬합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#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` 명령을 사용하여 검색 결과에서 집계를 계산합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**NULL/MISSING 값 처리**  



**NULL/MISSING 값 처리**  

| 함수 | NULL | MISSING | 
| --- | --- | --- | 
| COUNT | 계산되지 않음 | 계산되지 않음 | 
| SUM | 무시 | 무시 | 
| AVG | 무시 | 무시 | 
| MAX | 무시 | 무시 | 
| MIN | 무시 | 무시 | 

**구문**  
다음 구문을 사용합니다.

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

**aggregation**
+ 필수.
+ 필드에 적용되는 집계 함수입니다.

**by-clause**
+ 선택 사항.
+ 구문: `by [span-expression,] [field,]...`
+ 집계 결과를 그룹화하기 위한 필드와 표현식을 지정합니다. by-clause는 필드와 표현식을 사용하여 집계 결과를 그룹화할 수 있도록 합니다. 스칼라 함수, 집계 함수 및 범위 표현식을 사용하여 특정 필드를 동일한 간격의 버킷으로 분할할 수 있습니다.
+ 기본값: `<by-clause>`를 지정하지 않으면 stats 명령은 전체 결과 집합에 대한 집계를 나타내는 단일 행을 반환합니다.

**span 표현식**  

+ 선택 사항, 최대 1개.
+ 구문: `span(field_expr, interval_expr)`
+ interval 표현식의 단위는 기본적으로 자연 단위입니다. 필드가 날짜 및 시간 유형 필드이고 간격이 날짜/시간 단위인 경우, 간격 표현식에 단위를 지정합니다.
+ 예를 들어 `age` 필드를 10년 단위의 버킷으로 분할하면 `span(age, 10)`과 비슷하게 보입니다. 타임스탬프 필드를 1시간 간격으로 분할하려면 `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**  
`TAKE(field [, size])`를 사용하여 필드의 원래 값을 반환합니다. 값의 순서를 보장하지는 않습니다.

**필드**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**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: 필드의 고유 개수 계산**  
필드의 고유 값 수를 가져오려면 `COUNT` 대신 `DISTINCT_COUNT`(또는 `DC`) 함수를 사용할 수 있습니다. 이 예에서는 모든 계정의 성별 필드 수와 고유 수를 모두 계산합니다.

```
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`
```

#### subquery 명령
<a name="supported-ppl-subquery-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`subquery` 명령을 사용하여 파이프 처리 언어(PPL) 문 내에서 복잡한 중첩 쿼리를 수행합니다.

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

이 예에서 기본 검색(`source=logs`)은 하위 쿼리(`source=events`)의 결과를 기준으로 필터링됩니다.

subquery 명령은 복잡한 데이터 분석을 위해 여러 수준의 중첩을 지원합니다.

**중첩 하위 쿼리 예**  


```
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 ]`(subquery로 필터링 검색)
+ `source = outer a not in [ source = inner | fields b ]`(subquery로 필터링 검색)
+ `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 ]`(subquery로 필터링 검색)
+ `source = outer not exists [ source = inner | where a = c ]`(subquery로 필터링 검색)
+ `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 ]`(상관 관계가 없는 exists)
+ `source = outer | where not exists [ source = inner | where c > 10 ]`(상관 관계가 없는 exists)
+ `source = outer | where exists [ source = inner ] | eval l = "nonEmpty" | fields l`(특별한 형태의 상관 관계가 없는 exists)

**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`

Where에서:
+ `source = outer | where a > [ source = inner | stats min(c) ] | fields a`

Search 필터에서:
+ `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`

Where에서:
+ `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`

Search 필터에서:
+ `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`는 하위 쿼리 표현식이 아니며 Join 또는 From 절에서 일반적으로 사용되는 하위 쿼리 계획입니다.
+ `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 명령:

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

Search 필터

```
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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`top` 명령을 사용하여 필드 목록에서 모든 필드 값의 가장 흔한 튜플을 찾습니다.

**구문**  
다음 구문을 사용합니다.

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

**N**
+ 반환할 결과 수.
+ 기본값: 10

**field-list**
+ 필수.
+ 쉼표로 구분된 필드 이름의 목록입니다.

**by-clause**
+ 선택 사항.
+ 결과를 그룹화할 하나 이상의 필드입니다.

**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    |
+----------+-------+
```

#### trendline 명령
<a name="supported-ppl-trendline-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#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**
+ 필수.
+ 이동 평균을 계산하는 데이터 포인트의 수입니다.
+ 0보다 커야 합니다.

**필드**
+ 필수.
+ 이동 평균을 계산해야 하는 필드의 이름입니다.

**별칭**
+ 선택 사항.
+ 이동 평균을 포함하는 결과 열의 이름입니다.

단순 이동 평균(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를 기준으로 내림차순으로 정렬된 2개 및 3개의 데이터 포인트를 사용하여 온도에 대한 2개의 단순 이동 평균을 계산합니다.

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|
+-----------+---------+--------------------+------------+------------------+
```

#### where 명령
<a name="supported-ppl-where-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`where` 명령은 부울 표현식을 사용하여 검색 결과를 필터링합니다. 부울 표현식이 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>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`fieldsummary` 명령을 사용하여 각 필드의 기본 통계(개수, 고유 개수, 최소, 최대, 평균, stddev, 평균)를 계산하고 각 필드의 데이터 유형을 결정합니다. 이 명령은 이전 파이프와 함께 사용할 수 있으며 이전 파이프를 고려합니다.

**구문**  
다음 구문을 사용합니다. CloudWatch Logs 사용 사례의 경우 쿼리에서 하나의 필드만 지원됩니다.

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

**includefields**
+ 통계를 사용하여 통합 결과 집합으로 수집할 모든 열의 목록입니다.

**NULL**
+ 선택 사항.
+  true로 설정된 경우 집계 계산에 null 값을 포함합니다(숫자 값의 경우 null을 0으로 대체).

**예제 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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

`expand` 명령을 사용하여 Array<Any> 또는 Map<Any> 유형의 필드를 평면화하여 각 요소 또는 키-값 페어마다 개별 행을 생성합니다.

**구문**  
다음 구문을 사용합니다.

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

**필드**
+ 확장할 필드입니다.
+ 필드는 지원되는 유형이어야 합니다.

**별칭**
+ 선택 사항.
+ 원래 필드 이름 대신 사용할 이름입니다.

**사용 지침**  
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 등과 같은 다른 명령과 함께 사용할 수 있습니다. 여러 expand 명령을 사용하면 각 복합 배열 또는 맵 내의 모든 내부 요소의 데카르트 곱이 생성됩니다.

**효과적인 SQL 푸시 다운 쿼리**  
expand 명령은 LATERAL VIEW 분해를 사용하여 동등한 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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

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

**설명**: `isnull(field)`은 필드가 null인 경우 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>

**설명**: `isnotnull(field)`은 필드가 null이 아닌 경우 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>

**설명**: `ifnull(field1, field2)`은 `field1`이 null이면 `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>

**설명**: `if(condition, expr1, expr2)`는 조건이 true이면 `expr1`을 반환하고, 그렇지 않으면 `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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

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

MD5는 MD5 다이제스트를 계산하고 값을 32자 16진수 문자열로 반환합니다.

**사용량**: `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의 16진수 문자열 결과를 반환합니다.

**사용량**: `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)의 16진수 문자열 결과를 반환합니다. 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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#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 에포크 시간) 범위를 벗어날 경우 `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

**인수 유형**: 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>

**사용**: `NOW`는 현재 날짜 및 시간을 'YYYY-MM-DD hh:mm:ss' 형식의 `TIMESTAMP` 값으로 반환합니다. 이 값은 클러스터 시간대로 표시됩니다.

**참고**  
`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

**반의어:** `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>

**사용**: `SYSDATE()`는 현재 날짜 및 시간을 'YYYY-MM-DD hh:mm:ss.nnnnnn' 형식의 `TIMESTAMP` 값으로 반환합니다.

`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`이 문자열인 경우 타임스탬프로 해석됩니다. 문자열이 아닌 인수의 경우 이 함수는 UTC 시간대를 사용하여 `expr`을 타임스탬프로 캐스팅합니다. `expr`이 `TIME` 값인 경우 이 함수는 캐스팅 전 오늘 날짜를 적용합니다.

두 인수와 함께 사용할 경우 `TIMESTAMP(expr1, expr2)`는 날짜 또는 타임스탬프 표현식(`expr2`)에 시간 표현식(`expr1`)을 추가하고 결과를 타임스탬프 값으로 반환합니다.

**인수 유형**: STRING/DATE/TIME/TIMESTAMP

**반환 유형 맵**:

(STRING/DATE/TIME/TIMESTAMP) -> TIMESTAMP

(STRING/DATE/TIME/TIMESTAMP, STRING/DATE/TIME/TIMESTAMP) -> 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년 초에 시작된 에포크 이후 경과된 초)으로 변환합니다. 인수가 제공되지 않으면 현재 Unix 시간을 반환합니다.

날짜 인수는 `DATE`, `TIMESTAMP` 문자열 또는 `YYMMDD`, `YYMMDDhhmmss`, `YYYYMMDD`, `YYYYMMDDhhmmss` 형식 중 하나의 숫자일 수 있습니다. 인수에 시간 구성 요소가 포함된 경우 선택적으로 소수 초를 포함할 수 있습니다.

인수가 잘못된 형식이거나 1970-01-01 00:00:00 to 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 범위로 날짜의 연도를 반환하거나, 날짜가 '0'인 경우 0을 반환합니다.

**인수 유형**: 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

**반의어:** `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

**반의어:** `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: INTERVAL(SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR) 
+ integer: INTEGER 
+ date: 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: INTERVAL(SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR) 
+ start: DATE, TIMESTAMP 또는 STRING 
+ end: 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>

**사용**: `UTC_TIMESTAMP`는 현재 UTC 타임스탬프를 'YYYY-MM-DD hh:mm:ss' 형식의 값으로 반환합니다.

**반환 유형**: 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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

표현식, 특히 값 표현식은 스칼라 값을 반환합니다. 표현식의 유형과 형식은 다릅니다. 예를 들어 원자 표현식과 그에 따라 작성된 산술, 조건자 및 함수 표현식으로 리터럴 값이 존재합니다. `Filter` 및 `Stats` 명령에 산술 표현식을 사용하는 등, 다양한 절에서 표현식을 사용할 수 있습니다.

**연산자**

산술 표현식은 다음과 같이 숫자 리터럴과 바이너리 산술 연산자로 구성된 표현식입니다.

1. `+`: 더하기.

1. `-`: 빼기.

1. `*`: 곱하기.

1. `/`: 나누기(정수의 경우 결과는 소수 부분이 삭제된 정수)

1. `%`: 모듈로(정수에만 사용, 결과는 나누기의 나머지)

**우선 순위**

괄호를 사용하여 산술 연산자의 우선순위를 제어합니다. 그렇지 않으면 우선순위가 더 높은 연산자가 먼저 수행됩니다.

**유형 변환**

연산자 서명을 조회할 때 암시적 유형 변환이 수행됩니다. 예를 들어 정수 `+` 실수는 서명 `+(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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#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`은 모두 유효하고 비어 있지 않거나 null이 아니어야 합니다.

##### PPL JSON 함수
<a name="supported-ppl-json-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#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>는 문자열이어야 합니다.
+ <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_extract(jsonStr, path)`는 지정된 JSON 경로를 기반으로 JSON 문자열에서 JSON 객체를 추출합니다. 입력 JSON 문자열이 유효하지 않은 경우 이 함수는 null을 반환합니다.

**인수 유형**: STRING, STRING

**반환 유형**: STRING
+ 유효한 JSON 객체 형식의 STRING 표현식입니다.
+ JSON이 잘못된 경우 `NULL`이 반환됩니다.

**예**:

```
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]. 이 함수는 다른 유효한 JSON 문자열, 빈 문자열 또는 잘못된 JSON에 대해 `NULL`을 반환합니다.

**예**:

```
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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

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

**사용**: `exists(array, lambda)`는 Lambda 조건자가 배열의 하나 이상의 요소에 대해 보유하는지 여부를 평가합니다.

**인수 유형**: ARRAY, LAMBDA

**반환 유형**: BOOLEAN. 배열의 하나 이상의 요소가 Lambda 조건자를 충족하는 경우 `TRUE`를 반환하고, 그렇지 않으면 `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>

**사용량**: `filter(array, lambda)`는 지정된 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>

**사용**: `transform(array, lambda)`은 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>

**사용**: `reduce(array, start, merge_lambda, finish_lambda)`는 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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#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의 아크 코사인을 계산합니다. x가 -1\~1 범위에 속하지 않으면 `NULL`을 반환합니다.

**인수 유형**: 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의 아크 사인을 계산합니다. x가 -1\~1 범위에 속하지 않으면 `NULL`을 반환합니다.

**인수 유형**: 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 -> 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>

**사용**: `CONV(x, a, b)`는 x를 a 진법에서 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가 0과 같으면 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>

**사용**: `DEGREES(x)`는 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()`는 오일러 수를 반환합니다.

**반환 유형**: 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의 기본 e 로그를 반환합니다. log(B, x)는 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이 0 이외의 값인 경우 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>

**사용**: `RADIANS(x)`는 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>

**사용량**: `ROUND(x, d)`는 인수 x를 소수점 이하 자릿수로 반올림합니다. d를 지정하지 않을 경우 기본값은 0입니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형 맵**:
+ (INTEGER/LONG [,INTEGER]) -> LONG
+ (FLOAT/DOUBLE [,INTEGER]) -> LONG

**예:**

```
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`은 숫자가 음수, 0 또는 양수인지에 따라 인수의 부호를 -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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#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>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#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 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 | 
| BOOLEAN | Note1 | v?1:0 |  | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 | 
| TIMESTAMP | Note1 | 해당 사항 없음 | 해당 사항 없음 |  | DATE() | TIME() | 
| DATE | Note1 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 |  | 해당 사항 없음 | 
| TIME | Note1 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 |  | 

**문자열로 캐스팅 예:**

```
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    |
+---------+
```