top()#
relationalai.std.aggregates
#top(limit: int, *args: Producer, per: Optional[List[Producer]] = None) -> Expression
Filters values produced by one or more Producer
objects to the largest 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 top-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 top()
to return the top two people by age:
#import relationalai as rai
from relationalai.std.aggregates import top
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()
top(2, person.age, person)
response = select(person.name, person.age)
print(response.results)
# Output:
# name age
# 0 Joe 43
# 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 oldest friend of each person:
#import relationalai as rai
from relationalai.std import alias
from relationalai.std.aggregates import top
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()
top(1, person.friends.age, person.friends, per=[person])
response = select(
person.name,
alias(person.friends.name, "oldest_friend"),
person.friends.age
)
print(response.results)
# Output:
# name oldest_friend age
# 0 Jane Joe 43
# 1 Jill John 41
# 2 Joe John 41
# 3 John Joe 43