public class Session extends Object
When you create a Session object, you provide configuration settings to establish a
connection with a Snowflake database (e.g. the URL for the account, a user name, etc.). You can
specify these settings in a configuration file or in a Map that associates configuration setting
names with values.
To create a Session from a file:
Session session = Session.builder().configFile("/path/to/file.properties").create();
Session contains functions to construct DataFrames like Session.table, Session.sql, and Session.readDataFrame| Modifier and Type | Method and Description |
|---|---|
void |
addDependency(String path)
Registers a file in stage or a local file as a dependency of a user-defined function (UDF).
|
static SessionBuilder |
builder()
Returns a builder you can use to set configuration properties and create a
Session
object. |
void |
cancelAll()
Cancel all action methods that are running currently.
|
void |
close()
Close this session.
|
AsyncJob |
createAsyncJob(String queryID)
Returns an AsyncJob object that you can use to track the status and get the results of the
asynchronous query specified by the query ID.
|
DataFrame |
createDataFrame(Row[] data,
StructType schema)
Creates a new DataFrame that uses the specified schema and contains the specified Row objects.
|
FileOperation |
file()
Returns a FileOperation object that you can use to perform file operations on stages.
|
DataFrame |
flatten(Column input)
Creates a new DataFrame by flattening compound values into multiple rows.
|
DataFrame |
flatten(Column input,
String path,
boolean outer,
boolean recursive,
String mode)
Creates a new DataFrame by flattening compound values into multiple rows.
|
DataFrame |
generator(long rowCount,
Column... columns)
Creates a new DataFrame via Generator function.
|
Optional<String> |
getCurrentDatabase()
Returns the name of the current database for the JDBC session attached to this session.
|
Optional<String> |
getCurrentSchema()
Returns the name of the current schema for the JDBC session attached to this session.
|
Optional<String> |
getDefaultDatabase()
Returns the name of the default database configured for this session in
Session.builder. |
Optional<String> |
getDefaultSchema()
Returns the name of the default schema configured for this session in
Session.builder. |
Set<URI> |
getDependencies()
Returns the list of URLs for all the dependencies that were added for user-defined functions
(UDFs).
|
String |
getFullyQualifiedCurrentSchema()
Returns the fully qualified name of the current schema for the session.
|
Optional<String> |
getQueryTag()
Returns the query tag that you set by calling
setQueryTag. |
String |
getSessionInfo()
Get the session information.
|
String |
getSessionStage()
Returns the name of the temporary stage created by the Snowpark library for uploading and store
temporary artifacts for this session.
|
Connection |
jdbcConnection()
Returns the JDBC Connection
object used for the connection to the Snowflake database.
|
DataFrame |
range(long end)
Creates a new DataFrame from a range of numbers starting from 0.
|
DataFrame |
range(long start,
long end)
Creates a new DataFrame from a range of numbers.
|
DataFrame |
range(long start,
long end,
long step)
Creates a new DataFrame from a range of numbers.
|
DataFrameReader |
read()
Returns a DataFrameReader that you can use to read data from various supported sources (e.g.
|
void |
removeDependency(String path)
Removes a path from the set of dependencies.
|
void |
setQueryTag(String queryTag)
Sets a query tag for this session.
|
DataFrame |
sql(String query)
Returns a new
DataFrame representing the results of a SQL query. |
Updatable |
table(String name)
Returns a Updatable that points to the specified table.
|
Updatable |
table(String[] multipartIdentifier)
Returns an Updatable that points to the specified table.
|
DataFrame |
tableFunction(TableFunction func,
Column... args)
Creates a new DataFrame from the given table function and arguments.
|
DataFrame |
tableFunction(TableFunction func,
Map<String,Column> args)
Creates a new DataFrame from the given table function and arguments.
|
UDFRegistration |
udf()
Returns a UDFRegistration object that you can use to register UDFs.
|
UDTFRegistration |
udtf()
Returns a UDTFRegistration object that you can use to register UDTFs.
|
void |
unsetQueryTag()
Unset query_tag parameter for this session.
|
public static SessionBuilder builder()
Session
object.SessionBuilder object.public DataFrame sql(String query)
DataFrame representing the results of a SQL query.
You can use this method to execute an arbitrary SQL statement.
query - The SQL statement to execute.DataFrame objectpublic Updatable table(String name)
name can be a fully qualified identifier and must conform to the rules for a
Snowflake identifier.
name - Table name that is either a fully qualified name or a name in the current
database/schema.public Updatable table(String[] multipartIdentifier)
name can be a fully qualified identifier and must conform to the rules for a
Snowflake identifier.
multipartIdentifier - An array of strings that specify the database name, schema name, and
table name.public DataFrame range(long end)
end - End of the range.public DataFrame range(long start, long end, long step)
start - Start of the range.end - End of the range.step - Step function for producing the numbers in the range.public DataFrame range(long start, long end)
start - Start of the range.end - End of the range.public DataFrame createDataFrame(Row[] data, StructType schema)
For example, the following code creates a DataFrame containing two columns of the types `int` and `string` with two rows of data:
For example
Row[] data = {Row.create(1, "a"), Row.create(2, "b")};
StructType schema = StructType.create(
new StructField("num", DataTypes.IntegerType),
new StructField("str", DataTypes.StringType));
DataFrame df = getSession().createDataFrame(data, schema);
data - An array of Row objects representing rows of data.schema - A StructType representing the schema for the DataFrame.public UDFRegistration udf()
@PublicPreview public UDTFRegistration udtf()
public void removeDependency(String path)
path - Path to a local directory, local file, or file in a stage.public void addDependency(String path)
The local file can be a JAR file, a directory, or any other file resource. If you pass the
path to a local file to addDependency, the Snowpark library uploads the file to a
temporary stage and imports the file when executing a UDF.
If you pass the path to a file in a stage to addDependency, the file is included in
the imports when executing a UDF.
Note that in most cases, you don't need to add the Snowpark JAR file and the JAR file (or
directory) of the currently running application as dependencies. The Snowpark library
automatically attempts to detect and upload these JAR files. However, if this automatic
detection fails, the Snowpark library reports this in an error message, and you must add these
JAR files explicitly by calling addDependency.
The following example demonstrates how to add dependencies on local files and files in a stage:
session.addDependency("@my_stage/http-commons.jar")
session.addDependency("/home/username/lib/language-detector.jar")
session.addDependency("./resource-dir/")
session.addDependency("./resource.xml")
path - Path to a local directory, local file, or file in a stage.public Set<URI> getDependencies()
public void cancelAll()
public Connection jdbcConnection()
public void setQueryTag(String queryTag)
If not set, the default value of query tag is the Snowpark library call and the class and method in your code that invoked the query (e.g. `com.snowflake.snowpark.DataFrame.collect Main$.main(Main.scala:18)`).
queryTag - String to use as the query tag for this session.public void unsetQueryTag()
If not set, the default value of query tag is the Snowpark library call and the class and method in your code that invoked the query (e.g. `com.snowflake.snowpark.DataFrame.collect Main$.main(Main.scala:18)`).
public DataFrame generator(long rowCount, Column... columns)
For example:
import com.snowflake.snowpark_java.Functions;
DataFrame df = session.generator(10, Functions.seq4(),
Functions.uniform(Functions.lit(1), Functions.lit(4), Functions.random()));
rowCount - The row count of the result DataFrame.columns - the column list of the result DataFramepublic Optional<String> getDefaultDatabase()
Session.builder.public Optional<String> getDefaultSchema()
Session.builder.public Optional<String> getCurrentDatabase()
For example, if you change the current database by executing the following code:
session.sql("use database newDB").collect();
the method returns `newDB`.
public Optional<String> getCurrentSchema()
For example, if you change the current schema by executing the following code:
session.sql("use schema newSchema").collect();
the method returns `newSchema`.
public String getFullyQualifiedCurrentSchema()
public Optional<String> getQueryTag()
setQueryTag.public String getSessionStage()
addDependency.public DataFrame flatten(Column input)
For example:
import com.snowflake.snowpark_java.Functions;
DataFrame df = session.flatten(Functions.parse_json(Functions.lit("{\"a\":[1,2]}")));
input - The expression that will be unseated into rows. The expression must be of data
type VARIANT, OBJECT, or ARRAY.public DataFrame flatten(Column input, String path, boolean outer, boolean recursive, String mode)
for example:
import com.snowflake.snowpark_java.Functions;
DataFrame df = session.flatten(Functions.parse_json(Functions.lit("{\"a\":[1,2]}")),
"a", false. false, "BOTH");
input - The expression that will be unseated into rows. The expression must be of data
type VARIANT, OBJECT, or ARRAY.path - The path to the element within a VARIANT data structure which needs to be
flattened. Can be a zero-length string (i.e. empty path) if the outermost element is to be
flattened.outer - If false, any input rows that cannot be expanded, either because they
cannot be accessed in the path or because they have zero fields or entries, are completely
omitted from the output. Otherwise, exactly one row is generated for zero-row expansions
(with NULL in the KEY, INDEX, and VALUE columns).recursive - If false, only the element referenced by PATH is expanded. Otherwise,
the expansion is performed for all sub-elements recursively.mode - Specifies which types should be flattened ("OBJECT", "ARRAY", or
"BOTH").public void close()
public String getSessionInfo()
public DataFrameReader read()
public FileOperation file()
public DataFrame tableFunction(TableFunction func, Column... args)
Example
session.tableFunction(TableFunctions.split_to_table(),
Functions.lit("split by space"), Functions.lit(" "));
func - Table function object, can be created from TableFunction class or referred from the
built-in list from tableFunctions.args - The arguments of the given table function.public DataFrame tableFunction(TableFunction func, Map<String,Column> args)
Example
Map<String, Column> args = new HashMap<>();
args.put("input", Functions.parse_json(Functions.lit("[1,2]")));
session.tableFunction(TableFunctions.flatten(), args);
func - Table function object, can be created from TableFunction class or referred from the
built-in list from tableFunctions.args - function arguments map of the given table function. Some functions, like flatten,
have named parameters. use this map to assign values to the corresponding parameters.public AsyncJob createAsyncJob(String queryID)
For example, create an AsyncJob by specifying a valid `query_id`, check whether the query is running or not, and get the result rows.
AsyncJob job = session.createAsyncJob(id);
Row[] result = job.getRows();
queryID - A valid query ID© 2022 Snowflake Inc. All Rights Reserved