add()#
relationalai.ContextSelect
#ContextSelect.add(item: Any, **kwargs: Any) -> None
Adds an item to a ContextSelect
object.
Must be used in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
item | Any | The item to be added. |
**kwargs | Any | (Optional) Keyword arguments that set context-specific properties on added items. |
Returns#
None
Example#
#import relationalai as rai
model = rai.Model("books")
Book = model.Type("Book")
# Add some books to the model.
with model.rule():
Book.add(title="Foundation", author="Isaac Asimov", year=1951)
Book.add(title="Humble Pi", author="Matt Parker", year=2019)
# Get all books authored by Isaac Asimov or published after 1950.
with model.query() as select:
book = Book()
# 'matched' is a ContextSelect object.
with model.match(multiple=True) as matched:
with book.author == "Isaac Asimov":
matched.add(book, message="authored by Asimov")
with book.year > 1950:
matched.add(book, message="published after 1950")
response = select(matched.title, matched.author, matched.message)
print(response.results)
# Output:
# title author v
# 0 Foundation Isaac Asimov authored by Asimov
# 1 Foundation Isaac Asimov published after 1950
# 2 Humble Pi Matt Parker published after 1950
Calling .add()
on the same ContextSelect
object with different keyword arguments raises an exception.
Since .add()
sets a message
property the first time it’s called in the preceding example,
so must the second call to .add()
.
Note that the column for the .message
property in the results has the generic name v
.
You may change the column name using alias()
:
#from relationalai.std import alias
with model.query() as select:
book = Book()
with model.match(multiple=True) as matched:
with book.author == "Isaac Asimov":
matched.add(book, message="authored by Asimov")
with book.year > 1950:
matched.add(book, message="published after 1950")
response = select(
matched.title, matched.author, alias(matched.message, "message")
)
print(response.results)
# Output:
# title author message
# 0 Foundation Isaac Asimov authored by Asimov
# 1 Foundation Isaac Asimov published after 1950
# 2 Humble Pi Matt Parker published after 1950