Run Spark workloads from VS Code, Jupyter Notebooks, or a terminal¶
Jupyter Notebooks, VS Code, Spark 클러스터를 관리할 필요가 없는 Python 기반 인터페이스에서 대화형으로 Spark 워크로드를 실행할 수 있습니다. 워크로드는 Snowflake 인프라에서 실행됩니다.
예를 들면, 다음 작업을 수행할 수 있습니다.
전제 조건을 갖추고 있는지 확인합니다.
Snowflake에서 |spconnect|와 연결할 수 있는 환경을 설정합니다.
Snowpark Connect for Spark 를 설치합니다.
클라이언트에서 PySpark 코드를 실행하여 Snowflake에서 실행합니다.
전제 조건¶
Python 및 Java 설치가 동일한 컴퓨터 아키텍처에 기반을 두고 있는지 확인합니다. 예를 들어, Python이 arm64 기반인 경우 Java도 arm64여야 합니다(예: x86_64 아님).
환경 설정하기¶
코드로 Snowflake에서 |spconnect|에 연결할 수 있도록 하여 개발 환경을 설정할 수 있습니다. Snowflake 클라이언트 코드에 연결하려면, 연결 세부 정보가 포함된 .toml 파일을 사용합니다.
|sf-cli|가 설치되어 있다면 이를 사용하여 연결을 정의할 수 있습니다. 그렇지 않으면 config.toml 파일에 연결 매개 변수를 수동으로 작성할 수 있습니다.
|sf-cli|를 사용하여 연결 추가하기¶
|sf-cli|를 사용하면 |spconnect|에서 Snowflake에 연결할 수 있는 연결 속성을 추가할 수 있습니다. 변경 사항은 config.toml 파일에 저장됩니다.
다음 명령을 실행해 snow connection add 명령을 사용하는 연결을 추가합니다.
snow connection add
프롬프트에 따라 연결을 정의합니다.
:code:`spark-connect`를 연결 이름으로 지정해야 합니다.
다음 예제와 같이 이 명령은
config.toml파일에 연결을 추가합니다[connections.spark-connect] host = "example.snowflakecomputing.com" port = 443 account = "example" user = "test_example" password = "password" protocol = "https" warehouse = "example_wh" database = "example_db" schema = "public"
다음 명령을 실행하여 연결이 작동하는지 확인합니다.
|sf-cli|를 사용하여 추가한 경우 이 방법으로 연결을 테스트할 수 있습니다.
snow connection list snow connection test --connection spark-connect
연결 파일을 수동으로 작성하여 연결 추가하기¶
코드로 Snowflake에서 |spconnect|에 연결할 수 있도록 connections.toml 파일을 수동으로 작성하거나 업데이트할 수 있습니다.
다음 명령을 실행하여
connections.toml파일에서 소유자(사용자)만 읽기/쓰기 액세스 권한을 보유할 수 있도록 합니다.chmod 0600 "~/.snowflake/connections.toml"
다음 예제의 연결 속성을 사용하여
[spark-connect]연결을 포함하도록connections.toml파일을 편집합니다.값을 사용자 고유의 연결 세부 정보로 바꿔야 합니다.
[spark-connect] host="my_snowflake_account.snowflakecomputing.com" account="my_snowflake_account" user="my_user" password="&&&&&&&&" warehouse="my_wh" database="my_db" schema="public"
Snowpark Connect for Spark 설치하기¶
Python 패키지로 |spconnect|를 설치할 수 있습니다.
Python 가상 환경을 만듭니다.
Confirm that your Python version is 3.10 or later and earlier than 3.13 by running
python3 --version.python3 -m venv .venv source .venv/bin/activate
Snowpark Connect for Spark 패키지를 설치합니다.
pip install --upgrade --force-reinstall 'snowpark-connect[jdk]'
Python 코드를 추가하여 Snowpark Connect for Spark 서버를 시작하고 Snowpark Connect for Spark 세션을 만듭니다.
from snowflake import snowflake.snowpark_connect # Import snowpark_connect *before* importing pyspark libraries from pyspark.sql.types import Row spark = snowflake.snowpark_connect.server.init_spark_session()
Run Python code from your client¶
Once you have an authenticated connection in place, you can write code as you normally would.
PySpark 클라이언트 라이브러리를 사용하여 |spconnect|에 연결되는 PySpark 코드를 실행할 수 있습니다.
from pyspark.sql import Row
df = spark.createDataFrame([
Row(a=1, b=2.),
Row(a=2, b=3.),
Row(a=4, b=5.),])
print(df.count())
Run Scala code from your client¶
You can run Scala applications that connect to Snowpark Connect for Spark by using the Spark Connect client library.
This guide walks you through setting up Snowpark Connect and connecting your Scala applications to the Snowpark Connect for Spark server.
Step 1: Set up your Snowpark Connect for Spark environment¶
Set up your environment by using steps described in the following topics:
Step 2: Create a Snowpark Connect for Spark server script and launch the server¶
Create a Python script to launch the Snowpark Connect for Spark server.
# launch-snowpark-connect.py from snowflake import snowpark_connect def main(): snowpark_connect.start_session(is_daemon=False, remote_url="sc://localhost:15002") print("SAS started on port 15002") if __name__ == "__main__": main()
Launch the Snowpark Connect for Spark server.
# Make sure you're in the correct Python environment pyenv activate your-snowpark-connect-env # Run the server script python launch-snowpark-connect.py
Step 3: Set up your Scala application¶
Add the Spark Connect client dependency to your build.sbt file.
libraryDependencies += "org.apache.spark" %% "spark-connect-client-jvm" % "3.5.3" // Add JVM options for Java 9+ module system compatibility javaOptions ++= Seq( "--add-opens=java.base/java.nio=ALL-UNNAMED" )
Execute Scala code to connect to the Snowpark Connect for Spark server.
import org.apache.spark.sql.SparkSession import org.apache.spark.sql.connect.client.REPLClassDirMonitor object SnowparkConnectExample { def main(args: Array[String]): Unit = { // Create Spark session with Snowpark Connect val spark = SparkSession.builder().remote("sc://localhost:15002").getOrCreate() // Register ClassFinder for UDF support (if needed) // val classFinder = new REPLClassDirMonitor("target/scala-2.12/classes") // spark.registerClassFinder(classFinder) try { // Simple DataFrame operations import spark.implicits._ val data = Seq( (1, "Alice", 25), (2, "Bob", 30), (3, "Charlie", 35) ) val df = spark.createDataFrame(data).toDF("id", "name", "age") println("Original DataFrame:") df.show() println("Filtered DataFrame (age > 28):") df.filter($"age" > 28).show() println("Aggregated result:") df.groupBy().avg("age").show() } finally { spark.stop() } } }
애플리케이션을 컴파일하고 실행합니다.
# Compile your Scala application sbt compile # Run the application sbt "runMain SnowparkConnectExample"
Scala UDF support on Snowpark Connect for Spark¶
When using user-defined functions or custom code, do one of the following:
Register a class finder to monitor and upload class files.
import org.apache.spark.sql.connect.client.REPLClassDirMonitor val classFinder = new REPLClassDirMonitor("/absolute/path/to/target/scala-2.12/classes") spark.registerClassFinder(classFinder)
필요한 경우 JAR 종속성을 업로드합니다.
spark.addArtifact("/absolute/path/to/dependency.jar")
Snowpark Connect for Spark 설치 문제 해결하기¶
With the following list of checks, you can troubleshoot Snowpark Connect for Spark installation and use.
Java와 Python이 :ref:`동일한 아키텍처에 기반<label-snowpark_connect_jupyter_prereq>`을 두고 있는지 확인합니다.
Use the most recent Snowpark Connect for Spark package file, as described in Snowpark Connect for Spark 설치하기.
PySpark 코드가 포함된 python 명령이 로컬 실행, 즉 Snowflake 연결 없이 올바르게 작동하는지 확인합니다.
예를 들면, 다음과 같은 명령을 실행합니다.
python your_pyspark_file.py
Open source clients¶
You can use standard, off-the-shelf open source software (OSS) Spark client packages—such as PySpark and Spark clients for Java or Scala—from your preferred local environments, including Jupyter Notebooks and VS Code. In this way, you can avoid installing packages specific to Snowflake.
You might find this useful if you want to write Spark code locally and have the code use Snowflake compute resources and enterprise governance. In this scenario, you perform authentication and authorization through programmatic access tokens (PATs).
The following sections cover installation, configuration, and authentication. You’ll also find a simple PySpark example to validate your connection.
Step 1: Install Required Packages¶
Install
pyspark. You don’t need to install any Snowflake packages.pip install "pyspark[connect]>=3.5.0,<4"
Step 2: Setup and Authentication¶
Generate a programmatic access token (PAT).
For more information, see the following topics:
The following example adds a PAT named
TEST_PATfor the usersysadminand sets the expiration to 30 days.ALTER USER add PAT TEST_PAT ROLE_RESTRICTION = sysadmin DAYS_TO_EXPIRY = 30;
Find your Snowflake Spark Connect host URL.
Run the following SQL in Snowflake to find the hostname for your account:
SELECT t.VALUE:type::VARCHAR as type, t.VALUE:host::VARCHAR as host, t.VALUE:port as port FROM TABLE(FLATTEN(input => PARSE_JSON(SYSTEM$ALLOWLIST()))) AS t where type = 'SNOWPARK_CONNECT';
Step 3: Connect to Spark Connect server¶
To connect to the Spark Connect server, use code such as the following:
from pyspark.sql import SparkSession import urllib.parse # Replace with your actual PAT. pat = urllib.parse.quote("<pat>", safe="") # Replace with your Snowpark Connect host from the above SQL query. snowpark_connect_host = "" # Define database/schema/warehouse for executing your Spark session in Snowflake (recommended); otherwise, it will be resolved from your default_namespace and default_warehouse db_name = urllib.parse.quote("TESTDB", safe="") schema_name = urllib.parse.quote("TESTSCHEMA", safe="") warehouse_name = urllib.parse.quote("TESTWH", safe="") spark = SparkSession.builder.remote(f"sc://{snowpark_connect_host}/;token={pat};token_type=PAT;database={db_name};schema={schema_name};warehouse={warehouse_name}").getOrCreate() # Spark session is ready to use. You can write regular Spark DataFrame code, as in the following example: from pyspark.sql import Row df = spark.createDataFrame([ Row(a=1, b=2.), Row(a=2, b=3.), Row(a=4, b=5.),]) print(df.count())