as_rows()#
relationalai.std
#as_rows(data: list[tuple|dict|int|float|str]) -> Rows
Converts a list of data to a Rows
object.
Provides a way to pass data from Python to the model without having to define a Type
or use a dynamic rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
data | list[tuple|dict|int|float|str] | The data to convert to a Rows object. If data is a list of tuples or dictionaries, then each tuple must have the same length and each dictionary must have the same keys. |
Returns#
A Rows
object.
Example#
Use as_rows()
to convert a list of data to a Rows
object:
#import relationalai as rai
from relationalai.std import as_rows
# =====
# SETUP
# =====
model = rai.Model("MyModel")
Company = model.Type("Company")
Person = model.Type("Person")
# =======
# EXAMPLE
# =======
# Define a Rows object from a list of dictionaries
data_row = as_rows([
{"id": 1, "name": "Alice", "age": 30},
{"id": 2, "name": "Bob", "age": 45},
])
# Use data_rows to define Person objects in the model.
with model.rule():
Person.add(id=data_row.id).set(name=data_row.name, age=data_row.age)
# Query the data
with model.query() as select:
person = Person()
response = select(person.id, person.name, person.age)
print(response.results)
# id name age
# 0 1 Alice 30
# 1 2 Bob 45
IMPORTANT
If you pass a list of dictionaries to as_rows()
, each dictionary must have the same keys.
You may also use as_rows()
to define a Rows
object from a list of tuples:
## Declare a Company type.
Company = model.Type("Company")
# Define Company objects a Rows object.
with model.rule():
data_rows = as_rows([(1, "RelationalAI"), (2, "Snowflake")])
Company.add(id=data_rows[0]).set(name=data_rows[1])
# Or, alternatively:
# id, name = data_rows
# Company.add(id=id).set(name=name)
# Query the data
with model.query() as select:
company = Company()
response = select(company.id, company.name)
print(response.results)
# id name
# 0 1 RelationalAI
# 1 2 Snowflake
IMPORTANT
If you pass a list of tuples to as_rows()
, each tuple must have the same length.