bottom()#
relationalai.std.aggregates
#bottom(limit: int, *args: Producer, per: Optional[List[Producer]] = None) -> Expression
Filters values produced by one or more Producer
objects to the smallest values.
Pass a list of Producer
objects to the optional per
parameter to group values.
Must be called in a rule or query context.
Parameters#
Name | Type | Description |
---|---|---|
limit | int | The maximum number of bottom-ranked values to return. |
*args | Producer | One or more Producer objects. |
per | Optional[ListProducer ] | A list of Producer objects for grouping values. |
Returns#
An Expression
object.
Example#
Use bottom()
to return the bottom two people by age:
#import relationalai as rai
from relationalai.std.aggregates import bottom
model = rai.Model("people")
Person = model.Type("Person")
with model.rule():
Person.add(name="Joe", age=43)
Person.add(name="Jane", age=39)
Person.add(name="John", age=41)
with model.query() as select:
person = Person()
bottom(2, person.age, person)
response = select(person.name, person.age)
print(response.results)
# Output:
# name age
# 0 Jane 39
# 1 John 41
To group values, pass a list of one or more Producer
objects to the optional per
parameter.
In the following example, the person
object is passed to per
to find the youngest friend of each person:
#import relationalai as rai
from relationalai.std import alias
from relationalai.std.aggregates import bottom
model = rai.Model("friends")
Person = model.Type("Person")
with model.rule():
joe = Person.add(name="Joe", age=43)
jane = Person.add(name="Jane", age=39)
john = Person.add(name="John", age=41)
jill = Person.add(name="Jill", age=40)
joe.friends.extend([jane, john])
jane.friends.extend([joe, jill])
john.friends.extend([joe, jill])
jill.friends.extend([jane, john])
with model.query() as select:
person = Person()
bottom(1, person.friends.age, person.friends, per=[person])
response = select(
person.name,
alias(person.friends.name, "youngest_friend"),
person.friends.age
)
print(response.results)
# Output:
# name youngest_friend age
# 0 Jane Jill 40
# 1 Jill Jane 39
# 2 Joe Jane 39
# 3 John Jill 40