시맨틱 뷰용 YAML 사양
시맨틱 뷰용 YAML 사양
시맨틱 뷰는 데이터 위에 비즈니스 개념을 정의하는 스키마 수준 객체로, 사용자가 비즈니스 용어로 데이터를 더 쉽게 쿼리하고 분석할 수 있게 해줘요. YAML 사양을 사용해 Cortex Analyst에서 시맨틱 뷰를 만들거나, SYSTEM$CREATE_SEMANTIC_VIEW_FROM_YAML 저장 프로시저를 사용해 YAML 사양에서 시맨틱 뷰를 만들 수 있어요.
출처: Snowflake 문서
본문
시맨틱 뷰는 데이터 위에 비즈니스 개념을 정의하는 스키마 수준 객체로, 사용자가 비즈니스 용어로 데이터를 쿼리하고 분석하기 쉽게 해줘요. YAML 사양을 사용해 Cortex Analyst에서 시맨틱 뷰를 만들거나 SYSTEM$CREATE_SEMANTIC_VIEW_FROM_YAML 저장 프로시저로 YAML 사양에서 시맨틱 뷰를 만들 수 있어요.
YAML과 DDL 작성 방식의 비교는 Choosing between YAML and DDL for semantic views를 참고해요.
개요(Overview)
시맨틱 뷰는 Snowflake에서 비즈니스 시맨틱을 정의하는 권장 방식이에요. 시맨틱 뷰는 Snowflake의 권한 시스템, 공유 메커니즘, 메타데이터 카탈로그와 통합되는 스키마 수준 객체예요.
참고: 레거시 시맨틱 모델 YAML 파일(스테이지에 저장)은 이전 버전과의 호환을 위해 Cortex Analyst에서 계속 사용할 수 있지만, 새 구현에는 시맨틱 뷰를 권장해요.
레거시 시맨틱 모델에 비해 시맨틱 뷰의 이점은 다음과 같아요:
- 네이티브 Snowflake 통합: 완전한 RBAC, 공유, 카탈로그 지원을 갖춘 스키마 수준 객체
- 고급 기능: 파생 메트릭(derived metrics)과 액세스 수정자(public/private) 지원
- 더 나은 거버넌스: Snowflake의 권한 및 공유 시스템과 통합
- 간소화된 관리: 스테이지에서 YAML 파일을 관리할 필요 없음
YAML 형식
시맨틱 뷰는 YAML 사양으로 동작을 정의할 수 있어, 읽기 쉽고 일반 텍스트로 된 정의가 가능해요.
시맨틱 뷰 YAML 사양의 일반적인 구문은 다음과 같아요:
# Name and description of the semantic view.
name: <name>
description: <string>
# Logical table-level concepts
# A semantic view can contain one or more logical tables.
tables:
# A logical table on top of a base table.
- name: <name>
description: <string>
# The fully qualified name of the base table, or a SQL query definition.
base_table:
database: <database>
schema: <schema>
table: <base table name>
# Or, instead of database/schema/table, specify a SQL query:
# definition: <SQL query>
primary_key: # Optional: 0 or 1 primary key.
columns: [<col1>, <col2>, ...]
unique_keys: # Optional: 0 to N unique keys.
- columns: [<col1>, <col2>, ...]
# Dimension columns in the logical table.
dimensions:
- name: <name>
synonyms: <array of strings>
description: <string>
expr: <SQL expression>
data_type: <data type>
cortex_search_service:
service: <string>
literal_column: <string>
database: <string>
schema: <string>
is_enum: <boolean>
labels: # Optional: specify "filter" to use as a WHERE clause condition.
- filter
tags: # Optional tags for the dimension.
- name:
database: <database>
schema: <schema>
tag: <tag_name>
value: <tag_value>
- ...
# Time dimension columns in the logical table.
time_dimensions:
- name: <name>
synonyms: <array of strings>
description: <string>
expr: <SQL expression>
data_type: <data type>
# Fact columns in the logical table.
facts:
- name: <name>
synonyms: <array of strings>
description: <string>
access_modifier: <public_access | private_access> # Default is public_access.
expr: <SQL expression>
data_type: <data type>
labels: # Optional: specify "filter" to use as a WHERE clause condition.
- filter
tags: # Optional tags for the fact.
- name:
database: <database>
schema: <schema>
tag: <tag_name>
value: <tag_value>
# Regular metrics scoped to the logical table.
metrics:
- name: <name>
synonyms: <array of strings>
description: <string>
access_modifier: <public_access | private_access> # Default is public_access.
expr: <SQL expression>
non_additive_dimensions:
- table: <table name>
dimension: <dimension name>
sort_direction: <ascending | descending>
null_order: <first | last>
using_relationships:
- <relationship_name>
tags: # Optional tags for the metric.
- name:
database: <database>
schema: <schema>
tag: <tag_name>
value: <tag_value>
# Standalone filters (entity-level filters are recommended instead).
filters:
- name: <name>
synonyms: <array of strings>
description: <string>
expr: <SQL expression>
# Optional tags for the logical table.
tags:
- name:
database: <database>
schema: <schema>
tag: <tag_name>
value: <tag_value>
# View-level concepts
# Relationships between logical tables
relationships:
- name: <string>
left_table: <table>
right_table: <table>
relationship_columns:
- left_column: <column>
right_column: <column>
type: <asof | range> # Optional: defaults to equality join.
right_range: # Required when type is "range".
start_column: <column>
end_column: <column>
- left_column: <column>
right_column: <column>
# Variables for parameterized semantic views
variables:
- name: <name>
data_type: <data type>
default_value: <string> # Optional: default value for the variable.
description: <string> # Optional: description of the variable.
# Derived metrics scoped to the semantic view.
# Derived metrics combine metrics from multiple tables.
metrics:
- name: <name>
synonyms: <array of strings>
description: <string>
access_modifier: <public_access | private_access> # Default is public_access
expr: <SQL expression>
tags: # Optional tags for the derived metric.
- name:
database: <database>
schema: <schema>
tag: <tag_name>
value: <tag_value>
# Additional context concepts
# Verified queries with example questions and queries that answer them
verified_queries:
- name: <string> # A descriptive name of the query.
question: <string> # The natural language question that this query answers.
verified_at: <int> # Optional: Time (in seconds since the UNIX epoch, January 1, 1970) when the query was verified.
verified_by: <string> # Optional: Name of the person who verified the query.
use_as_onboarding_question: <boolean> # Optional: Marks this question as an onboarding question for the end user.
sql: <string> # The SQL query for answering the question
# Custom instructions for Cortex Analyst
# Freeform guidance for SQL generation (legacy; prefer module_custom_instructions).
custom_instructions: <string>
# Module-scoped custom instructions for Cortex Analyst
module_custom_instructions:
sql_generation: <string> # Instructions for SQL generation
question_categorization: <string> # Instructions for classifying user questions
# Maximum staleness for materializations (in seconds).
# Required to add materializations to the semantic view.
# Example: 7200 sets a 2-hour maximum staleness.
max_staleness: <integer>
# Optional tags for the semantic view itself.
tags:
- name:
database: <database>
schema: <schema>
tag: <tag_name>
value: <tag_value>
중요: 시맨틱 뷰는 레거시 시맨틱 모델에서 사용된
join_type또는relationship_type필드를 요구하지 않아요. 관계 유형은 데이터에서 자동으로 유추돼요.
핵심 개념(Key concepts)
테이블(Tables)
논리 테이블은 비즈니스 엔티티(예: 고객, 주문, 제품)를 나타내며 물리적 데이터베이스 테이블이나 SQL 쿼리에 매핑돼요. 각 논리 테이블은 다음을 정의할 수 있어요:
- 기본 테이블(Base table): 물리적 테이블의 정규화된 이름, 또는
definition속성을 사용한 SQL 쿼리 - 기본 키(Primary key): 각 행을 고유하게 식별하는 값의 컬럼(테이블당 0 또는 1개)
- 고유 키(Unique keys): 값이 행 전체에서 고유한 추가 컬럼(테이블당 0~N개)
- 동의어(Synonyms): 테이블의 대체 이름
- 설명(Description): 테이블이 무엇을 나타내는지에 대한 비즈니스 친화적인 설명
primary_key
각 행을 고유하게 식별하는 값의 컬럼이에요. 테이블은 기본 키를 0 또는 1개 가질 수 있어요.
primary_key:
columns: [customer_id]
unique_keys
값이 행 전체에서 각각 고유한 추가 컬럼이에요. 테이블은 고유 키를 0~N개 가질 수 있어요.
unique_keys:
- columns: [email]
- columns: [region, account_number]
물리적 테이블 대신 SQL 쿼리를 지정하려면 database, schema, table 대신 base_table 아래의 definition 속성을 사용해요. 자세한 내용은 Using an SQL query as a logical table을 참고해요.
차원(Dimensions)
차원은 분석에 컨텍스트를 제공하는 범주형 속성을 나타내요. "누가, 무엇을, 어디서, 언제" 질문에 답해요. 차원은 다음이 될 수 있어요:
- 일반 차원(Regular dimensions): 텍스트, 숫자 또는 다른 범주형 값
- 시간 차원(Time dimensions): 특별한 시간 기반 처리가 있는 날짜 또는 타임스탬프 컬럼
차원의 속성
expr: 차원 값을 계산하는 SQL 표현식synonyms: 사용자가 사용할 수 있는 대체 용어is_enum: 차원이 고정된 값 집합을 갖는지 여부cortex_search_service: 시맨틱 검색을 위한 선택적 Cortex Search 서비스labels: 이 차원이 WHERE 절의 조건으로 사용될 수 있음을 나타내도록[filter]로 설정(표현식은 BOOLEAN으로 해석되어야 함)
물리적 차원의 선택적 속성
이 필드들은 선택사항이지만, 시맨틱 뷰 검색에서 더 높은 품질의 결과를 얻기 위해 권장돼요.
synonyms— 이 차원을 참조하는 데 사용되는 다른 용어/구의 목록. 이 시맨틱 모델의 모든 동의어에서 고유해야 해요.description— 이 차원에 대한 간단한 설명. 이 차원이 나타내는 데이터 같은 유용한 컨텍스트를 제공하는 정보를 포함해요.sample_values— 이 컬럼의 샘플 값(있는 경우). 사용자 질문에서 참조될 가능성이 있는 값을 추가해요.is_enum— 불리언 값.True이면sample_values필드의 값이 가능한 값의 전체 목록으로 간주되고, 모델은 그 컬럼을 필터링할 때 그 값들에서만 선택해요.cortex_search_service— 이 차원에 사용할 Cortex Search Service를 지정해요. 다음 필드가 있어요:service: Cortex Search Service의 이름literal_column: (선택) 리터럴 값을 포함하는 Cortex Search Service의 컬럼database: (선택) Cortex Search Service가 위치한 데이터베이스. 기본값은base_table의 데이터베이스schema: (선택) Cortex Search Service가 위치한 스키마. 기본값은base_table의 스키마
cortex_search_service는 이름만 지정할 수 있었던 cortex_search_service_name 필드를 대체해요. cortex_search_service_name은 더 이상 사용되지 않아요(deprecated).
시간 차원의 선택적 속성
이 필드들은 선택사항이지만, 시맨틱 뷰 검색에서 더 높은 품질의 결과를 얻기 위해 권장돼요.
synonyms— 이 시간 차원을 참조하는 데 사용되는 다른 용어/구의 목록. 이 시맨틱 모델의 모든 동의어에서 고유해야 해요.description— 이 차원에 대한 간단한 설명. 이 차원이 기준점으로 사용하는 시간대 같은 유용한 컨텍스트를 제공하는 정보를 포함해요.sample_values— 이 컬럼의 샘플 값(있는 경우). 사용자 질문에서 참조될 가능성이 있는 값을 추가해요.
Fact
Fact는 특정 비즈니스 이벤트나 트랜잭션을 나타내는 행 수준(row-level) 정량 속성이에요. Fact는 개별 판매 금액, 구매 수량, 비용처럼 가장 세부적인 수준에서 "얼마나"(how much/how many)를 포착해요. Fact는 대개 시맨틱 뷰 안에서 dimension과 metric을 구성하는 데 도움이 되는 "헬퍼" 개념으로 기능해요.
Fact의 속성은 다음과 같아요:
expr: fact 값을 계산하는 SQL 표현식access_modifier: 쿼리에서 숨기려면private_access로 설정(중간 계산에 유용)data_type: fact의 데이터 타입labels: 이 fact가 WHERE 절의 조건으로 사용될 수 있음을 나타내도록[filter]로 설정(표현식은 BOOLEAN으로 해석되어야 함)
메트릭(Metrics)
메트릭은 SUM, AVG, COUNT 같은 함수로 fact나 다른 컬럼을 집계해 계산된 비즈니스 성과의 정량적 측정값이에요.
두 가지 유형의 메트릭이 있어요:
- 테이블 수준 메트릭(Table-level metrics): 특정 논리 테이블에 한정되며, 그 테이블 안의 데이터를 집계
- 파생 메트릭(Derived metrics): 여러 테이블의 메트릭을 결합하는 뷰 수준 메트릭
메트릭의 속성
expr: 집계 함수가 있는 SQL 표현식access_modifier: 쿼리에서 숨기려면private_access로 설정(중간 계산에 유용)synonyms: 메트릭의 대체 용어
메트릭의 선택적 속성
메트릭에 대해 비가산(non-additive)이어야 할 dimension을 지정하려면 다음 필드를 사용해요:
non_additive_dimensions— 메트릭이 집계되지 않아야 하는 dimension을 지정해요.table— dimension을 포함하는 논리 테이블의 이름dimension— dimension의 이름sort_direction— 비가산 dimension의 정렬 순서. 다음 값 중 하나를 지정할 수 있어요:ascending: dimension 값을 오름차순으로 정렬descending: dimension 값을 내림차순으로 정렬- 기본값:
ascending
null_order— NULL이 비-NULL 값보다 앞 또는 뒤에 정렬되는지 여부를 지정해요. 다음 값 중 하나를 지정할 수 있어요:first: NULL이 비-NULL 값보다 앞에 정렬됨last: NULL이 비-NULL 값보다 뒤에 정렬됨- 기본값:
sort_direction필드 값(ascending/descending)에 따라 달라짐. ORDER BY 문서의 사용 참고를 보세요.
참고: 행이 비가산 dimension으로 정렬되므로 dimension을 지정하는 순서가 중요해요. 이는 ORDER BY 절에서 컬럼을 지정하는 순서와 비슷해요.
다음 예시는 m_account_balance 메트릭이 year_dim과 month_dim dimension으로 집계될 수 없음을 지정해요:
metrics:
- name: m_account_balance
...
non_additive_dimensions:
- table: bank_accounts
dimension: year_dim
sort_direction: ascending
null_order: last
- table: bank_accounts
dimension: month_dim
sort_direction: descending
null_order: first
시맨틱 뷰에서 두 특정 논리 테이블 사이에 여러 관계 경로가 있다면, 사용할 관계 경로를 지정하려면 using_relationships 필드를 사용해요.
미리 보기 기능(Preview Feature) — 오픈이며 모든 계정에서 사용할 수 있어요. 메트릭을 계산할 때 논리 테이블을 조인하는 데 사용할 관계의 이름을 지정해요.
파생 메트릭(Derived metrics)
파생 메트릭은 특정 테이블에 묶이지 않은 뷰 수준 메트릭이에요. 여러 테이블의 메트릭을 결합하거나 뷰 전체에 걸쳐 계산을 수행할 수 있어요.
파생 메트릭 예시:
metrics:
- name: total_profit_margin
description: "Overall profit margin across all products"
expr: (orders.total_revenue - orders.total_cost) / orders.total_revenue
access_modifier: public_access
관계(Relationships)
관계는 논리 테이블이 어떻게 조인되는지 정의해요. 각 관계는 다음을 지정해요:
left_table: 외래 키를 포함하는 테이블right_table: 참조되는 테이블relationship_columns:left_column과right_column으로 조인할 컬럼 쌍
관계 유형(일대일, 다대일)은 데이터와 기본 키 정의에서 자동으로 유추돼요.
참고: 레거시 시맨틱 모델과 달리, 시맨틱 뷰는 명시적인
join_type또는relationship_type사양이 필요하지 않아요. 이들은 자동으로 결정돼요.
기본 관계
relationships:
- name: orders_to_customers
left_table: orders
right_table: customers
relationship_columns:
- left_column: customer_id
right_column: customer_id
다중 컬럼 조인
관계에 여러 컬럼이 필요하면(복합 외래 키), 각 쌍을 relationship_columns에 나열해요:
relationships:
- name: lineitem_to_partsupp
left_table: lineitem
right_table: partsupp
relationship_columns:
- left_column: l_partkey
right_column: ps_partkey
- left_column: l_suppkey
right_column: ps_suppkey
일대일 관계
관계의 양쪽 모두 조인 컬럼을 기본 키의 일부로 선언하면 일대일 관계가 자동으로 유추돼요:
tables:
- name: customer_basic
primary_key:
columns: [customer_id]
- name: customer_details
primary_key:
columns: [customer_id]
relationships:
- name: details_to_basic
left_table: customer_details
right_table: customer_basic
relationship_columns:
- left_column: customer_id
right_column: customer_id
ASOF 관계
ASOF 관계는 시점(point-in-time) 조회를 기반으로 테이블을 조인하며, 주로 느린 변화 차원(SLOWLY CHANGING DIMENSION)에 사용돼요. 정확히 일치하는 값 대신 가장 최근 값을 찾아 일치시키려는 관계 컬럼에 type: asof를 설정해요:
relationships:
- name: orders_to_address
left_table: orders
right_table: customer_address
relationship_columns:
- left_column: o_custid
right_column: ca_custid
- left_column: o_orddate
right_column: ca_start_date
type: asof
이 예시에서 각 주문은 주문 날짜 기준으로 가장 최근에 유효했던 고객 주소와 매칭돼요.
범위(범위) 관계
범위 관계는 값이 대상 테이블의 두 컬럼으로 정의된 범위 안에 들어갈 때(예: 시작 날짜와 종료 날짜 사이의 날짜) 테이블을 조인해요. type: range를 설정하고 시작·종료 컬럼이 있는 right_range를 제공해요:
relationships:
- name: orders_to_address
left_table: orders
right_table: customer_address
relationship_columns:
- left_column: o_custid
right_column: ca_custid
- left_column: o_orddate
right_column: ca_start_date
type: range
right_range:
start_column: ca_start_date
end_column: ca_end_date
이 예시에서 각 주문은 유효 기간이 주문 날짜를 포함하는 고객 주소와 매칭돼요.
브리지 테이블을 통한 다대다 관계
다대다 관계는 브리지(접합) 테이블에서 두 엔티티 테이블로의 두 관계를 정의해 표현해요. 시스템은 관계 그래프에서 다대다 경로를 유추해요:
tables:
- name: authors
primary_key:
columns: [author_id]
- name: books
primary_key:
columns: [book_id]
- name: book_authors
primary_key:
columns: [book_id, author_id]
relationships:
- name: ba_to_authors
left_table: book_authors
right_table: authors
relationship_columns:
- left_column: author_id
right_column: author_id
- name: ba_to_books
left_table: book_authors
right_table: books
relationship_columns:
- left_column: book_id
right_column: book_id
역할 재사용(Role-playing) 테이블
단일 물리적 테이블이 다른 역할을 모델링하기 위해 다른 논리 테이블 이름으로 여러 번 나타날 수 있어요. 같은 base_table을 가리키는 다른 name 값을 사용해요:
tables:
- name: customer_region
base_table:
database: my_db
schema: my_schema
table: region
primary_key:
columns: [r_regionkey]
- name: supplier_region
base_table:
database: my_db
schema: my_schema
table: region
primary_key:
columns: [r_regionkey]
relationships:
- name: customer_nation_to_region
left_table: customer_nation
right_table: customer_region
relationship_columns:
- left_column: n_regionkey
right_column: r_regionkey
- name: supplier_nation_to_region
left_table: supplier_nation
right_table: supplier_region
relationship_columns:
- left_column: n_regionkey
right_column: r_regionkey
필터(Filters)
시맨틱 뷰 YAML 사양에서 필터를 정의하는 방법은 두 가지가 있어요:
엔티티 수준 필터(labels 사용): 정의에 labels: [filter]를 추가해 dimension이나 fact를 필터로 표시할 수 있어요. 표현식은 BOOLEAN 값으로 해석되어야 해요. 이것은 CREATE SEMANTIC VIEW 명령의 LABELS = (FILTER)와 동등한 YAML 방식이에요.
dimensions:
- name: high_value
expr: loyalty_points > 100
labels:
- filter
facts:
- name: completed_only
expr: is_completed
labels:
- filter
자세한 내용은 Defining a filter을 참고해요.
독립형 필터(Standalone filters): filters 필드를 사용해 테이블 수준에서 독립형 필터 표현식을 정의할 수 있어요. 독립형 필터는 Cortex Analyst SQL 생성에서 지원되지만, Snowflake 시맨틱 SQL 컴파일러는 엔티티 수준 필터(labels로 정의)를 사용해요. 더 넓은 호환성을 위해 엔티티 수준 필터를 사용하는 것을 권장해요.
filters:
- name: active_customers
description: "Customers who have made a purchase in the last 12 months"
expr: "customer_last_purchase_date >= DATEADD(month, -12, CURRENT_DATE())"
검증 쿼리(Verified queries)
검증 쿼리는 해당 SQL 쿼리가 있는 예시 질문이에요. Cortex Analyst가 비슷한 질문에 답하는 방법을 이해하고 사용자에게 문서화 역할을 제공해요.
속성:
question: 자연어 질문sql: 그 질문에 답하는 SQL 쿼리verified_by: 쿼리가 올바른지 검증한 선택적 사람verified_at: 검증된 시각의 선택적 타임스탬프use_as_onboarding_question: 사용자에게 이것을 추천으로 표시하는 선택적 플래그
태그(Tags)
태그를 시맨틱 뷰와 그 안의 속성(논리 테이블, dimension, fact, metric 포함)에 할당할 수 있어요. 태그는 민감한 데이터를 추적하고, 거버넌스 정책을 관리하며, 시맨틱 뷰 객체를 구성하는 데 도움을 줘요.
각 태그 참조는 정규화된 태그 이름(database, schema, tag)과 value를 지정해요:
tags:
- name:
database: my_db
schema: my_schema
tag: pii_type
value: "email"
다음 수준에서 태그를 할당할 수 있어요:
- 시맨틱 뷰(최상위
tags): 시맨틱 뷰 객체 자체의 태그 - 논리 테이블(테이블 아래의
tags): 시맨틱 뷰 안의 논리 테이블 태그 - Dimension(dimension 아래의
tags): 특정 dimension 태그 - Fact(fact 아래의
tags): 특정 fact 태그 - Metric(metric 아래의
tags): 파생 메트릭을 포함한 특정 metric 태그
각 수준에서 여러 태그를 할당할 수 있어요. 객체 태깅에 대한 자세한 내용은 Introduction to object tagging을 참고해요.
액세스 수정자(Access modifiers)
시맨틱 뷰는 fact와 metric에 대한 액세스 수정자를 지원해 가시성을 제어할 수 있어요:
public_access(기본값): 사용자에게 표시되고 쿼리 가능private_access: 쿼리에서 숨겨지며 중간 계산에만 사용
예시:
facts:
- name: internal_cost
expr: unit_cost * quantity
data_type: NUMBER
access_modifier: private_access # Not visible in queries
metrics:
- name: total_revenue
expr: SUM(sale_amount)
access_modifier: public_access # Visible in queries
Cortex Analyst용 Custom instructions
Custom instructions를 사용하면 Cortex Analyst가 SQL을 생성하는 방식과 사용자 질문을 분류하는 방식을 제어할 수 있어요. YAML 사양의 최상위 키로 custom instructions를 지정하거나, CREATE SEMANTIC VIEW 명령으로 설정할 수 있어요(Providing custom instructions for Cortex Analyst 참고).
자세한 안내와 예시는 Custom instructions in Cortex Analyst을 참고해요.
custom_instructions
SQL 생성에 대한 지침을 제공하는 단일 자유 형식 문자열이에요. 예를 들어:
custom_instructions: "Ensure that all numeric columns are rounded to 2 decimal points in the output."
중요: 기존
custom_instructions를 다음 섹션에 설명된 대로module_custom_instructions의sql_generation구성 요소로 마이그레이션하세요.
module_custom_instructions
모듈 범위(MODULE-scoped) custom instructions는 Cortex Analyst 파이프라인의 특정 구성 요소를 대상으로 더 세밀한 제어를 제공해요. YAML 사양의 최상위에 module_custom_instructions 키를 다음 구성 요소 중 하나 또는 둘 다로 설정해요:
sql_generation— SQL을 생성하는 방법에 대한 지침(예: 데이터 형식 지정과 필터링)question_categorization— Cortex Analyst가 사용자 질문을 분류하는 방법에 대한 지침(예: 특정 주제 차단 또는 누락된 세부 정보 요청)
예시:
module_custom_instructions:
sql_generation: |
Ensure that all numeric columns are rounded to 2 decimal points.
For any percentage or rate calculation, multiply the result by 100.
question_categorization: |
If the question asks for users without providing a product_type, consider this question
UNCLEAR and ask the user to specify product_type.
Reject all questions about salary data.
Cortex Agent를 통해 Cortex Analyst를 사용하면 에이전트가 custom instructions를 직접 따릅니다. UNCLEAR 같은 범주화 상태 키워드를 참조하지 않고 일반 자연어로 질문 분류 지침을 작성할 수 있어요. 자세한 내용은 Custom instructions through Cortex Agents를 참고해요.
변수(Variables)
변수를 사용하면 소비자가 쿼리 시 파라미터를 전달해 dimension, fact, metric 표현식을 파라미터화할 수 있어요. YAML 사양의 최상위에 변수를 정의해요:
variables:
- name: threshold
data_type: NUMBER(5,1)
default_value: "42"
- name: category_filter
data_type: STRING
description: Filter by product category
속성:
name: 표현식에서 참조되는 변수 이름data_type: 변수의 Snowflake 데이터 타입(예:NUMBER,STRING,FLOAT)default_value: 쿼리 시 변수가 제공되지 않을 때 사용되는 선택적 기본값description: 변수 용도의 선택적 설명
변수 이름을 직접 참조해 dimension, fact, metric 표현식에서 변수를 사용해요:
tables:
- name: orders
dimensions:
- name: above_threshold
expr: order_total > threshold
data_type: BOOLEAN
metrics:
- name: total_above_threshold
expr: SUM(CASE WHEN order_total > threshold THEN order_total ELSE 0 END)
variables:
- name: threshold
data_type: NUMBER
default_value: "100"
시맨틱 뷰를 쿼리할 때 VARIABLES 절로 변수 값을 전달해요:
SELECT * FROM SEMANTIC_VIEW(
my_sv
DIMENSIONS orders.above_threshold
METRICS orders.total_above_threshold
VARIABLES threshold => 500
);
사전 집계된 Fact(Pre-aggregated facts)
Fact는 관련 테이블에 대한 집계 표현식을 포함할 수 있어, 테이블의 세분성(grain)으로 사전 집계된 값을 만들어요. 이는 더 높은 세분성의 테이블이 더 낮은 세분성의 관련 테이블의 데이터 요약이 필요할 때 유용해요:
tables:
- name: customer
facts:
- name: f_revenue
expr: SUM(orders.f_order_total)
data_type: NUMBER
- name: f_order_count
expr: COUNT(orders.f_orderkey)
data_type: NUMBER
- name: orders
facts:
- name: f_order_total
expr: o_totalprice
data_type: NUMBER
- name: f_orderkey
expr: o_orderkey
data_type: NUMBER
차원과 fact에서의 윈도우 함수
차원과 fact는 순위, 누적 계산, lag/lead 값을 위한 윈도우 함수 표현식을 지원해요:
tables:
- name: sales
dimensions:
- name: category_rank
expr: "DENSE_RANK() OVER (PARTITION BY quarter ORDER BY revenue DESC)"
data_type: NUMBER
- name: prev_quarter_category
expr: "LAG(subcategory, 1) OVER (PARTITION BY quarter ORDER BY id)"
data_type: TEXT
facts:
- name: running_total_units
expr: "SUM(units_sold) OVER ()"
data_type: NUMBER
- name: rolling_avg_revenue
expr: "AVG(revenue) OVER (PARTITION BY category ORDER BY quarter ROWS BETWEEN 1 PRECEDING AND CURRENT ROW)"
data_type: NUMBER
윈도우 함수는 메트릭 표현식에서도 지원돼요. PARTITION BY EXCLUDING 구문은 이름이 지정된 것을 제외한 모든 선택된 dimension으로 파티션을 나눠요:
metrics:
- name: sales_moving_avg_7_day
expr: "AVG(lineitem.sales) OVER (ORDER BY orders.dim_day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)"
- name: running_total
expr: "SUM(store_sales.sales_amount) OVER (PARTITION BY EXCLUDING date_dim.day ORDER BY date_dim.day)"
max_staleness
YAML 사양의 최상위에 max_staleness를 설정해 시맨틱 뷰에서 구체화(materializations)를 활성화해요. 이 값은 새로고침이 트리거되기 전에 구체화된 데이터에 허용되는 최대 지연을 나타내는 정수 초(second)예요.
max_staleness: 7200 # 2 hours
최소 허용 값은 120초예요. 시맨틱 뷰에 구체화가 존재하는 동안에는 max_staleness를 해제(unset)할 수 없어요. 이 속성을 제거해야 한다면 먼저 모든 구체화를 드롭하세요. 자세한 내용은 Setting the maximum staleness of the materialized dimensions and metrics을 참고해요.
예시 시맨틱 뷰 YAML
시맨틱 뷰 YAML 사양의 완전한 예시는 다음과 같아요:
name: revenue_analysis
description: "Semantic view for analyzing revenue across products and customers"
tables:
- name: customers
description: "Customer information"
base_table:
database: sales_db
schema: public
table: customers
dimensions:
- name: customer_name
synonyms: ["client name", "customer"]
description: "Full name of the customer"
expr: c_name
data_type: VARCHAR
tags:
- name:
database: sales_db
schema: public
tag: pii_type
value: "name"
- name: customer_segment
synonyms: ["segment", "market segment"]
description: "Customer market segment"
expr: c_mktsegment
data_type: VARCHAR
is_enum: true
- name: orders
description: "Order information"
base_table:
database: sales_db
schema: public
table: orders
dimensions:
- name: order_date
description: "Date when order was placed"
expr: o_orderdate
data_type: DATE
time_dimensions:
- name: order_year
description: "Year when order was placed"
expr: YEAR(o_orderdate)
data_type: NUMBER
facts:
- name: order_total
description: "Total order amount"
expr: o_totalprice
data_type: NUMBER
metrics:
- name: total_orders
description: "Total number of orders"
expr: COUNT(*)
- name: average_order_value
description: "Average order value"
expr: AVG(o_totalprice)
relationships:
- name: orders_to_customers
left_table: orders
right_table: customers
relationship_columns:
- left_column: o_custkey
right_column: c_custkey
variables:
- name: min_order_amount
data_type: NUMBER
default_value: "100"
description: "Minimum order amount to include"
metrics:
- name: revenue_per_customer
description: "Average revenue per customer"
expr: orders.total_revenue / customers.customer_count
access_modifier: public_access
module_custom_instructions:
sql_generation: |
Always use fiscal year (April-March) for date grouping
unless the user explicitly asks for calendar year.
question_categorization: |
Classify questions about order totals and revenue as
financial questions.
verified_queries:
- name: top_customers_by_revenue
question: "Who are the top 10 customers by revenue?"
sql: |
SELECT
customer_name,
SUM(order_total) as total_revenue
FROM revenue_analysis
GROUP BY customer_name
ORDER BY total_revenue DESC
LIMIT 10
use_as_onboarding_question: true
tags:
- name:
database: sales_db
schema: public
tag: department
value: "sales"
YAML에서 시맨틱 뷰 만들기
YAML 사양에서 시맨틱 뷰를 만들려면 SYSTEM$CREATE_SEMANTIC_VIEW_FROM_YAML 저장 프로시저를 사용해요. 자세한 내용은 Creating a semantic view from a YAML specification을 참고해요.
시맨틱 뷰에서 YAML 가져오기
시맨틱 뷰를 YAML 형식으로 내보내려면 SYSTEM$READ_YAML_FROM_SEMANTIC_VIEW 함수를 사용해요. 자세한 내용은 Getting the YAML specification for a semantic view을 참고해요.
레거시 시맨틱 모델과의 차이점
스테이지 기반 YAML 파일에서 시맨틱 뷰로 마이그레이션한다면 Migrating from the legacy stage API에서 마이그레이션 안내를 참고해요.