Working with DataFrames in Snowpark Scala¶
In Snowpark, the main way in which you query and process data is through a DataFrame. This topic explains how to work with DataFrames.
To retrieve and manipulate data, you use the DataFrame class. A DataFrame represents a relational dataset that is evaluated lazily: it only executes when a specific action is triggered. In a sense, a DataFrame is like a query that needs to be evaluated in order to retrieve data.
To retrieve data into a DataFrame:
Construct a DataFrame, specifying the source of the data for the dataset.
For example, you can create a DataFrame to hold data from a table, an external CSV file, or the execution of a SQL statement.
Specify how the dataset in the DataFrame should be transformed.
For example, you can specify which columns should be selected, how the rows should be filtered, how the results should be sorted and grouped, etc.
Execute the statement to retrieve the data into the DataFrame.
In order to retrieve the data into the DataFrame, you must invoke a method that performs an action (for example, the
collect()method).
The next sections explain these steps in more detail.
Setting up the Examples for this Section¶
Some of the examples of this section use a DataFrame to query a table named sample_product_data. If you want to run these
examples, you can create this table and fill the table with some data by executing the following SQL statements:
To verify that the table was created, run:
Constructing a DataFrame¶
To construct a DataFrame, you can use methods in the Session class. Each of the following methods constructs a DataFrame
from a different type of data source:
To create a DataFrame from data in a table, view, or stream, call the
tablemethod:Note
The
session.tablemethod returns anUpdatableobject.UpdatableextendsDataFrameand provides additional methods for working with data in the table (e.g. methods for updating and deleting data). See Updating, Deleting, and Merging Rows in a Table.To create a DataFrame from a sequence of values, call the
createDataFramemethod:Note
Words reserved by Snowflake are not valid as column names when constructing a DataFrame. For a list of reserved words, refer to Reserved & limited keywords.
To create a DataFrame containing a range of values, call the
rangemethod:To create a DataFrame for a file in a stage, call
readto get aDataFrameReaderobject. In theDataFrameReaderobject, call the method corresponding to the format of the data in the file:To create a DataFrame to hold the results of a SQL query, call the
sqlmethod:Note: Although you can use this method to execute SELECT statements that retrieve data from tables and staged files, you should use the
tableandreadmethods instead. Methods liketableandreadcan provide better syntax highlighting, error highlighting, and intelligent code completion in development tools.
Specifying How the Dataset Should Be Transformed¶
To specify which columns should be selected and how the results should be filtered, sorted, grouped, etc., call the DataFrame
methods that transform the dataset. To identify columns in these methods, use the col function or an expression that
evaluates to a column. (See Specifying Columns and Expressions.)
For example:
To specify which rows should be returned, call the
filtermethod:To specify the columns that should be selected, call the
selectmethod:
Each method returns a new DataFrame object that has been transformed. (The method does not affect the original DataFrame object.) This means that if you want to apply multiple transformations, you can chain method calls, calling each subsequent transformation method on the new DataFrame object returned by the previous method call.
Note that these transformation methods do not retrieve data from the Snowflake database. (The action methods described in Performing an Action to Evaluate a DataFrame perform the data retrieval.) The transformation methods simply specify how the SQL statement should be constructed.
Specifying Columns and Expressions¶
When calling these transformation methods, you might need to specify columns or expressions that use columns. For example, when
calling the select method, you need to specify the columns that should be selected.
To refer to a column, create a Column object by calling the col function in the com.snowflake.snowpark.functions
object.
Note
To create a Column object for a literal, see Using Literals as Column Objects.
When specifying a filter, projection, join condition, etc., you can use Column objects in an expression. For example:
You can use
Columnobjects with thefiltermethod to specify a filter condition:You can use
Columnobjects with theselectmethod to define an alias:You can use
Columnobjects with thejoinmethod to define a join condition:
Referring to Columns in Different DataFrames¶
When referring to columns in two different DataFrame objects that have the same name (for example, joining the DataFrames on that
column), you can use the DataFrame.col method in one DataFrame object to refer to a column in that object (for example,
df1.col("name") and df2.col("name")).
The following example demonstrates how to use the DataFrame.col method to refer to a column in a specific DataFrame. The
example joins two DataFrame objects that both have a column named key. The example uses the Column.as method to change
the names of the columns in the newly created DataFrame.
Using the apply Method to Refer to a Column¶
As an alternative to the DataFrame.col method, you can use the DataFrame.apply method to refer to a column in a
specific DataFrame. Like the DataFrame.col method, the DataFrame.apply method accepts a column name as input and
returns a Column object.
Note that when an object has an apply method in Scala, you can call the apply method by calling the object as if
it were a function. For example, to call df.apply("column_name"), you can simply write df("column_name"). The
following calls are equivalent:
df.col("<column_name>")df.apply("<column_name>")df("<column_name>")
The following example is the same as the previous example but uses the DataFrame.apply method to refer to the columns in
a join operation:
Using Shorthand For a Column Object¶
As an alternative to using the col function, you can refer to a column in one of these ways:
Use a dollar sign in front of the quoted column name (
$"column_name").Use an apostrophe (a single quote) in front of the unquoted column name (
'column_name).
To do this, import the names from the implicits object after you create a Session object:
Using Double Quotes Around Object Identifiers (Table Names, Column Names, etc.)¶
The names of databases, schemas, tables, and stages that you specify must conform to the Snowflake identifier requirements. When you specify a name, Snowflake considers the name to be in upper case. For example, the following calls are equivalent:
If the name does not conform to the identifier requirements, you must use double quotes (") around the name. Use a backslash
(\) to escape the double quote character within a Scala string literal. For example, the following table name does not start
with a letter or an underscore, so you must use double quotes around the name:
Note that when specifying the name of a column, you don’t need to use double quotes around the name. The Snowpark library automatically encloses the column name in double quotes for you if the name does not comply with the identifier requirements:.
If you have already added double quotes around a column name, the library does not insert additional double quotes around the name.
In some cases, the column name might contain double quote characters:
As explained in Identifier requirements, for each double quote character within a double-quoted identifier, you
must use two double quote characters (e.g. "name_with_""air""_quotes" and """column_name_quoted"""):
Keep in mind that when an identifier is enclosed in double quotes (whether you explicitly added the quotes or the library added the quotes for you), Snowflake treats the identifier as case-sensitive:
Using Literals as Column Objects¶
To use a literal in a method that passes in a Column object, create a Column object for the literal by passing
the literal to the lit function in the com.snowflake.snowpark.functions object. For example:
If the literal is a floating point or double value in Scala (e.g. 0.05 is
treated as a Double by default), the Snowpark library
generates SQL that implicitly casts the value to the corresponding Snowpark data type (e.g. 0.05::DOUBLE). This can produce
an approximate value that differs from the exact number specified.
For example, the following code displays no matching rows, even though the filter (that matches values greater than or equal to
0.05) should match the rows in the DataFrame:
The problem is that lit(0.06) and lit(0.01) produce approximate values for 0.06 and 0.01, not the exact values.
To avoid this problem, you can use one of the following approaches:
Option 1: Cast the literal to the Snowpark type that you want to use. For example, to use a NUMBER with a precision of 5 and a scale of 2:
Option 2: Cast the value to the type that you want to use before passing the value to the
litfunction. For example, if you want to use the BigDecimal type:
Casting a Column Object to a Specific Type¶
To cast a Column object to a specific type, call the Column.cast method, and pass in a type object from the
com.snowflake.snowpark.types package. For example, to cast a literal as a NUMBER with a precision of 5
and a scale of 2:
Chaining Method Calls¶
Because each method that transforms a DataFrame object returns a new DataFrame object that has the transformation applied, you can chain method calls to produce a new DataFrame that is transformed in additional ways.
The following example returns a DataFrame that is configured to:
Query the
sample_product_datatable.Return the row with
id = 1.Select the
nameandserial_numbercolumns.
In this example:
session.table("sample_product_data")returns a DataFrame for thesample_product_datatable.Although the DataFrame does not yet contain the data from the table, the object does contain the definitions of the columns in the table.
filter(col("id") === 1)returns a DataFrame for thesample_product_datatable that is set up to return the row withid = 1.Note again that the DataFrame does not yet contain the matching row from the table. The matching row is not retrieved until you call an action method.
select(col("name"), col("serial_number"))returns a DataFrame that contains thenameandserial_numbercolumns for the row in thesample_product_datatable that hasid = 1.
When you chain method calls, keep in mind that the order of calls is important. Each method call returns a DataFrame that has been transformed. Make sure that subsequent calls work with the transformed DataFrame.
For example, in the code below, the select method returns a DataFrame that just contains two columns: name and
serial_number. The filter method call on this DataFrame fails because it uses the id column, which is not in the
transformed DataFrame.
In contrast, the following code executes successfully because the filter() method is called on a DataFrame that contains
all of the columns in the sample_product_data table (including the id column):
Keep in mind that you might need to make the select and filter method calls in a different order than you would
use the equivalent keywords (SELECT and WHERE) in a SQL statement.
Limiting the Number of Rows in a DataFrame¶
To limit the number of rows in a DataFrame, you can use the DataFrame.limit transformation method.
The Snowpark API also provides action methods for retrieving and printing out a limited number of rows:
the DataFrame.first action method (to execute the query and return the first
nrows)the DataFrame.show action method (to execute the query and print the first
nrows)
These methods effectively add a LIMIT clause to the SQL statement that is executed.
As explained in the usage notes for LIMIT, the results are non-deterministic unless you specify a sort order (ORDER BY) in conjunction with LIMIT.
To keep the ORDER BY clause with the LIMIT clause (e.g. so that ORDER BY is not in a separate subquery), you must call the method
that limits results on the DataFrame returned by the sort method.
For example, if you are chaining method calls:
Retrieving Column Definitions¶
To retrieve the definition of the columns in the dataset for the DataFrame, call the schema method. This method returns
a StructType object that contains an Array of StructField objects. Each StructField object
contains the definition of a column.
In the returned StructType object, the column names are always normalized. Unquoted identifiers are returned in uppercase,
and quoted identifiers are returned in the exact case in which they were defined.
The following example creates a DataFrame containing the columns named ID and 3rd. For the column name 3rd, the
Snowpark library automatically encloses the name in double quotes ("3rd") because
the name does not comply with the requirements for an identifier.
The example calls the schema method and then calls the names method on the returned StructType object to
get an ArraySeq of column names. The names are normalized in the StructType returned by the schema method.
Joining DataFrames¶
To join DataFrame objects, call the DataFrame.join method.
The following sections explain how to use DataFrames to perform a join:
Setting up the Sample Data for the Joins¶
The examples in the next sections use sample data that you can set up by executing the following SQL statements:
Specifying the Columns for the Join¶
With the DataFrame.join method, you can specify the columns to use in one of the following ways:
Specify a Column expression that describes the join condition.
Specify one or more columns that should be used as the common columns in the join.
The following example performs an inner join on the column named id_a:
Note that the example uses the DataFrame.col method to specify the condition to use for the join. See
Specifying Columns and Expressions for more about this method.
This prints the following output:
Identical Column Names Duplicated in the Join Result¶
In the DataFrame resulting from a join, the Snowpark library uses the column names found in the tables that were joined even when the
column names are identical across tables. When this happens, these column names are duplicated in the DataFrame resulting from the join.
To access a duplicated column by name, call the col method on the DataFrame representing the column’s original table. (For more
information about specifying columns, see Referring to Columns in Different DataFrames.)
Code in the following example joins two DataFrames, then calls the select method on the joined DataFrame. It specifies the columns
to select by calling the col method from the variable representing the respective DataFrame objects: dfRhs and
dfLhs. It uses the as method to give the columns new names in the DataFrame that the select method creates.
This prints the following output:
Deduplicate Columns Before Saving or Caching¶
Note that when a DataFrame resulting from a join includes duplicate column names, you must deduplicate or rename columns to remove duplication in the DataFrame before you save the result to a table or cache the DataFrame. For duplicate column names in a DataFrame that you save to a table or cache, the Snowpark library will replace duplicate column names with aliases so that they’re no longer duplicated.
The following example illustrates how the output of a cached DataFrame might appear if column names ID_A and VALUE were
duplicated in a join from two tables, then not deduplicated or renamed prior to caching the result.
Performing a Natural Join¶
To perform a natural join (where DataFrames are joined on columns that have the same name), call the DataFrame.naturalJoin method.
The following example joins the DataFrames for the tables sample_a and sample_b on their common columns (the column
id_a):
This prints the following output:
Specifying the Type of Join¶
By default, the DataFrame.join method creates an inner join. To specify a different type of join, set the
joinType argument to one of the following values:
Type of Join |
|
|---|---|
Inner join |
|
Cross join |
|
Full outer join |
|
Left outer join |
|
Left anti join |
|
Left semi join |
|
Right outer join |
|
For example:
This prints the following output:
Joining Multiple Tables¶
To join multiple tables:
Create a DataFrame for each table.
Call the
DataFrame.joinmethod on the first DataFrame, passing in the second DataFrame.Using the DataFrame returned by the
joinmethod, call thejoinmethod, passing in the third DataFrame.
You can chain the join calls as shown below:
This prints the following output:
Performing a Self-Join¶
If you need to join a table with itself on different columns, you cannot perform the self-join with a single DataFrame. The
following examples that use a single DataFrame to perform a self-join fail because the column expressions for "id" are
present in the left and right sides of the join:
Both of these examples fail with the following exception:
Instead, use the DataFrame.clone method to create a clone of the DataFrame object, and use the two DataFrame objects to perform the join:
If you want to perform a self-join on the same column, call the join method that passes in a Seq of column
expressions for the USING clause:
Performing an Action to Evaluate a DataFrame¶
As mentioned earlier, the DataFrame is lazily evaluated, which means the SQL statement isn’t sent to the server for execution until you perform an action. An action causes the DataFrame to be evaluated and sends the corresponding SQL statement to the server for execution.
The following sections explain how to perform an action synchronously and asynchronously on a DataFrame:
Performing an Action Synchronously¶
To perform an action synchronously, call one of the following action methods:
Method to Perform an Action Synchronously |
Description |
|---|---|
|
Evaluates the DataFrame and returns the resulting dataset as an |
|
Evaluates the DataFrame and returns an Iterator of Row objects. If the result set is large, use this method to avoid loading all the results into memory at once. See Returning an Iterator for the Rows. |
|
Evaluates the DataFrame and returns the number of rows. |
|
Evaluates the DataFrame and prints the rows to the console. Note that this method limits the number of rows to 10 (by default). See Printing the Rows in a DataFrame. |
|
Executes the query, creates a temporary table, and puts the results into the table. The method returns a |
|
Saves the data in the DataFrame to the specified table. See Saving Data to a Table. |
|
Saves a DataFrame to a specified file on a stage. See Saving a DataFrame to Files on a Stage. |
|
Copies the data in the DataFrame to the specified table. See Copying Data from Files into a Table. |
|
Deletes rows in the specified table. See Updating, Deleting, and Merging Rows in a Table. |
|
Updates rows in the specified table. See Updating, Deleting, and Merging Rows in a Table. |
|
Merges rows into the specified table. See Updating, Deleting, and Merging Rows in a Table. |
To execute the query and return the number of results, call the count method:
You can also call action methods to:
Note: If you are calling the schema method to get the definitions of the columns in the DataFrame, you do not need to
call an action method.
Performing an Action Asynchronously¶
Note
This feature was introduced in Snowpark 0.11.0.
To perform an action asynchronously, call the async method to return an “async actor” object (e.g.
DataFrameAsyncActor), and call an asynchronous action method in that object.
These action methods of an async actor object return a TypedAsyncJob object, which you can use to check
the status of the asynchronous action and retrieve the results of the action.
The next sections explain how to perform actions asynchronously and check the results.
Understanding the Basic Flow of Asynchronous Actions¶
You can use the following methods to perform an action asynchronously:
Method to Perform an Action Asynchronously |
Description |
|---|---|
|
Asynchronously evaluates the DataFrame to retrieve the resulting dataset as an |
|
Asynchronously evaluates the DataFrame to retrieve an Iterator of Row objects. If the result set is large, use this method to avoid loading all the results into memory at once. See Returning an Iterator for the Rows. |
|
Asynchronously evaluates the DataFrame to retrieve the number of rows. |
|
Asynchronously saves the data in the DataFrame to the specified table. See Saving Data to a Table. |
|
Saves a DataFrame to a specified file on a stage. See Saving a DataFrame to Files on a Stage. |
|
Asynchronously copies the data in the DataFrame to the specified table. See Copying Data from Files into a Table. |
|
Asynchronously deletes rows in the specified table. See Updating, Deleting, and Merging Rows in a Table. |
|
Asynchronously updates rows in the specified table. See Updating, Deleting, and Merging Rows in a Table. |
|
Asynchronously merges rows into the specified table. Supported in version 1.3.0 or later. See Updating, Deleting, and Merging Rows in a Table. |
From the returned TypedAsyncJob object, you can do the following:
To determine if the action has completed, call the
isDonemethod.To get the query ID that corresponds to the action, call the
getQueryIdmethod.To return the results of the action (e.g. the
ArrayofRowobjects for thecollectmethod or the count of rows for thecountmethod), call thegetResultmethod.Note that
getResultis a blocking call.To cancel the action, call the
cancelmethod.
For example, to execute a query asynchronously and retrieve the results as an Array of Row objects, call
DataFrame.async.collect:
To execute the query asynchronously and retrieve the number of results, call DataFrame.async.count:
Specifying the Maximum Number of Seconds to Wait¶
When calling the getResult method, you can use the maxWaitTimeInSeconds argument to specify the maximum number of
seconds to wait for the query to complete before attempting to retrieve the results. For example:
If you omit this argument, the method waits for the maximum number of seconds specified by the snowpark_request_timeout_in_seconds configuration property. (This is a property that you can set when creating the Session object.)
Accessing an Asynchronous Query by ID¶
If you have the query ID of an asynchronous query that you submitted earlier, you can call Session.createAsyncJob method
to create an AsyncJob object that you can use to check the status of the query, retrieve the query results, or cancel the
query.
Note that unlike TypedAsyncJob, AsyncJob does not provide a getResult method for retrieving the results.
If you need to retrieve the results, call the getRows or getIterator method instead.
For example:
Retrieving Rows into a DataFrame¶
After you specify how the DataFrame should be transformed, you can
call an action method to execute a query and return the results. You can return
all of the rows in an Array, or you can return an Iterator that allows you to iterate over the results, row by row. In
the latter case, if the amount of data is large, the rows are loaded into memory by chunk to avoid loading a large amount of data
into memory.
Returning All Rows¶
To return all rows at once, call the DataFrame.collect method. This method returns an Array of Row objects. To retrieve the
values from the row, call the getType method (e.g. getString, getInt, etc.).
For example:
Returning an Iterator for the Rows¶
If you want to use an Iterator to iterate over the Row objects in the results, call DataFrame.toLocalIterator. If the amount of data in the results is large, the method loads the rows by chunk to avoid loading all rows into memory at once.
For example:
Returning the First n Rows¶
To return the first n rows, call the DataFrame.first method, passing in the number of rows to return.
As explained in Limiting the Number of Rows in a DataFrame, the results are non-deterministic. If you want the results to be
deterministic, call this method on a sorted DataFrame (df.sort().first()).
For example:
Printing the Rows in a DataFrame¶
To print the first 10 rows in the DataFrame to the console, call the DataFrame.show method. To print out a different number of rows, pass in the number of rows to print.
As explained in Limiting the Number of Rows in a DataFrame, the results are non-deterministic. If you want the results to be
deterministic, call this method on a sorted DataFrame (df.sort().show()).
For example:
Updating, Deleting, and Merging Rows in a Table¶
Note
This feature was introduced in Snowpark 0.7.0.
When you call Session.table to create a DataFrame object for a table, the method returns an Updatable
object, which extends DataFrame with additional methods for updating and deleting data in the table. (See Updatable.)
If you need to update or delete rows in a table, you can use the following methods of the Updatable class:
Call
updateto update existing rows in the table. See Updating Rows in a Table.Call
deleteto delete rows from a table. See Deleting Rows in a Table.Call
mergeto insert, update, and delete rows in one table, based on data in a second table or subquery. (This is the equivalent of the MERGE command in SQL.) See Merging Rows into a Table.
Updating Rows in a Table¶
For the update method, pass in a Map that associates the columns to update and the corresponding values to assign
to those columns. update returns an UpdateResult object, which contains the number of rows that were updated. (See
UpdateResult.)
Note
update is an action method, which means that calling the method sends
SQL statements to the server for execution.
For example, to replace the values in the column named count with the value 1:
The example above uses the name of the column to identify the column. You can also use a column expression:
If the update should be made only when a condition is met, you can specify that condition as an argument. For example, to replace
the values in the column named count for rows in which the category_id column has the value 20:
If you need to base the condition on a join with a different DataFrame object, you can pass that DataFrame in as
an argument and use that DataFrame in the condition. For example, to replace the values in the column named count for
rows in which the category_id column matches the category_id in the DataFrame dfParts:
Deleting Rows in a Table¶
For the delete method, you can specify a condition that identifies the rows to delete, and you can base that condition on
a join with another DataFrame. delete returns a DeleteResult object, which contains the
number of rows that were deleted. (See DeleteResult.)
Note
delete is an action method, which means that calling the method sends
SQL statements to the server for execution.
For example, to delete the rows that have the value 1 in the category_id column:
If the condition refers to columns in a different DataFrame, pass that DataFrame in as the second argument. For example, to delete
the rows in which the category_id column matches the category_id in the DataFrame dfParts, pass in dfParts
as the second argument:
Merging Rows into a Table¶
To insert, update, and deletes rows in one table based on values in a second table or a subquery (the equivalent of the MERGE command in SQL), do the following:
In the
Updatableobject for the table where you want the data merged in, call themergemethod, passing in theDataFrameobject for the other table and the column expression for the join condition.This returns a
MergeBuilderobject that you can use to specify the actions to take (e.g. insert, update, or delete) on the rows that match and the rows that don’t match. (See MergeBuilder.)Using the
MergeBuilderobject:To specify the update or deletion that should be performed on matching rows, call the
whenMatchedmethod.If you need to specify an additional condition whe rows should be updated or deleted, you can pass in a column expression for that condition.
This method returns a
MatchedClauseBuilderobject that you can use to specify the action to perform. (See MatchedClauseBuilder.)Call the
updateordeletemethod in theMatchedClauseBuilderobject to specify the update or delete action that should be performed on matching rows. These methods return aMergeBuilderobject that you can use to specify additional clauses.To specify the insert that should be performed when rows do not match, call the
whenNotMatchedmethod.If you need to specify an additional condition when rows should be inserted, you can pass in a column expression for that condition.
This method returns a
NotMatchedClauseBuilderobject that you can use to specify the action to perform. (See NotMatchedClauseBuilder.)Call the
insertmethod in theNotMatchedClauseBuilderobject to specify the insert action that should be performed when rows do not match. These methods return aMergeBuilderobject that you can use to specify additional clauses.
When you are done specifying the inserts, updates, and deletions that should be performed, call the
collectmethod of theMergeBuilderobject to perform the specified inserts, updates, and deletions on the table.collectreturns aMergeResultobject, which contains the number of rows that were inserted, updated, and deleted. (See MergeResult.)
The following example inserts a row with the id and value columns from the source table into the target table if
the target table does not contain a row with a matching ID:
The following example updates a row in the target table with the value of the value column from the row in the source
table that has the same ID:
Saving Data to a Table¶
You can save the contents of a DataFrame to a new or existing table. In order to do this, you must have the following privileges:
CREATE TABLE privileges on the schema, if the table does not exist.
INSERT privileges on the table.
To save the contents of a DataFrame to a table:
Call the DataFrame.write method to get a DataFrameWriter object.
Call the DataFrameWriter.mode method, passing in a SaveMode object that specifies your preferences for writing to the table:
To insert rows, pass in
SaveMode.Append.To overwrite the existing table, pass in
SaveMode.Overwrite.
This method returns the same
DataFrameWriterobject configured with the specified mode.If you are inserting rows into an existing table (
SaveMode.Append) and the column names in the DataFrame match the column names in the table, call the DataFrameWriter.option method, passing in"columnOrder"and"name"as arguments.Note
This method was introduced in Snowpark 1.4.0.
By default, the
columnOrderoption is set to"index", which means that theDataFrameWriterinserts the values in the order that the columns appear. For example, theDataFrameWriterinserts the value from the first column from the DataFrame in the first column in the table, the second column from the DataFrame in the second column in the table, etc.This method returns the same
DataFrameWriterobject configured with the specified option.Call the DataFrameWriter.saveAsTable to save the contents of the DataFrame to a specified table.
You do not need to call a separate method (e.g.
collect) to execute the SQL statement that saves the data to the table.saveAsTableis an action method that executes the SQL statement.
The following example overwrites an existing table (identified by the tableName variable) with the contents of the DataFrame
df:
The following example inserts rows from the DataFrame df into an existing table (identified by the tableName variable).
In this example, the table and the DataFrame both contain the columns c1 and c2.
The example demonstrates the difference between setting the columnOrder option to "name" (which inserts values
into the table columns with the same names as the DataFrame columns) and using the default columnOrder option (which
inserts values into the table columns based on the order of the columns in the DataFrame).
Creating a View From a DataFrame¶
To create a view from a DataFrame, call the DataFrame.createOrReplaceView method:
Note that calling createOrReplaceView immediately creates the new view. More importantly, it does not
cause the DataFrame to be evaluated. (The DataFrame itself is not evaluated until you
perform an action.)
Views that you create by calling createOrReplaceView are persistent. If you no longer need that view, you can
drop the view manually.
If you need to create a temporary view just for the session, call the DataFrame.createOrReplaceTempView method instead:
Caching a DataFrame¶
In some cases, you may need to perform a complex query and keep the results for use in subsequent operations (rather than executing the same query again). In these cases, you can cache the contents of a DataFrame by calling the DataFrame.cacheResult method.
This method:
Runs the query.
You do not need to call a separate action method to retrieve the results before calling
cacheResult.cacheResultis an action method that executes the query.Saves the results in a temporary table
Because
cacheResultcreates a temporary table, you must have the CREATE TABLE privilege on the schema that is in use.Returns a HasCachedResult object, which provides access to the results in the temporary table.
Because
HasCachedResultextendsDataFrame, you can perform some of the same operations on this cached data as you can perform on a DataFrame.
Note
Because cacheResult executes the query and saves the results to a table, the method can result in increased compute and
storage costs.
For example:
Note that the original DataFrame is not affected when you call this method. For example, suppose that dfTable is a DataFrame
for the table sample_product_data:
After you call cacheResult, dfTable still points to the sample_product_data table, and you can continue to use
dfTable to query and update that table.
To use the cached data in the temporary table, you use dfTempTable (the HasCachedResult object returned by
cacheResult).
Working With Files in a Stage¶
The Snowpark library provides classes and methods that you can use to load data into Snowflake and unload data from Snowflake by using files in stages.
Note
In order to use these classes and methods on a stage, you must have the required privileges for working with the stage.
The next sections explain how to use these classes and methods:
Uploading and Downloading Files in a Stage¶
To upload and download files in a stage, use the FileOperation object:
Uploading Files to a Stage¶
To upload files to a stage:
Verify that you have the privileges to upload files to the stage.
Use Session.file to access the FileOperation object for the session.
Call the FileOperation.put method to upload the files to a stage.
This method executes a SQL PUT command.
To specify any optional parameters for the PUT command, create a
Mapof the parameters and values, and pass in theMapas theoptionsargument. For example:In the
localFilePathargument, you can use wildcards (*and?) to identify a set of files to upload. For example:
Check the
Arrayof PutResult objects returned by theputmethod to determine if the files were successfully uploaded. For example, to print the filename and the status of the PUT operation for that file:
Downloading Files from a Stage¶
To download files from a stage:
Verify that you have the privileges to download files from the stage.
Use Session.file to access the FileOperation object for the session.
Call the FileOperation.get method to download the files from a stage.
This method executes a SQL GET command.
To specify any optional parameters for the GET command, create a
Mapof the parameters and values, and pass in theMapas theoptionsargument. For example:Check the
Arrayof GetResult objects returned by thegetmethod to determine if the files were successfully downloaded. For example, to print the filename and the status of the GET operation for that file:
Using Input Streams to Upload and Download Data in a Stage¶
Note
This feature was introduced in Snowpark 1.4.0.
To use input streams to upload data to a file on a stage and download data from a file on a stage, use the uploadStream
and downloadStream methods of the FileOperation object:
Using an Input Stream to Upload Data to a File on a Stage¶
To upload the data from a java.io.InputStream object to a file on a stage:
Verify that you have the privileges to upload files to the stage.
Use Session.file to access the FileOperation object for the session.
Call the FileOperation.uploadStream method.
Pass in the complete path to the file on the stage where the data should be written and the
InputStreamobject. In addition, use thecompressargument to specify whether or not the data should be compressed before it is uploaded.
For example:
Using an Input Stream to Download Data from a File on a Stage¶
To download data from a file on a stage to a java.io.InputStream object:
Verify that you have the privileges to download files from the stage.
Use Session.file to access the FileOperation object for the session.
Call the FileOperation.downloadStream method.
Pass in the complete path to the file on the stage containing the data to download. Use the
decompressargument to specify whether or not the data in the file is compressed.
For example:
Setting Up a DataFrame for Files in a Stage¶
This section explains how to set up a DataFrame for files in a Snowflake stage. Once you create this DataFrame, you can use the DataFrame to:
To set up a DataFrame for files in a Snowflake stage, use the DataFrameReader class:
Verify that you have the following privileges:
One of the following:
CREATE TABLE privileges on the schema, if you plan to specify copy options that determine how data is copied from the staged files.
CREATE FILE FORMAT privileges on the schema, otherwise.
Call the
readmethod in theSessionclass to access aDataFrameReaderobject.If the files are in CSV format, describe the fields in the file. To do this:
Create a StructType object that consists of a sequence of StructField objects that describe the fields in the file.
For each
StructFieldobject, specify the following:The name of the field.
The data type of the field (specified as an object in the
com.snowflake.snowpark.typespackage).Whether or not the field is nullable.
For example:
Call the
schemamethod in theDataFrameReaderobject, passing in theStructTypeobject.For example:
The
schemamethod returns aDataFrameReaderobject that is configured to read files containing the specified fields.Note that you do not need to do this for files in other formats (such as JSON). For those files, the
DataFrameReadertreats the data as a single field of the VARIANT type with the field name$1.
If you need to specify additional information about how the data should be read (for example, that the data is compressed or that a CSV file uses a semicolon instead of a comma to delimit fields), call the DataFrameReader.option method or the DataFrameReader.options method.
Pass in the name and value of the option that you want to set. You can set the following types of options:
The file format options described in the documentation on CREATE FILE FORMAT.
The copy options described in the COPY INTO TABLE documentation.
Note that setting copy options can result in a more expensive execution strategy when you retrieve the data into the DataFrame.
The following example sets up the
DataFrameReaderobject to query data in a CSV file that is not compressed and that uses a semicolon for the field delimiter.The
optionmethod returns aDataFrameReaderobject that is configured with the specified option.To set multiple options, you can either chain calls to the
optionmethod (as shown in the example above) or call the DataFrameReader.options method, passing in aMapof the names and values of the options.Call the method corresponding to the format of the files. You can call one of the following methods:
When calling these methods, pass in the stage location of the files to be read. For example:
To specify multiple files that start with the same prefix, specify the prefix after the stage name. For example, to load files that have the prefix
csv_from the stage@mystage:The methods corresponding to the format of a file return a CopyableDataFrame object for that file.
CopyableDataFrameextendsDataFrameand provides additional methods for working the data in staged files.Call an action method to:
As is the case with DataFrames for tables, the data is not retrieved into the DataFrame until you call an action method.
Loading Data from Files into a DataFrame¶
After you set up a DataFrame for files in a stage, you can load data from the files into the DataFrame:
Use the DataFrame object methods to perform any transformations needed on the dataset (for example, selecting specific fields, filtering rows, etc.).
For example, to extract the
colorelement from a JSON file nameddata.jsonin the stage namedmystage:As explained earlier, for files in formats other than CSV (e.g. JSON), the
DataFrameReadertreats the data in the file as a single VARIANT column with the name$1.Call the
DataFrame.collectmethod to load the data. For example:
Copying Data from Files into a Table¶
After you set up a DataFrame for files in a stage, you can call the CopyableDataFrame.copyInto method to copy the data into a table. This method executes the COPY INTO <table> command.
Note
You do not need to call the collect method before calling copyInto. The data from the files does not need to
be in the DataFrame before you call copyInto.
For example, the following code loads data from the CSV file specified by myFileStage into the table mytable. Because the
data is in a CSV file, the code must also describe the fields in the file. The
example does this by calling the DataFrameReader.schema method and passing in a StructType object (csvFileSchema)
containing a sequence of StructField objects that describe the fields.
Saving a DataFrame to Files on a Stage¶
Note
This feature was introduced in Snowpark 1.5.0.
If you need to save a DataFrame to files on a stage, you can call the DataFrameWriter method corresponding to the format of
the file (e.g. the csv method to write to a CSV file), passing in the stage location where the files should be saved.
These DataFrameWriter methods execute the COPY INTO <location> command.
Note
You do not need to call the collect method before calling these DataFrameWriter methods. The data from the file
does not need to be in the DataFrame before you call these methods.
To save the contents of a DataFrame to files on a stage:
Call the DataFrame.write method to get a DataFrameWriter object. For example, to get the
DataFrameWriterobject for a DataFrame that represents the table namedsample_product_data:If you want to overwrite the contents of the file (if the file exists), call the DataFrameWriter.mode method, passing in
SaveMode.Overwrite.Otherwise, by default, the
DataFrameWriterreports an error if the specified file on the stage already exists.The
modemethod returns the sameDataFrameWriterobject configured with the specified mode.For example, to specify that the
DataFrameWritershould overwrite the file on the stage:If you need to specify additional information about how the data should be saved (for example, that the data should be compressed or that you want to use a semicolon to delimit fields in a CSV file), call the DataFrameWriter.option method or the DataFrameWriter.options method.
Pass in the name and value of the option that you want to set. You can set the following types of options:
The file format options described in the documentation on COPY INTO <location>.
The copy options described in the documentation on COPY INTO <location>.
Note that you cannot use the
optionmethod to set the following options:The TYPE format type option.
The OVERWRITE copy option. To set this option, call the
modemethod instead (as mentioned in the previous step).
The following example sets up the
DataFrameWriterobject to save data to a CSV file in uncompressed form, using a semicolon (rather than a comma) as the field delimiter.The
optionmethod returns aDataFrameWriterobject that is configured with the specified option.To set multiple options, you can chain calls to the
optionmethod (as shown in the example above) or call the DataFrameWriter.options method, passing in aMapof the names and values of the options.To return details about each file that was saved, set the
DETAILED_OUTPUTcopy option toTRUE.By default,
DETAILED_OUTPUTisFALSE, which means that the method returns a single row of output containing the fields"rows_unloaded","input_bytes", and"output_bytes".When you set
DETAILED_OUTPUTtoTRUE, the method returns a row of output for each file saved. Each row contains the fieldsFILE_NAME,FILE_SIZE, andROW_COUNT.Call the method corresponding to the format of the file to save the data to the file. You can call one of the following methods:
When calling these methods, pass in the stage location of the file where the data should be written (e.g.
@mystage).By default, the method saves the data to filenames with the prefix
data_(e.g.@mystage/data_0_0_0.csv). If you want the files to be named with a different prefix, specify the prefix after the stage name. For example:This example saves the contents of the DataFrame to files that begin with the prefix
saved_data(e.g.@mystage/saved_data_0_0_0.csv).Check the WriteFileResult object returned for information about the amount of data written to the file.
From the
WriteFileResultobject, you can access the output produced by the COPY INTO <location> command:To access the rows of output as an array of Row objects, use the
rowsvalue member.To determine which fields are present in the rows, use the
schemavalue member, which is a StructType that describes the fields in the row.
For example, to print out the names of the fields and values in the output rows:
The following example uses a DataFrame to save the contents of the table named car_sales to JSON files with the prefix
saved_data on the stage @mystage (e.g. @mystage/saved_data_0_0_0.json). The sample code:
Overwrites the file, if the file already exists on the stage.
Returns detailed output about the save operation.
Saves the data uncompressed.
Finally, the sample code prints out each field and value in the output rows returned:
Working with Semi-Structured Data¶
Using a DataFrame, you can query and access semi-structured data (e.g JSON data). The next sections explain how to work with semi-structured data in a DataFrame.
Note
The examples in these sections use the sample data in Sample Data Used in Examples.
Traversing Semi-Structured Data¶
To refer to a specific field or element in semi-structured data, use the following methods of the Column object:
Use Column.apply(“<field_name>”) to return a
Columnobject for a field in an OBJECT (or a VARIANT that contains an OBJECT).Use Column.apply(<index>) to return a
Columnobject for an element in an ARRAY (or a VARIANT that contains an ARRAY).
Note
If the field name or elements in the path are irregular and make it difficult to use the Column.apply methods, you can
use the get, get_ignore_case, or get_path functions as an alternative.
As mentioned in Using the apply Method to Refer to a Column, you can omit the method name apply:
For example, the following code selects the dealership field in objects in the src column of the
sample data:
The code prints the following output:
Note
The values in the DataFrame are surrounded by double quotes because these values are returned as string literals. To cast these values to a specific type, see Explicitly Casting Values in Semi-Structured Data.
You can also chain method calls to traverse a path to a specific field or element.
For example, the following code selects the name field in the salesperson object:
The code prints the following output:
As another example, the following code selects the first element of vehicle field, which holds an array of vehicles. The
example also selects the price field from the first element.
The code prints the following output:
As an alternative to the apply method, you can use the get, get_ignore_case, or get_path functions if the field
name or elements in the path are irregular and make it difficult to use the Column.apply methods.
For example, the following lines of code both print the value of a specified field in an object:
Similarly, the following lines of code both print the value of a field at a specified path in an object:
Explicitly Casting Values in Semi-Structured Data¶
By default, the values of fields and elements are returned as string literals (including the double quotes), as shown in the examples above.
To avoid unexpected results, call the cast method to cast the value to a specific type. For example, the following code prints out the values without and with casting:
The code prints the following output:
Flattening an Array of Objects into Rows¶
If you need to “flatten” semi-structured data into a DataFrame (e.g. producing a row for every object in an array), call the DataFrame.flatten method. This method is equivalent to the FLATTEN SQL function. If you pass in a path to an object or array, the method returns a DataFrame that contains a row for each field or element in the object or array.
For example, in the sample data, src:customer is an array of objects that
contain information about a customer. Each object contains a name and address field.
If you pass this path to the flatten function:
the method returns a DataFrame:
From this DataFrame, you can select the name and address fields from each object in the VALUE field:
The following code adds to the previous example by casting the values to a specific type and changing the names of the columns:
Executing SQL Statements¶
To execute a SQL statement that you specify, call the sql method in the Session class, and pass in the statement
to be executed. The method returns a DataFrame.
Note that the SQL statement won’t be executed until you call an action method.
If you want to call methods to transform the DataFrame (e.g. filter, select, etc.), note that these methods work only if the underlying SQL statement is a SELECT statement. The transformation methods are not supported for other kinds of SQL statements.