Model#
#class Model(
name: str,
*,
format: str = "default",
profile: str | None = None,
connection: SnowflakeConnection | None = None,
ensure_change_tracking: bool = False
)
A RelationalAI model is made up of objects,
which represent real-world entities and are categorized by type,
and rules that describe objects and the relationships between them.
The Model
class is used to create, manage, and query models.
Parameters#
Name | Type | Description |
---|---|---|
name | str | The name of the model. Must be at least three characters. May only contain letters, numbers, and underscores. |
format | str | Optional format for query responses. Default is "default" , which stores results as a pandas DataFrame. Use "snowpark" to get results as a Snowpark DataFrame. |
profile | str or None | Optional name of the configuration profile to use when creating the model. If None , the currently active profile is used. |
connection | Session or None | Optional Snowpark Session object to use when creating the model. If None , connection details in the configuration profile set by the profile parameter are used. Ignored in Azure-based projects. |
ensure_change_tracking | bool | Optional flag to enable change tracking on tables or views passed to the source parameter. (Default: False ). |
Attributes#
Name | Type | Description |
---|---|---|
.name | str | The name of the model. |
Methods#
Name | Description | Returns |
---|---|---|
.Type() | Creates a Type for categorizing objects in the model. | Type |
.rule() | Adds a rule to the model. | Context |
.query() | Queries the model. | Context |
.export() | Exports a Python function as a Snowflake stored procedure. Used as a decorator. | Callable |
.rule()
and .query()
are Python context managers
and must be used in a with
statement.
The with
block defines the scope of the rule or query
and is where you define the rule or query logic using the RelationalAI query-builder syntax.
The following methods create contexts for expressing conditional logic in rules and queries
and must be called from inside a .rule()
or .query()
context’s with
block:
Name | Description | Returns |
---|---|---|
.found() | Checks that a subquery has at least one result. | Context |
.not_found() | Checks that a subquery has no results. | Context |
.match() | Matches objects to one or more subqueries. Similar to a Python match or a SQL CASE statment. | Context |
.case() | Creates a subquery inside of a .match() context. | Context |
Example#
#import relationalai as rai
# Create a new model named "people."
model = rai.Model("people")
# Get the Person table from the 'sandbox.public' schema in Snowflake.
Person = model.Type("Person", source="sandbox.public.person")
# Create an Adult type in the model.
Adult = model.Type("Adult")
# The model.rule() context manager is used to define rules in the model.
# This rule adds all people over 18 to the Adult type.
with model.rule():
person = Person()
person.age >= 18
person.set(Adult)
# The model.query() context manager is used to query the model.
# This query returns the names of all adults in the model.
with model.query() as select:
adult = Adult()
response = select(adult.name)
print(response.results)
# Output:
# name
# 0 Alice
# 1 Bob
Before you can access a Snowflake table in a model,
such as the sandbox.public.person
table in the preceding example,
you must import the table using the rai imports:stream
CLI command
or the RelationalAI SQL Library.
Your Snowflake user must have the correct privileges to create a stream on the table.
Contact your Snowflake administrator if you need help importing a Snowflake table.
By default, query results are returned as a pandas DataFrame,
which downloads to your local machine and can be slow down large datasets.
To keep results in Snowflake and avoid downloads, use format="snowpark"
when creating the model:
## NOTE: The format parameter must be passed as a keyword argument.
model = rai.Model("people", format="snowpark")
# ...
with model.query() as select:
adult = Adult()
response = select(adult.name)
# The response is a Snowpark DataFrame.
print(response.results)
# Output:
# <snowflake.snowpark.dataframe.DataFrame object at 0x1313d3590>
# To view the contents of the Snowpark DataFrame, use the .show() method.
response.results.show()
# Output:
# ----------
# |"NAME" |
# ----------
# |Bob |
# |Alice |
# ----------
# To save results to a table in Snowflake, use the .write() method.
response.results.write.save_as_table("sandbox.public.adults")
Refer the Snowflake documentation for details on working with Snowpark DataFrames.
You may also export a Python function as a Snowflake stored procedure using the .export()
method,
allowing Snowflake SQL users to interact with the model:
## Export a function to the `sandbox.public` schema in Snowflake.
# The stored procedure is named "get_adults_by_age".
# NOTE: Type hints are required for the function parameters and return values.
from typing import Tuple
@model.export("sandbox.public")
def get_adults_by_age(age: int) -> Tuple[str, int]:
adult = Adult(age=age)
return adult.name, adult.age
# The stored procedure can be called in Snowflake SQL:
# CALL sandbox.public.get_adults_by_age(21);
Anything you can do in a query context can be done in an exported function, including advanced logic and graph analytics.
See .export()
for more details.
To use a configuration profile other than the active profile,
pass the profile name to the profile
parameter when creating the model:
## NOTE: The profile name must be passed as a keyword argument.
model = rai.Model("people", profile="my_profile")
To use a Snowpark Session other than the one specified in the configuration profile,
pass a Session
object to the connection
parameter when creating the model:
#from snowflake.snowpark import Session
connection_parameters = {
"user": <USER>,
"password": <PASSWORD>,
"account": <ACCOUNT>,
"warehouse": <WAREHOUSE>,
"database": <DATABASE>,
"schema": <SCHEMA>
)
conn = Session.builder.configs(connection_parameters).create()
# NOTE: The connection object must be passed as a keyword argument.
model = rai.Model("people", connection=conn)
See the Snowflake docs for more details on creating Snowpark Session objects.