min()#

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

Calculates the minimum 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 minimum 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 min() to compute the minimum 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=25)
    Person.add(id=3).set(name="John", age=30)


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

with model.query() as select:
    person = Person()
    # Find the minimum age of a person.
    min_age = aggregates.min(person.age)
    response = select(alias(min_age, "min_age"))

print(response.results)
#   min_age
# 0      20

When you pass multiple Producer objects to min(), 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 minimum value is taken over the last column. In most cases, you can achieve the same result by using the min() function on a single Producer object.

To group values and find the minimum 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 minimum 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 minimum age of each person's friends.
    min_friend_age = aggregates.min(person.friends.age, per=[person])
    response = select(person.name, alias(min_friend_age, "min_friend_age"))

print(response.results)
#    name  min_friend_age
# 0  Jane              20
# 1   Joe              25
# 2  John              20

See Also#