max()#

relationalai.std.aggregates
#max(*args: Producer, per: list[Producer] = []) -> Expression

Calculates the maximum value produced by one or more Producer objects. Pass a list of Producer objects to the optional per parameter to group values and compute the maximum per group. Must be called in a rule or query context.

Parameters#

NameTypeDescription
*argsProducerOne or more Producer objects.
perList[Producer]An optional list of Producer objects used to group arguments. (Default: [])

Returns#

An Expression object.

Example#

Use max() to compute the maximum value of a property:

#import relationalai as rai
from relationalai.std import aggregates, alias


# =====
# SETUP
# =====

model = rai.Model("MyModel")
Person = model.Type("Person")

with model.rule():
    Person.add(id=1).set(name="Joe", age=20)
    Person.add(id=2).set(name="Jane", age=20)
    Person.add(id=3).set(name="John", age=25)


# =======
# EXAMPLE
# =======

with model.query() as select:
    person = Person()
    # Find the maximum age of a person.
    max_age = aggregates.max(person.age)
    response = select(alias(max_age, "max_age"))

print(response.results)
#   max_age
# 0      30

When you pass multiple Producer objects to max(), the aggregation is performed over the distinct rows of the form (v1, v2, ..., vn) where v1, v2, …, vn are the values produced by the Producer objects, where the maximum value is taken over the last column. In most cases, you can achieve the same result by using the max() function on a single Producer object.

To group values and find the maximum for each group, pass a list of one or more Producer objects to the optional per keyword argument. In the following example, the person object is passed to per to compute the maximum age of a person’s friends:

## Set a multi-valued friend property for each person.
with model.rule():
    joe = Person(name="Joe")
    jane = Person(name="Jane")
    john = Person(name="John")
    joe.friends.extend([jane, john])
    jane.friends.extend([joe])
    john.friends.extend([joe])

with model.query() as select:
    person = Person()
    # Find the maximum age of each person's friends.
    max_friend_age = aggregates.max(person.friends.age, per=[person])
    response = select(person.name, alias(max_friend_age, "max_friend_age"))

print(response.results)
#    name  max_friend_age
# 0  Jane              20
# 1   Joe              30
# 2  John              20

See Also#