count()#

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

Counts the number of distinct values produced by one or more Producer objects. When multiple producers are provided, the count is performed over rows (v1, v2, ... vn) representing distinct combinations of values produced by the arguments. Pass a list of Producer objects to the optional per parameter to group values and compute the count 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 count() to compute the number of distinct values 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()
    # Count the distinct ages of people. Note that properties use set semantics,
    # so the count is performed over distinct age values.
    count_ages = aggregates.count(person.age)
    response = select(alias(count_ages, "distinct_age_count"))

print(response.results)
#   distinct_age_count
# 0                  2

When you pass multiple Producer objects to count(), the aggregation is performed over the expansion of the arguments into distinct rows of the form (v1, v2, ..., vn) where v1, v2, …, vn are the values produced by the Producer objects.

For example, you can use this to count the total number of age values:

## Get the count of distinct person-age pairs.
with model.query() as select:
    person = Person()
    count_pairs = aggregates.count(person, person.age)
    response = select(alias(count_pairs, "person_age_count"))

print(response.results)
#   person_age_count
# 0                3

To group values and count the number of values in 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 count the number of each 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()
    # Count the number of friends each person has.
    count_friends = aggregates.count(person.friends, per=[person])
    response = select(person.name, alias(count_friends, "friend_count"))

print(response.results)
#    name  friend_count
# 0  Jane             1
# 1   Joe             2
# 2  John             1

See Also#