case()#

relationalai.Model
#Model.case(dynamic: bool = False) -> Context

Creates a subquery context in .match() contexts with a conditional scope. Must be used in a rule or query context.

Parameters#

NameTypeDescription
dynamicboolWhether or not the context is dynamic. Dynamic queries support Python control flow as macros. See Context for more information.

Returns#

A Context object.

Example#

Use Model.case() to add subqueries to a .match() context. .case() is a context manager and must be called in a with statement:

#import relationalai as rai

# Create a model named "people" with Person, Adult, and Senior types.
model = rai.Model("people")
Person = model.Type("Person")
Adult = model.Type("Adult")
Senior = model.Type("Senior")

# Add some people to the model.
with model.rule():
    jack = Person(name="Jack", age=15)
    joe = Person(name="Joe", age=30)
    jane = Person(name="Jane", age=65)

# Assign people to the Adult and Senior types based on age.
with model.rule():
    # Get all Person objects.
    person = Person()
    with model.match():
        with model.case():
            # Check if the person is at least 60 years old.
            person.age >= 60
            person.set(Senior)
        with model.case():
            # Check if the person is at least 18 years old.
            person.age >= 18
            person.set(Adult)

# Who is a Senior?
with model.query() as select:
    dog_owner = DogOwner()
    response = select(dog_owner.name)

print(response.results)
# Output:
#    name
# 0  Jane

# Who is an Adult?
with model.query() as select:
    adult = Adult()
    response = select(adult.name)

print(response.results)
# Output:
#   name
# 0  Joe

You may write the above rule more compactly by using person.age >= 60 and person.age >= 18 as context managers:

#with model.rule()
    person = Person()
    with model.match():
        with person.age >= 60:
            person.set(Senior)
        with person.age >= 18:
            person.set(Adult)

Use .case() to add a default case to a .match() context when no other cases match:

#Child = model.Type("Child")
with model.match():
    with person.age >= 60:
        person.set(Senior)
    with person.age >= 18:
        person.set(Adult)
    with model.case():
        person.set(Child)

# Who is a Child?
with model.query() as select:
    child = Child()
    response = select(child.name)

print(response.results)
# Output:
#    name
# 0  Jack

See Also#