Агрегатные функции

Агрегирование

Все агрегатные функции можно использовать как выражения верхнего уровня на этапе aggregate(...).

Имя Описание
COUNT Возвращает количество документов.
COUNT_IF Возвращает количество документов, для которых выражение оценивается как TRUE.
COUNT_DISTINCT Возвращает количество уникальных значений, не равных NULL.
SUM Возвращает сумму всех значений NUMERIC.
AVERAGE Возвращает среднее значение всех значений NUMERIC.
MINIMUM Возвращает минимальное значение, не равное NULL.
MAXIMUM Возвращает максимальное значение, не равное NULL.
FIRST Возвращает значение expression для первого документа.
LAST Возвращает значение expression для последнего документа.
ARRAY_AGG Возвращает массив всех входных значений.
ARRAY_AGG_DISTINCT Возвращает массив всех уникальных входных значений.

COUNT

Синтаксис:

count() -> INT64
count(expression: ANY) -> INT64

Описание.

Возвращает количество документов из предыдущего этапа, где expression оценивается как любое значение, отличное от NULL. Если expression не указано, возвращает общее количество документов из предыдущего этапа.

Node.js
// Total number of books in the collection
const countOfAll = await db.pipeline()
  .collection("books")
  .aggregate(countAll().as("count"))
  .execute();

// Number of books with nonnull `ratings` field
const countField = await db.pipeline()
  .collection("books")
  .aggregate(field("ratings").count().as("count"))
  .execute();

Web

// Total number of books in the collection
const countOfAll = await execute(db.pipeline()
  .collection("books")
  .aggregate(countAll().as("count"))
);

// Number of books with nonnull `ratings` field
const countField = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("ratings").count().as("count"))
);
Swift
// Total number of books in the collection
let countAll = try await db.pipeline()
  .collection("books")
  .aggregate([CountAll().as("count")])
  .execute()

// Number of books with nonnull `ratings` field
let countField = try await db.pipeline()
  .collection("books")
  .aggregate([Field("ratings").count().as("count")])
  .execute()

Kotlin

// Total number of books in the collection
val countAll = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.countAll().alias("count"))
    .execute()

// Number of books with nonnull `ratings` field
val countField = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.count("ratings").alias("count"))
    .execute()

Java

// Total number of books in the collection
Task<Pipeline.Snapshot> countAll = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.countAll().alias("count"))
    .execute();

// Number of books with nonnull `ratings` field
Task<Pipeline.Snapshot> countField = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.count("ratings").alias("count"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Count

# Total number of books in the collection
count_all = (
    client.pipeline().collection("books").aggregate(Count().as_("count")).execute()
)

# Number of books with nonnull `ratings` field
count_field = (
    client.pipeline()
    .collection("books")
    .aggregate(Count("ratings").as_("count"))
    .execute()
)
Java
// Total number of books in the collection
Pipeline.Snapshot countAll =
    firestore.pipeline().collection("books").aggregate(countAll().as("count")).execute().get();

// Number of books with nonnull `ratings` field
Pipeline.Snapshot countField =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(count("ratings").as("count"))
        .execute()
        .get();
Проложить маршрут
// Total number of books in the collection
countAll, err := client.Pipeline().Collection("books").
	Aggregate(firestore.Accumulators(firestore.CountAll().As("count"))).
	Execute(ctx).Results().GetAll()
if err != nil {
	fmt.Fprintf(w, "GetAll failed: %v", err)
	return err
}

// Number of books with nonnull `ratings` field
countField, err := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(firestore.Count("ratings").As("count"))).
	Execute(ctx).Results().GetAll()
if err != nil {
	fmt.Fprintf(w, "GetAll failed: %v", err)
	return err
}

COUNT_IF

Синтаксис:

count_if(expression: BOOLEAN) -> INT64

Описание.

Возвращает количество документов из предыдущего этапа, где expression оценивается как TRUE.

Node.js
const result = await db.pipeline()
  .collection("books")
  .aggregate(
    field("rating").greaterThan(4).countIf().as("filteredCount")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(
    field("rating").greaterThan(4).countIf().as("filteredCount")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([
    AggregateFunction("count_if", [Field("rating").greaterThan(4)]).as("filteredCount")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .aggregate(
        AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCount")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .aggregate(
        AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCount")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("rating").greater_than(4).count_if().as_("filteredCount"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(countIf(field("rating").greaterThan(4)).as("filteredCount"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.CountIf(firestore.FieldOf("rating").GreaterThan(4)).As("filteredCount"),
	)).
	Execute(ctx)

COUNT_DISTINCT

Синтаксис:

count_distinct(expression: ANY) -> INT64

Описание.

Возвращает количество уникальных значений expression, не равных NULL и ABSENT.

Node.js
const result = await db.pipeline()
  .collection("books")
  .aggregate(field("author").countDistinct().as("unique_authors"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("author").countDistinct().as("unique_authors"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([AggregateFunction("count_distinct", [Field("author")]).as("unique_authors")])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.countDistinct("author").alias("unique_authors"))
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.countDistinct("author").alias("unique_authors"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("author").count_distinct().as_("unique_authors"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(countDistinct("author").as("unique_authors"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.CountDistinct("author").As("unique_authors"),
	)).
	Execute(ctx)

SUM

Синтаксис:

sum(expression: ANY) -> NUMBER

Описание.

Возвращает сумму всех числовых значений, игнорируя нечисловые. Возвращает NaN, если любое из значений равно NaN.

Выходные данные будут иметь тот же тип, что и входные данные самого широкого типа, за исключением следующих случаев:

  • Если значение INTEGER нельзя представить в виде INTEGER, оно будет преобразовано в DOUBLE.
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").sum().as("totalPopulation"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("cities")
  .aggregate(field("population").sum().as("totalPopulation"))
);
Swift
let result = try await db.pipeline()
  .collection("cities")
  .aggregate([Field("population").sum().as("totalPopulation")])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("cities")
    .aggregate(AggregateFunction.sum("population").alias("totalPopulation"))
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("cities")
    .aggregate(AggregateFunction.sum("population").alias("totalPopulation"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("cities")
    .aggregate(Field.of("population").sum().as_("totalPopulation"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("cities")
        .aggregate(sum("population").as("totalPopulation"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("cities").
	Aggregate(firestore.Accumulators(
		firestore.Sum("population").As("totalPopulation"),
	)).
	Execute(ctx)

СРЕДНЕЕ

Синтаксис:

average(expression: ANY) -> FLOAT64

Описание.

Возвращает среднее значение для всех числовых значений, игнорируя нечисловые. Возвращает NaN, если любое из значений равно NaN, или NULL, если числовые значения не агрегированы.

Тип выходных данных будет совпадать с типом входных данных, за исключением следующих случаев:

  • Если значение INTEGER нельзя представить в виде INTEGER, оно будет преобразовано в DOUBLE.
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").average().as("averagePopulation"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("cities")
  .aggregate(field("population").average().as("averagePopulation"))
);
Swift
let result = try await db.pipeline()
  .collection("cities")
  .aggregate([Field("population").average().as("averagePopulation")])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("cities")
    .aggregate(AggregateFunction.average("population").alias("averagePopulation"))
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("cities")
    .aggregate(AggregateFunction.average("population").alias("averagePopulation"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("cities")
    .aggregate(Field.of("population").average().as_("averagePopulation"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("cities")
        .aggregate(average("population").as("averagePopulation"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("cities").
	Aggregate(firestore.Accumulators(
		firestore.Average("population").As("averagePopulation"),
	)).
	Execute(ctx)

МИНИМУМ

Синтаксис:

minimum(expression: ANY) -> ANY

Описание.

Возвращает минимальное значение expression, которое не равно NULL и не отсутствует, при оценке каждого документа.

Если все значения равны NULL или отсутствуют, возвращается NULL. в том числе когда документы не учитываются.

Если минимальных эквивалентных значений несколько, может быть возвращено любое из них. Типы значений упорядочены в соответствии с документацией.

Node.js
const result = await db.pipeline()
  .collection("books")
  .aggregate(field("price").minimum().as("minimumPrice"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").minimum().as("minimumPrice"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([Field("price").minimum().as("minimumPrice")])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.minimum("price").alias("minimumPrice"))
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.minimum("price").alias("minimumPrice"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("price").minimum().as_("minimumPrice"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(minimum("price").as("minimumPrice"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.Minimum("price").As("minimumPrice"),
	)).
	Execute(ctx)

МАКСИМУМ

Синтаксис:

maximum(expression: ANY) -> ANY

Описание.

Возвращает максимальное значение expression, которое не равно NULL и не отсутствует, при оценке каждого документа.

Если все значения равны NULL или отсутствуют, возвращается NULL. в том числе когда документы не учитываются.

Если максимальных значений несколько, может быть возвращено любое из них. Типы значений упорядочены в соответствии с документацией.

Node.js
const result = await db.pipeline()
  .collection("books")
  .aggregate(field("price").maximum().as("maximumPrice"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").maximum().as("maximumPrice"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([Field("price").maximum().as("maximumPrice")])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.maximum("price").alias("maximumPrice"))
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.maximum("price").alias("maximumPrice"))
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("price").maximum().as_("maximumPrice"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(maximum("price").as("maximumPrice"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.Maximum("price").As("maximumPrice"),
	)).
	Execute(ctx)

FIRST

Синтаксис:

first(expression: ANY) -> ANY

Описание.

Возвращает значение expression для первого возвращенного документа.

ПОСЛЕДНИЙ

Синтаксис:

last(expression: ANY) -> ANY

Описание.

Возвращает значение expression для последнего возвращенного документа.

ARRAY_AGG

Синтаксис:

array_agg(expression: ANY) -> ARRAY<ANY>

Описание.

Возвращает массив, содержащий все значения expression, полученные при оценке каждого документа.

Если выражение разрешается в отсутствующее значение, оно преобразуется в NULL.

Порядок элементов в выходном массиве не является стабильным и на него не следует полагаться.

ARRAY_AGG_DISTINCT

Синтаксис:

array_agg_distinct(expression: ANY) -> ARRAY<ANY>

Описание.

Возвращает массив, содержащий все уникальные значения expression, полученные при оценке каждого документа.

Если выражение разрешается в отсутствующее значение, оно преобразуется в NULL.

Порядок элементов в выходном массиве не является стабильным, и на него не следует полагаться.