ContextSelect#

relationalai
class ContextSelect

ContextSelect objects are returned by the Context.__enter__() method. They are primarily used to select results in query contexts. ContextSelect objects are also used in Model.match() contexts.

Methods#

NameDescriptionReturns
.__call__(*args, **kwargs)Calls the ContextSelect object to select results in a query context. Must be called in a query context.Context
.__getattribute__(name)Gets properties objects added to the ContextSelect object. Only used in .match() contexts.Producer
.add(item, **kwargs)Adds items to the ContextSelect object. Only used in .match() contexts.None

Example#

The Context.__enter__() method returns a ContextSelect object when called in a with statement. An example is the select object used in query contexts:

import relationalai as rai

model = rai.Model("books")
Book = model.Type("Book")

# Add a book to the model.
with model.rule():
    Book.add(title="Foundation", author="Isaac Asimov")
    Book.add(title="Humble Pi", author="Matt Parker")

# Get all books in the model.
# `select` is a `ContextSelect` object returned by `model.query().__enter__()`.
with model.query() as select:
    book = Book()
    response = select(book.name, book.author)

print(response.results)
# Output:
#         title        author
# 0  Foundation  Isaac Asimov
# 1   Humble Pi   Matt Parker

ContextSelect objects are callable. The preceding example calls the select object to select results in the query. You may only call ContextSelect objects in a query context.

Model.match() may also use a ContextSelect object. In these contexts, the ContextSelect object groups matched objects:

with model.query() as select:
    book = Book()
    # `matched` is a `ContextSelect` object created by the
    # `model.match().__enter__()` method. The `matched.add()`
    # method is used to "select" objects based on conditions and
    # add them to the `matched` collection.
    with model.match(multiple=True) as matched:
        with book.author == "Isaac Asimov":
            matched.add(book)
        with book.title == "Humble Pi":
            matched.add(book)
    response = select(matched.title, matched.author)

print(response.results)
# Output:
#         title        author
# 0  Foundation  Isaac Asimov
# 1   Humble Pi   Matt Parker

Properties of objects added to a ContextSelect object via ContextSelect.add() may be accessed directly thanks to ContextSelect.__getattribute__(). For instance, in the preceding example, the .title and .author properties of Book objects in matched are accessed as matched.title and matched.author.