Совокупность
Все агрегатные функции могут использоваться в качестве выражений верхнего уровня на этапе 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() -> 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")) );
Быстрый
// 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") ) );
Быстрый
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")) );
Быстрый
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(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")) );
Быстрый
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")) );
Быстрый
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
Описание:
Возвращает минимальное NULL (неотсутствующее) значение expression при его оценке для каждого документа.
Если отсутствуют значения, отличные от 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")) );
Быстрый
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
Описание:
Возвращает максимальное NULL (неотсутствующее) значение expression при его оценке для каждого документа.
Если отсутствуют значения, отличные от 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")) );
Быстрый
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(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 .
Порядок элементов в выходном массиве нестабилен, и на него не следует полагаться.
Арифметические функции
Все арифметические функции в Cloud Firestore обладают следующим поведением:
- Если какой-либо из входных параметров равен
NULL, результат будет равенNULL. - Если хотя бы один из аргументов равен
NaN, результат будет равенNaN. - Генерирует ошибку в случае переполнения или недополнения.
Кроме того, когда арифметическая функция принимает несколько числовых аргументов разных типов (например: add(5.0, 6) ), Cloud Firestore неявно преобразует аргументы в самый широкий входной тип. Если предоставлены только входные данные типа INT32 , возвращаемый тип будет INT64 .
| Имя | Описание |
ABS | Возвращает абсолютное значение number |
ADD | Возвращает значение x + y |
SUBTRACT | Возвращает значение x - y |
MULTIPLY | Возвращает значение x * y |
DIVIDE | Возвращает значение x / y |
MOD | Возвращает остаток от деления x / y |
CEIL | Возвращает порядковый номер целого number |
FLOOR | Возвращает целую часть number |
ROUND | Округляет number до десяти places после запятой. |
TRUNC | Усекает number до десятичных places |
POW | Возвращает значение, равное base^exponent |
SQRT | Возвращает квадратный корень из number |
EXP | Возвращает число Эйлера, возведенное в степень exponent . |
LN | Возвращает натуральный логарифм number . |
LOG | Возвращает логарифм number |
LOG10 | Возвращает логарифм number в десятичной системе счисления 10 |
RAND | Возвращает псевдослучайное число с плавающей запятой. |
АБС
Синтаксис:
abs[N <: INT32 | INT64 | FLOAT64](number: N) -> N
Описание:
Возвращает абсолютное значение number .
- Вызывает ошибку, если функция приведет к переполнению значения типа
INT32илиINT64.
Примеры:
| число | abs(number) |
|---|---|
| 10 | 10 |
| -10 | 10 |
| 10 л | 10 л |
| -0.0 | 0.0 |
| 10.5 | 10.5 |
| -10.5 | 10.5 |
| -2 31 | [error] |
| -2 63 | [error] |
ДОБАВЛЯТЬ
Синтаксис:
add[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Описание:
Возвращает значение x + y .
Примеры:
| х | й | add(x, y) |
|---|---|---|
| 20 | 3 | 23 |
| 10.0 | 1 | 11.0 |
| 22.5 | 2.0 | 24.5 |
| INT64.MAX | 1 | [error] |
| INT64.MIN | -1 | [error] |
Node.js
const result = await db.pipeline() .collection("books") .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("soldBooks").add(Field("unsoldBooks")).as("totalBooks")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("soldBooks").add(Field.of("unsoldBooks")).as_("totalBooks")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(add(field("soldBooks"), field("unsoldBooks")).as("totalBooks")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Add(firestore.FieldOf("soldBooks"), firestore.FieldOf("unsoldBooks")).As("totalBooks"), )). Execute(ctx)
ВЫЧИТАТЬ
Синтаксис:
subtract[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Описание:
Возвращает значение x - y .
Примеры:
| х | й | subtract(x, y) |
|---|---|---|
| 20 | 3 | 17 |
| 10.0 | 1 | 9.0 |
| 22.5 | 2.0 | 20.5 |
| INT64.MAX | -1 | [error] |
| INT64.MIN | 1 | [error] |
Node.js
const storeCredit = 7; const result = await db.pipeline() .collection("books") .select(field("price").subtract(constant(storeCredit)).as("totalCost")) .execute();
Web
const storeCredit = 7; const result = await execute(db.pipeline() .collection("books") .select(field("price").subtract(constant(storeCredit)).as("totalCost")) );
Быстрый
let storeCredit = 7 let result = try await db.pipeline() .collection("books") .select([Field("price").subtract(Constant(storeCredit)).as("totalCost")]) .execute()
Kotlin
val storeCredit = 7 val result = db.pipeline() .collection("books") .select(Expression.subtract(field("price"), storeCredit).alias("totalCost")) .execute()
Java
int storeCredit = 7; Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(Expression.subtract(field("price"), storeCredit).alias("totalCost")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field store_credit = 7 result = ( client.pipeline() .collection("books") .select(Field.of("price").subtract(store_credit).as_("totalCost")) .execute() )
Java
int storeCredit = 7; Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(subtract(field("price"), storeCredit).as("totalCost")) .execute() .get();
Идти
storeCredit := 7 snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Subtract(firestore.FieldOf("price"), storeCredit).As("totalCost"), )). Execute(ctx)
УМНОЖИТЬ
Синтаксис:
multiply[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Описание:
Возвращает значение x * y .
Примеры:
| х | й | multiply(x, y) |
|---|---|---|
| 20 | 3 | 60 |
| 10.0 | 1 | 10.0 |
| 22.5 | 2.0 | 45.0 |
| INT64.MAX | 2 | [error] |
| INT64.MIN | 2 | [error] |
| FLOAT64.MAX | FLOAT64.MAX | +inf |
Node.js
const result = await db.pipeline() .collection("books") .select(field("price").multiply(field("soldBooks")).as("revenue")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("price").multiply(field("soldBooks")).as("revenue")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("price").multiply(Field("soldBooks")).as("revenue")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(Expression.multiply(field("price"), field("soldBooks")).alias("revenue")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(Expression.multiply(field("price"), field("soldBooks")).alias("revenue")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("price").multiply(Field.of("soldBooks")).as_("revenue")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(multiply(field("price"), field("soldBooks")).as("revenue")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Multiply(firestore.FieldOf("price"), firestore.FieldOf("soldBooks")).As("revenue"), )). Execute(ctx)
РАЗДЕЛЯТЬ
Синтаксис:
divide[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Описание:
Возвращает значение x / y . При целочисленном делении результат усекается.
Примеры:
| х | й | divide(x, y) |
|---|---|---|
| 20 | 3 | 6 |
| 10.0 | 3 | 3.333... |
| 22.5 | 2 | 11.25 |
| 10 | 0 | [error] |
| 1.0 | 0.0 | +inf |
| -1.0 | 0.0 | -inf |
Node.js
const result = await db.pipeline() .collection("books") .select(field("ratings").divide(field("soldBooks")).as("reviewRate")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("ratings").divide(field("soldBooks")).as("reviewRate")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("ratings").divide(Field("soldBooks")).as("reviewRate")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(Expression.divide(field("ratings"), field("soldBooks")).alias("reviewRate")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(Expression.divide(field("ratings"), field("soldBooks")).alias("reviewRate")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("ratings").divide(Field.of("soldBooks")).as_("reviewRate")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(divide(field("ratings"), field("soldBooks")).as("reviewRate")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Divide(firestore.FieldOf("ratings"), firestore.FieldOf("soldBooks")).As("reviewRate"), )). Execute(ctx)
МОД
Синтаксис:
mod[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Описание:
Возвращает остаток от деления x / y .
- Вызывает
error, еслиyравно нулю для целочисленных типов (INT64). - Возвращает
NaNкогдаyравно нулю для типов с плавающей запятой (FLOAT64).
Примеры:
| х | й | mod(x, y) |
|---|---|---|
| 20 | 3 | 2 |
| -10 | 3 | -1 |
| 10 | -3 | 1 |
| -10 | -3 | -1 |
| 10 | 1 | 0 |
| 22.5 | 2 | 0,5 |
| 22.5 | 0.0 | NaN |
| 25 | 0 | [error] |
Node.js
const displayCapacity = 1000; const result = await db.pipeline() .collection("books") .select(field("unsoldBooks").mod(constant(displayCapacity)).as("warehousedBooks")) .execute();
Web
const displayCapacity = 1000; const result = await execute(db.pipeline() .collection("books") .select(field("unsoldBooks").mod(constant(displayCapacity)).as("warehousedBooks")) );
Быстрый
let displayCapacity = 1000 let result = try await db.pipeline() .collection("books") .select([Field("unsoldBooks").mod(Constant(displayCapacity)).as("warehousedBooks")]) .execute()
Kotlin
val displayCapacity = 1000 val result = db.pipeline() .collection("books") .select(Expression.mod(field("unsoldBooks"), displayCapacity).alias("warehousedBooks")) .execute()
Java
int displayCapacity = 1000; Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(Expression.mod(field("unsoldBooks"), displayCapacity).alias("warehousedBooks")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field display_capacity = 1000 result = ( client.pipeline() .collection("books") .select(Field.of("unsoldBooks").mod(display_capacity).as_("warehousedBooks")) .execute() )
Java
int displayCapacity = 1000; Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(mod(field("unsoldBooks"), displayCapacity).as("warehousedBooks")) .execute() .get();
Идти
displayCapacity := 1000 snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Mod(firestore.FieldOf("unsoldBooks"), displayCapacity).As("warehousedBooks"), )). Execute(ctx)
CEIL
Синтаксис:
ceil[N <: INT32 | INT64 | FLOAT64](number: N) -> N
Описание:
Возвращает наименьшее целое число, которое не меньше заданного number .
Примеры:
| число | ceil(number) |
|---|---|
| 20 | 20 |
| 10 | 10 |
| 0 | 0 |
| 24 л | 24 л |
| -0.4 | -0.0 |
| 0,4 | 1.0 |
| 22.5 | 23.0 |
+inf | +inf |
-inf | -inf |
Node.js
const booksPerShelf = 100; const result = await db.pipeline() .collection("books") .select( field("unsoldBooks").divide(constant(booksPerShelf)).ceil().as("requiredShelves") ) .execute();
Web
const booksPerShelf = 100; const result = await execute(db.pipeline() .collection("books") .select( field("unsoldBooks").divide(constant(booksPerShelf)).ceil().as("requiredShelves") ) );
Быстрый
let booksPerShelf = 100 let result = try await db.pipeline() .collection("books") .select([ Field("unsoldBooks").divide(Constant(booksPerShelf)).ceil().as("requiredShelves") ]) .execute()
Kotlin
val booksPerShelf = 100 val result = db.pipeline() .collection("books") .select( Expression.divide(field("unsoldBooks"), booksPerShelf).ceil().alias("requiredShelves") ) .execute()
Java
int booksPerShelf = 100; Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( Expression.divide(field("unsoldBooks"), booksPerShelf).ceil().alias("requiredShelves") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field books_per_shelf = 100 result = ( client.pipeline() .collection("books") .select( Field.of("unsoldBooks") .divide(books_per_shelf) .ceil() .as_("requiredShelves") ) .execute() )
Java
int booksPerShelf = 100; Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(ceil(divide(field("unsoldBooks"), booksPerShelf)).as("requiredShelves")) .execute() .get();
Идти
booksPerShelf := 100 snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Ceil(firestore.Divide(firestore.FieldOf("unsoldBooks"), booksPerShelf)).As("requiredShelves"), )). Execute(ctx)
ПОЛ
Синтаксис:
floor[N <: INT32 | INT64 | FLOAT64](number: N) -> N
Описание:
Возвращает наибольшее целое число, не превышающее значение number .
Примеры:
| число | floor(number) |
|---|---|
| 20 | 20 |
| 10 | 10 |
| 0 | 0 |
| 2147483648 | 2147483648 |
| -0.4 | -1.0 |
| 0,4 | 0.0 |
| 22.5 | 22.0 |
+inf | +inf |
-inf | -inf |
Node.js
const result = await db.pipeline() .collection("books") .addFields( field("wordCount").divide(field("pages")).floor().as("wordsPerPage") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .addFields( field("wordCount").divide(field("pages")).floor().as("wordsPerPage") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .addFields([ Field("wordCount").divide(Field("pages")).floor().as("wordsPerPage") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .addFields( Expression.divide(field("wordCount"), field("pages")).floor().alias("wordsPerPage") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .addFields( Expression.divide(field("wordCount"), field("pages")).floor().alias("wordsPerPage") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .add_fields( Field.of("wordCount").divide(Field.of("pages")).floor().as_("wordsPerPage") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .addFields(floor(divide(field("wordCount"), field("pages"))).as("wordsPerPage")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). AddFields(firestore.Selectables( firestore.Floor(firestore.Divide(firestore.FieldOf("wordCount"), firestore.FieldOf("pages"))).As("wordsPerPage"), )). Execute(ctx)
КРУГЛЫЙ
Синтаксис:
round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N
round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N, places: INT64) -> N
Описание:
places цифр в number . Цифры округляются справа от десятичной точки, если places положительное, и слева от десятичной точки, если оно отрицательное.
- Если указано только
number, округляется до ближайшего целого значения. - В случаях, когда значение округляется до нуля, оно не равно нулю.
-
errorвозникает, если округление с отрицательнымplacesприводит к переполнению.
Примеры:
| число | места | round(number, places) |
|---|---|---|
| 15.5 | 0 | 16.0 |
| -15.5 | 0 | -16.0 |
| 15 | 1 | 15 |
| 15 | 0 | 15 |
| 15 | -1 | 20 |
| 15 | -2 | 0 |
| 15.48924 | 1 | 15.5 |
| 2 31 -1 | -1 | [error] |
| 2 63 -1L | -1 | [error] |
Node.js
const result = await db.pipeline() .collection("books") .select(field("soldBooks").multiply(field("price")).round().as("partialRevenue")) .aggregate(field("partialRevenue").sum().as("totalRevenue")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("soldBooks").multiply(field("price")).round().as("partialRevenue")) .aggregate(field("partialRevenue").sum().as("totalRevenue")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("soldBooks").multiply(Field("price")).round().as("partialRevenue")]) .aggregate([Field("partialRevenue").sum().as("totalRevenue")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(Expression.multiply(field("soldBooks"), field("price")).round().alias("partialRevenue")) .aggregate(AggregateFunction.sum("partialRevenue").alias("totalRevenue")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(Expression.multiply(field("soldBooks"), field("price")).round().alias("partialRevenue")) .aggregate(AggregateFunction.sum("partialRevenue").alias("totalRevenue")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("soldBooks") .multiply(Field.of("price")) .round() .as_("partialRevenue") ) .aggregate(Field.of("partialRevenue").sum().as_("totalRevenue")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(round(multiply(field("soldBooks"), field("price"))).as("partialRevenue")) .aggregate(sum("partialRevenue").as("totalRevenue")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Round(firestore.Multiply(firestore.FieldOf("soldBooks"), firestore.FieldOf("price"))).As("partialRevenue"), )). Aggregate(firestore.Accumulators( firestore.Sum("partialRevenue").As("totalRevenue"), )). Execute(ctx)
ТРЮК
Синтаксис:
trunc[N <: Number](number: N) -> N
trunc[N <: Number](number: N, places: INT64) -> N
Описание:
Очищает number до заданного количества десятичных places . Если places положительное, цифры отсекаются справа от десятичной точки, а если отрицательное — слева от десятичной точки.
- Если указано только
number, вычисляется округление до ближайшего целого значения, близкого к нулю. - Если при попытке усечения происходит переполнение, генерируется
error.
Примеры:
| число | места | trunc(number, places) |
|---|---|---|
| 15.5 | 0 | 15.0 |
| -15.5 | 0 | -15.0 |
| 15 | 1 | 15 |
| 15 | 0 | 15 |
| 15 | -1 | 10 |
| 15 | -2 | 0 |
| 15.48924 | 1 | 15.4 |
| -15.48924 | 2 | -15.48 |
ПАВ
Синтаксис:
pow(base: FLOAT64, exponent: FLOAT64) -> FLOAT64
Описание:
Возвращает base возведенное в степень exponent .
Вызывает ошибку, если
base <= 0иexponentотрицательный.Для любого
exponentpow(1, exponent)равно 1.Для любой
basepow(base, 0)равно 1.
Примеры:
| база | показатель степени | pow(base, exponent) |
|---|---|---|
| 2 | 3 | 8.0 |
| 2 | -3 | 0,125 |
+inf | 0 | 1.0 |
| 1 | +inf | 1.0 |
| -1 | 0,5 | [error] |
| 0 | -1 | [error] |
Node.js
const googleplex = { latitude: 37.4221, longitude: 122.0853 }; const result = await db.pipeline() .collection("cities") .addFields( field("lat").subtract(constant(googleplex.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("latitudeDifference"), field("lng").subtract(constant(googleplex.longitude)) .multiply(111 /* km per degree */) .pow(2) .as("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle") ) .execute();
Web
const googleplex = { latitude: 37.4221, longitude: 122.0853 }; const result = await execute(db.pipeline() .collection("cities") .addFields( field("lat").subtract(constant(googleplex.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("latitudeDifference"), field("lng").subtract(constant(googleplex.longitude)) .multiply(111 /* km per degree */) .pow(2) .as("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle") ) );
Быстрый
let googleplex = CLLocation(latitude: 37.4221, longitude: 122.0853) let result = try await db.pipeline() .collection("cities") .addFields([ Field("lat").subtract(Constant(googleplex.coordinate.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("latitudeDifference"), Field("lng").subtract(Constant(googleplex.coordinate.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("longitudeDifference") ]) .select([ Field("latitudeDifference").add(Field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle") ]) .execute()
Kotlin
val googleplex = GeoPoint(37.4221, -122.0853) val result = db.pipeline() .collection("cities") .addFields( field("lat").subtract(googleplex.latitude) .multiply(111) // km per degree .pow(2) .alias("latitudeDifference"), field("lng").subtract(googleplex.longitude) .multiply(111) // km per degree .pow(2) .alias("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .alias("approximateDistanceToGoogle") ) .execute()
Java
GeoPoint googleplex = new GeoPoint(37.4221, -122.0853); Task<Pipeline.Snapshot> result = db.pipeline() .collection("cities") .addFields( field("lat").subtract(googleplex.getLatitude()) .multiply(111 /* km per degree */) .pow(2) .alias("latitudeDifference"), field("lng").subtract(googleplex.getLongitude()) .multiply(111 /* km per degree */) .pow(2) .alias("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .alias("approximateDistanceToGoogle") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field googleplexLat = 37.4221 googleplexLng = -122.0853 result = ( client.pipeline() .collection("cities") .add_fields( Field.of("lat") .subtract(googleplexLat) .multiply(111) # km per degree .pow(2) .as_("latitudeDifference"), Field.of("lng") .subtract(googleplexLng) .multiply(111) # km per degree .pow(2) .as_("longitudeDifference"), ) .select( Field.of("latitudeDifference") .add(Field.of("longitudeDifference")) .sqrt() # Inaccurate for large distances or close to poles .as_("approximateDistanceToGoogle") ) .execute() )
Java
double googleplexLat = 37.4221; double googleplexLng = -122.0853; Pipeline.Snapshot result = firestore .pipeline() .collection("cities") .addFields( pow(multiply(subtract(field("lat"), googleplexLat), 111), 2) .as("latitudeDifference"), pow(multiply(subtract(field("lng"), googleplexLng), 111), 2) .as("longitudeDifference")) .select( sqrt(add(field("latitudeDifference"), field("longitudeDifference"))) // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle")) .execute() .get();
Идти
googleplexLat := 37.4221 googleplexLng := -122.0853 snapshot := client.Pipeline(). Collection("cities"). AddFields(firestore.Selectables( firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lat"), googleplexLat), 111), 2).As("latitudeDifference"), firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lng"), googleplexLng), 111), 2).As("longitudeDifference"), )). Select(firestore.Fields( firestore.Sqrt(firestore.Add(firestore.FieldOf("latitudeDifference"), firestore.FieldOf("longitudeDifference"))). // Inaccurate for large distances or close to poles As("approximateDistanceToGoogle"), )). Execute(ctx)
Квадратный корень
Синтаксис:
sqrt[N <: FLOAT64 | DECIMAL128](number: N) -> N
Описание:
Возвращает квадратный корень из number .
- Вызывает
error, еслиnumberотрицательное.
Примеры:
| число | sqrt(number) |
|---|---|
| 25 | 5.0 |
| 12.002 | 3.464... |
| 0.0 | 0.0 |
NaN | NaN |
+inf | +inf |
-inf | [error] |
x < 0 | [error] |
Node.js
const googleplex = { latitude: 37.4221, longitude: 122.0853 }; const result = await db.pipeline() .collection("cities") .addFields( field("lat").subtract(constant(googleplex.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("latitudeDifference"), field("lng").subtract(constant(googleplex.longitude)) .multiply(111 /* km per degree */) .pow(2) .as("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle") ) .execute();
Web
const googleplex = { latitude: 37.4221, longitude: 122.0853 }; const result = await execute(db.pipeline() .collection("cities") .addFields( field("lat").subtract(constant(googleplex.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("latitudeDifference"), field("lng").subtract(constant(googleplex.longitude)) .multiply(111 /* km per degree */) .pow(2) .as("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle") ) );
Быстрый
let googleplex = CLLocation(latitude: 37.4221, longitude: 122.0853) let result = try await db.pipeline() .collection("cities") .addFields([ Field("lat").subtract(Constant(googleplex.coordinate.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("latitudeDifference"), Field("lng").subtract(Constant(googleplex.coordinate.latitude)) .multiply(111 /* km per degree */) .pow(2) .as("longitudeDifference") ]) .select([ Field("latitudeDifference").add(Field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle") ]) .execute()
Kotlin
val googleplex = GeoPoint(37.4221, -122.0853) val result = db.pipeline() .collection("cities") .addFields( field("lat").subtract(googleplex.latitude) .multiply(111) // km per degree .pow(2) .alias("latitudeDifference"), field("lng").subtract(googleplex.longitude) .multiply(111) // km per degree .pow(2) .alias("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .alias("approximateDistanceToGoogle") ) .execute()
Java
GeoPoint googleplex = new GeoPoint(37.4221, -122.0853); Task<Pipeline.Snapshot> result = db.pipeline() .collection("cities") .addFields( field("lat").subtract(googleplex.getLatitude()) .multiply(111 /* km per degree */) .pow(2) .alias("latitudeDifference"), field("lng").subtract(googleplex.getLongitude()) .multiply(111 /* km per degree */) .pow(2) .alias("longitudeDifference") ) .select( field("latitudeDifference").add(field("longitudeDifference")).sqrt() // Inaccurate for large distances or close to poles .alias("approximateDistanceToGoogle") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field googleplexLat = 37.4221 googleplexLng = -122.0853 result = ( client.pipeline() .collection("cities") .add_fields( Field.of("lat") .subtract(googleplexLat) .multiply(111) # km per degree .pow(2) .as_("latitudeDifference"), Field.of("lng") .subtract(googleplexLng) .multiply(111) # km per degree .pow(2) .as_("longitudeDifference"), ) .select( Field.of("latitudeDifference") .add(Field.of("longitudeDifference")) .sqrt() # Inaccurate for large distances or close to poles .as_("approximateDistanceToGoogle") ) .execute() )
Java
double googleplexLat = 37.4221; double googleplexLng = -122.0853; Pipeline.Snapshot result = firestore .pipeline() .collection("cities") .addFields( pow(multiply(subtract(field("lat"), googleplexLat), 111), 2) .as("latitudeDifference"), pow(multiply(subtract(field("lng"), googleplexLng), 111), 2) .as("longitudeDifference")) .select( sqrt(add(field("latitudeDifference"), field("longitudeDifference"))) // Inaccurate for large distances or close to poles .as("approximateDistanceToGoogle")) .execute() .get();
Идти
googleplexLat := 37.4221 googleplexLng := -122.0853 snapshot := client.Pipeline(). Collection("cities"). AddFields(firestore.Selectables( firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lat"), googleplexLat), 111), 2).As("latitudeDifference"), firestore.Pow(firestore.Multiply(firestore.Subtract(firestore.FieldOf("lng"), googleplexLng), 111), 2).As("longitudeDifference"), )). Select(firestore.Fields( firestore.Sqrt(firestore.Add(firestore.FieldOf("latitudeDifference"), firestore.FieldOf("longitudeDifference"))). // Inaccurate for large distances or close to poles As("approximateDistanceToGoogle"), )). Execute(ctx)
ЭКСП
Синтаксис:
exp(exponent: FLOAT64) -> FLOAT64
Описание:
Возвращает значение числа Эйлера, возведенного в степень exponent , также называемого натуральной экспоненциальной функцией.
Примеры:
| показатель степени | exp(exponent) |
|---|---|
| 0.0 | 1.0 |
| 10 | e^10 ( FLOAT64 ) |
+inf | +inf |
-inf | 0 |
Node.js
const result = await db.pipeline() .collection("books") .select(field("rating").exp().as("expRating")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("rating").exp().as("expRating")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("rating").exp().as("expRating")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("rating").exp().alias("expRating")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("rating").exp().alias("expRating")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").exp().as_("expRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(exp(field("rating")).as("expRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Exp(firestore.FieldOf("rating")).As("expRating"), )). Execute(ctx)
ЛН
Синтаксис:
ln(number: FLOAT64) -> FLOAT64
Описание:
Возвращает натуральный логарифм number . Эта функция эквивалентна функции log(number) .
Примеры:
| число | ln(number) |
|---|---|
| 1 | 0.0 |
| 2 л | 0,693... |
| 1.0 | 0.0 |
e ( FLOAT64 ) | 1.0 |
-inf | NaN |
+inf | +inf |
x <= 0 | [error] |
Node.js
const result = await db.pipeline() .collection("books") .select(field("rating").ln().as("lnRating")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("rating").ln().as("lnRating")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("rating").ln().as("lnRating")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("rating").ln().alias("lnRating")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("rating").ln().alias("lnRating")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").ln().as_("lnRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(ln(field("rating")).as("lnRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Ln(firestore.FieldOf("rating")).As("lnRating"), )). Execute(ctx)
БРЕВНО
Синтаксис:
log(number: FLOAT64, base: FLOAT64) -> FLOAT64
log(number: FLOAT64) -> FLOAT64
Описание:
Возвращает логарифм number по base .
- Если указано только
number, возвращает логарифмnumberпоbase(синоним функцииln(number)).
Примеры:
| число | база | log(number, base) |
|---|---|---|
| 100 | 10 | 2.0 |
-inf | Numeric | NaN |
Numeric . | +inf | NaN |
number <= 0 | Numeric | [error] |
Numeric | base <= 0 | [error] |
Numeric | 1.0 | [error] |
LOG10
Синтаксис:
log10(x: FLOAT64) -> FLOAT64
Описание:
Возвращает логарифм number в 10 системе счисления.
Примеры:
| число | log10(number) |
|---|---|
| 100 | 2.0 |
-inf | NaN |
+inf | +inf |
x <= 0 | [error] |
РАНД
Синтаксис:
rand() -> FLOAT64
Описание:
Возвращает псевдослучайное число с плавающей запятой, выбранное равномерно в диапазоне от 0.0 (включительно) до 1.0 (исключительно).
Функции массивов
| Имя | Описание |
ARRAY | Возвращает ARRAY содержащий один элемент для каждого входного аргумента. |
ARRAY_CONCAT | Объединяет несколько массивов в один ARRAY |
ARRAY_CONTAINS | Возвращает TRUE если заданный ARRAY содержит определенное значение. |
ARRAY_CONTAINS_ALL | Возвращает TRUE если все значения присутствуют в ARRAY |
ARRAY_CONTAINS_ANY | Возвращает TRUE если хотя бы одно из значений присутствует в ARRAY |
ARRAY_FILTER | Отфильтровывает из ARRAY элементы, не удовлетворяющие предикату. |
ARRAY_FIRST | Возвращает первый элемент ARRAY |
ARRAY_FIRST_N | Возвращает первые n элементов ARRAY . |
ARRAY_GET | Возвращает элемент по заданному индексу в ARRAY |
ARRAY_INDEX_OF | Возвращает индекс первого вхождения значения в ARRAY |
ARRAY_INDEX_OF_ALL | Возвращает все индексы значения в ARRAY |
ARRAY_LENGTH | Возвращает количество элементов в ARRAY |
ARRAY_LAST | Возвращает последний элемент ARRAY . |
ARRAY_LAST_N | Возвращает последние n элементов ARRAY . |
ARRAY_REVERSE | Изменяет порядок элементов в ARRAY |
ARRAY_SLICE | Возвращает срез ARRAY |
ARRAY_TRANSFORM | Преобразует элементы ARRAY , применяя выражение к каждому элементу. |
MAXIMUM | Возвращает максимальное значение в ARRAY |
MAXIMUM_N | Возвращает n наибольших значений в ARRAY |
MINIMUM | Возвращает минимальное значение в ARRAY |
MINIMUM_N | Возвращает n наименьших значений в ARRAY |
SUM | Возвращает сумму всех NUMERIC значений в ARRAY . |
JOIN | Создает конкатенацию элементов ARRAY в виде STRING значения. |
МНОЖЕСТВО
Синтаксис:
array(values: ANY...) -> ARRAY
Описание:
Создает массив из заданных элементов.
- Если аргумент отсутствует, он заменяется значением
NULLв результирующем массиве.
Примеры:
| ценности | array(values) |
|---|---|
| () | [] |
| (1, 2, 3) | [1, 2, 3] |
| ("а", 1, true) | ["а", 1, true] |
| (1, null) | [1, null] |
| (1, [2, 3]) | [1, [2, 3]] |
ARRAY_CONCAT
Синтаксис:
array_concat(arrays: ARRAY...) -> ARRAY
Описание:
Объединяет два или более массивов в один ARRAY .
Примеры:
| массивы | array_concat(arrays) |
|---|---|
| ([1, 2], [3, 4]) | [1, 2, 3, 4] |
| (["a", "b", ["c"]) | ["a", "b", "c"] |
| ([1], [2], [3]) | [1, 2, 3] |
| ([], [1, 2]) | [1, 2] |
Node.js
const result = await db.pipeline() .collection("books") .select(field("genre").arrayConcat([field("subGenre")]).as("allGenres")) .execute();
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayConcat([Field("subGenre")]).as("allGenres")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("genre").arrayConcat(field("subGenre")).alias("allGenres")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("genre").arrayConcat(field("subGenre")).alias("allGenres")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("genre").array_concat(Field.of("subGenre")).as_("allGenres")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(arrayConcat(field("genre"), field("subGenre")).as("allGenres")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayConcat(firestore.FieldOf("genre"), firestore.FieldOf("subGenre")).As("allGenres"), )). Execute(ctx)
ARRAY_CONTAINS
Синтаксис:
array_contains(array: ARRAY, value: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если value найдено в array , и FALSE в противном случае.
Примеры:
| множество | ценить | array_contains(array, value) |
|---|---|---|
| [1, 2, 3] | 2 | истинный |
| [[1, 2], [3]] | [1, 2] | истинный |
| [1, null] | нулевой | истинный |
| "abc" | ЛЮБОЙ | ошибка |
Node.js
const result = await db.pipeline() .collection("books") .select(field("genre").arrayContains(constant("mystery")).as("isMystery")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("genre").arrayContains(constant("mystery")).as("isMystery")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayContains(Constant("mystery")).as("isMystery")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("genre").arrayContains("mystery").alias("isMystery")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("genre").arrayContains("mystery").alias("isMystery")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("genre").array_contains("mystery").as_("isMystery")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(arrayContains(field("genre"), "mystery").as("isMystery")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayContains(firestore.FieldOf("genre"), "mystery").As("isMystery"), )). Execute(ctx)
ARRAY_CONTAINS_ALL
Синтаксис:
array_contains_all(array: ARRAY, search_values: ARRAY) -> BOOLEAN
Описание:
Возвращает TRUE если все search_values найдены в array , и FALSE в противном случае.
Примеры:
| множество | search_values | array_contains_all(array, search_values) |
|---|---|---|
| [1, 2, 3] | [1, 2] | истинный |
| [1, 2, 3] | [1, 4] | ЛОЖЬ |
| [1, null] | [нулевой] | истинный |
| [NaN] | [NaN] | истинный |
| [] | [] | истинный |
| [1, 2, 3] | [] | истинный |
Node.js
const result = await db.pipeline() .collection("books") .select( field("genre") .arrayContainsAll([constant("fantasy"), constant("adventure")]) .as("isFantasyAdventure") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("genre") .arrayContainsAll([constant("fantasy"), constant("adventure")]) .as("isFantasyAdventure") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("genre") .arrayContainsAll([Constant("fantasy"), Constant("adventure")]) .as("isFantasyAdventure") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("genre") .arrayContainsAll(listOf("fantasy", "adventure")) .alias("isFantasyAdventure") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("genre") .arrayContainsAll(Arrays.asList("fantasy", "adventure")) .alias("isFantasyAdventure") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("genre") .array_contains_all(["fantasy", "adventure"]) .as_("isFantasyAdventure") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( arrayContainsAll(field("genre"), Arrays.asList("fantasy", "adventure")) .as("isFantasyAdventure")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayContainsAll(firestore.FieldOf("genre"), []string{"fantasy", "adventure"}).As("isFantasyAdventure"), )). Execute(ctx)
ARRAY_CONTAINS_ANY
Синтаксис:
array_contains_any(array: ARRAY, search_values: ARRAY) -> BOOLEAN
Описание:
Возвращает TRUE если в array найдено хотя бы одно из значений search_values , и FALSE в противном случае.
Примеры:
| множество | search_values | array_contains_any(array, search_values) |
|---|---|---|
| [1, 2, 3] | [4, 1] | истинный |
| [1, 2, 3] | [4, 5] | ЛОЖЬ |
| [1, 2, null] | [нулевой] | истинный |
Node.js
const result = await db.pipeline() .collection("books") .select( field("genre") .arrayContainsAny([constant("fantasy"), constant("nonfiction")]) .as("isMysteryOrFantasy") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("genre") .arrayContainsAny([constant("fantasy"), constant("nonfiction")]) .as("isMysteryOrFantasy") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("genre") .arrayContainsAny([Constant("fantasy"), Constant("nonfiction")]) .as("isMysteryOrFantasy") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("genre") .arrayContainsAny(listOf("fantasy", "nonfiction")) .alias("isMysteryOrFantasy") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("genre") .arrayContainsAny(Arrays.asList("fantasy", "nonfiction")) .alias("isMysteryOrFantasy") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("genre") .array_contains_any(["fantasy", "nonfiction"]) .as_("isMysteryOrFantasy") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( arrayContainsAny(field("genre"), Arrays.asList("fantasy", "nonfiction")) .as("isMysteryOrFantasy")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayContainsAny(firestore.FieldOf("genre"), []string{"fantasy", "nonfiction"}).As("isMysteryOrFantasy"), )). Execute(ctx)
ARRAY_FILTER
Синтаксис:
array_filter(array: ARRAY, predicate: (ANY) -> BOOLEAN) -> ARRAY
Описание:
Фильтрует array используя predicate выражение, и возвращает новый массив, содержащий только элементы, удовлетворяющие предикату.
- Для каждого элемента
arrayвыполняется оценкаpredicate. Если он возвращаетtrue, элемент включается в результат; в противном случае (если он возвращаетfalseилиnull) он опускается. - Если результат вычисления
predicateне равен логическому значению или значению, функция возвращает ошибку.
Примеры:
| множество | предикат | array_filter(array, predicate) |
|---|---|---|
| [1, 2, 3] | x -> x > 1 | [2, 3] |
| [1, null, 3] | x -> x > 1 | [3] |
| ["a", "b", "c"] | x -> x != "b" | ["a", "c"] |
| [] | x -> true | [] |
ARRAY_GET
Синтаксис:
array_get(array: ARRAY, index: INT64) -> ANY
Описание:
Возвращает элемент array , index которого начинается с 0.
- Если
indexотрицательный, доступ к элементам осуществляется с конца массива, где-1— последний элемент. - Если
arrayне является типомARRAYи неnull, возвращается ошибка. - Если
indexвыходит за пределы допустимого диапазона, функция возвращает отсутствующее значение. - Если
indexне имеет типаINT64, функция возвращает ошибку.
Примеры:
| множество | индекс | array_get(array, index) |
|---|---|---|
| [1, 2, 3] | 0 | 1 |
| [1, 2, 3] | -1 | 3 |
| [1, 2, 3] | 3 | отсутствующий |
| [1, 2, 3] | -4 | отсутствующий |
| "abc" | 0 | ошибка |
| нулевой | 0 | нулевой |
Array | "a" | ошибка |
Array | 2.0 | ошибка |
ДЛИНА МАССИВА
Синтаксис:
array_length(array: ARRAY) -> INT64
Описание:
Возвращает количество элементов в array .
Примеры:
| множество | array_length(array) |
|---|---|
| [1, 2, 3] | 3 |
| [] | 0 |
| [1, 1, 1] | 3 |
| [1, null] | 2 |
Node.js
const result = await db.pipeline() .collection("books") .select(field("genre").arrayLength().as("genreCount")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("genre").arrayLength().as("genreCount")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayLength().as("genreCount")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("genre").arrayLength().alias("genreCount")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("genre").arrayLength().alias("genreCount")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("genre").array_length().as_("genreCount")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(arrayLength(field("genre")).as("genreCount")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayLength(firestore.FieldOf("genre")).As("genreCount"), )). Execute(ctx)
ARRAY_REVERSE
Синтаксис:
array_reverse(array: ARRAY) -> ARRAY
Описание:
Переворачивает заданный array .
Примеры:
| множество | array_reverse(array) |
|---|---|
| [1, 2, 3] | [3, 2, 1] |
| ["а", "б"] | ["б", "а"] |
| [1, 2, 2, 3] | [3, 2, 2, 1] |
Node.js
const result = await db.pipeline() .collection("books") .select(arrayReverse(field("genre")).as("reversedGenres")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("genre").arrayReverse().as("reversedGenres")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayReverse().as("reversedGenres")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("genre").arrayReverse().alias("reversedGenres")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("genre").arrayReverse().alias("reversedGenres")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("genre").array_reverse().as_("reversedGenres")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(arrayReverse(field("genre")).as("reversedGenres")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayReverse(firestore.FieldOf("genre")).As("reversedGenres"), )). Execute(ctx)
ARRAY_FIRST
Синтаксис:
array_first(array: ARRAY) -> ANY
Описание:
Возвращает первый элемент array . Это эквивалентно функции array_get(array, 0) .
- Если
arrayпуст, возвращает отсутствующее значение.
Примеры:
| множество | array_first(array) |
|---|---|
| [1, 2, 3] | 1 |
| [] | отсутствующий |
ARRAY_FIRST_N
Синтаксис:
array_first_n(array: ARRAY, n: INT64) -> ARRAY
Описание:
Возвращает первые n элементов array . Это эквивалентно функции array_slice(array, 0, n) .
- Если
nотрицательное, возвращается ошибка.
Примеры:
| множество | н | array_first_n(array, n) |
|---|---|---|
| [1, 2, 3, 4, 5] | 3 | [1, 2, 3] |
| [1, 2] | 3 | [1, 2] |
| [1, 2, 3] | 0 | [] |
ARRAY_INDEX_OF
Синтаксис:
array_index_of(array: ARRAY, value: ANY) -> INT64
Описание:
Возвращает индекс первого вхождения value в array , начинающийся с 0. Возвращает -1, если value не найдено.
Примеры:
| множество | ценить | array_index_of(array, value) |
|---|---|---|
| [1, 2, 3, 2] | 2 | 1 |
| [1, 2, 3] | 4 | -1 |
| [1, null, 3] | нулевой | 1 |
ARRAY_INDEX_OF_ALL
Синтаксис:
array_index_of_all(array: ARRAY, value: ANY) -> ARRAY<INT64>
Описание:
Возвращает массив, содержащий индексы всех вхождений value в array , начиная с 0. Возвращает [] , если value не найдено.
Примеры:
| множество | ценить | array_index_of_all(array, value) |
|---|---|---|
| [1, 2, 3, 2] | 2 | [1, 3] |
| [1, 2, 3] | 4 | [] |
| [1, null, 3, null] | нулевой | [1, 3] |
ARRAY_LAST
Синтаксис:
array_last(array: ARRAY) -> ANY
Описание:
Возвращает последний элемент array . Это эквивалентно функции array_get(array, -1) .
- Если
arrayпуст, возвращает отсутствующее значение.
Примеры:
| множество | array_last(array) |
|---|---|
| [1, 2, 3] | 3 |
| [] | отсутствующий |
ARRAY_LAST_N
Синтаксис:
array_last_n(array: ARRAY, n: INT64) -> ARRAY
Описание:
Возвращает последние n элементов array .
- Если
nотрицательное, возвращается ошибка.
Примеры:
| множество | н | array_last_n(array, n) |
|---|---|---|
| [1, 2, 3, 4, 5] | 3 | [3, 4, 5] |
| [1, 2] | 3 | [1, 2] |
| [1, 2, 3] | 0 | [] |
ARRAY_SLICE
Синтаксис:
array_slice(array: ARRAY, offset: INT64, length: INT64) -> ARRAY
Описание:
Возвращает подмножество array , начиная с нулевого offset и включая элементы length .
- Если
offsetотрицательное, оно указывает начальную позицию от конца массива, при этом-1соответствует последнему элементу. - Если
lengthпревышает количество элементов, оставшихся в массиве послеoffset, результат распространяется до конца массива. -
lengthдолжна быть неотрицательной, в противном случае возвращается ошибка.
Примеры:
| множество | компенсировать | длина | array_slice(array, offset, length) |
|---|---|---|---|
| [1, 2, 3, 4, 5] | 1 | 3 | [2, 3, 4] |
| [1, 2, 3, 4, 5] | -2 | 2 | [4, 5] |
| [1, 2, 3] | 1 | 5 | [2, 3] |
| [1, 2, 3] | 3 | 2 | [] |
ARRAY_TRANSFORM
Синтаксис:
array_transform(array: ARRAY, expression: (ANY) -> ANY) -> ARRAY
array_transform(array: ARRAY, expression: (ANY, INT64) -> ANY) -> ARRAY
Описание:
Преобразует array , применяя expression к каждому элементу, и возвращает новый массив с преобразованными элементами. Выходной массив всегда будет иметь тот же размер, что и входной массив.
-
expressionможет быть унарной функциейelement -> resultили бинарной функцией(element, index) -> result. - Если
expressionявляется унарным, оно вызывается для каждого элементаarray. - Если
expressionявляется бинарным, оно вызывается для каждого элементаarrayи соответствующего ему индекса, начинающегося с 0.
Примеры:
| множество | выражение | array_transform(array, expression) |
|---|---|---|
| [1, 2, 3] | x -> x * 2 | [2, 4, 6] |
| [1, 2, 3] | x -> x + 1 | [2, 3, 4] |
| [10, 20] | (x, i) -> x + i | [10, 21] |
| [] | x -> 1 | [] |
МАКСИМУМ
Синтаксис:
maximum(array: ARRAY) -> ANY
Описание:
Возвращает максимальное значение в array .
- Значения
NULLигнорируются при сравнении. - Если
arrayпуст или содержит только значенияNULL, возвращаетNULL.
Примеры:
| множество | maximum(array) |
|---|---|
| [1, 5, 2] | 5 |
| [1, null, 5] | 5 |
| ["a", "c", "b"] | "с" |
| [null, null] | нулевой |
| [] | нулевой |
МАКСИМУМ_Н
Синтаксис:
maximum_n(array: ARRAY, n: INT64) -> ARRAY
Описание:
Возвращает массив из n наибольших значений в array в порядке убывания.
- Значения
NULLигнорируются. - If
nis negative, returns an error.
Примеры:
| множество | н | maximum_n(array, n) |
|---|---|---|
| [1, 5, 2, 4, 3] | 3 | [5, 4, 3] |
| [1, null, 5] | 3 | [5, 1] |
МИНИМУМ
Синтаксис:
minimum(array: ARRAY) -> ANY
Описание:
Возвращает минимальное значение в array .
- Значения
NULLигнорируются при сравнении. - Если
arrayпуст или содержит только значенияNULL, возвращаетNULL.
Примеры:
| множество | minimum(array) |
|---|---|
| [1, 5, 2] | 1 |
| [5, null, 1] | 1 |
| ["a", "c", "b"] | "а" |
| [null, null] | нулевой |
| [] | нулевой |
МИНИМУМ_Н
Синтаксис:
minimum_n(array: ARRAY, n: INT64) -> ARRAY
Описание:
Возвращает массив из n наименьших значений в array в порядке возрастания.
- Значения
NULLигнорируются. - Если
nотрицательное, возвращается ошибка.
Примеры:
| множество | н | minimum_n(array, n) |
|---|---|---|
| [1, 5, 2, 4, 3] | 3 | [1, 2, 3] |
| [5, null, 1] | 3 | [1, 5] |
СУММА
Синтаксис:
sum(array: ARRAY) -> INT64 | FLOAT64
Описание:
Возвращает сумму всех NUMERIC значений в ARRAY .
- Нечисловые значения в массиве игнорируются.
- Если какое-либо числовое значение в массиве равно
NaN, функция возвращаетNaN. - Тип возвращаемого значения определяется самым широким числовым типом в массиве:
INT64<FLOAT64. - Если переполнение 64-битного целого числа происходит до суммирования каких-либо значений с плавающей запятой, возвращается ошибка. Если значения с плавающей запятой суммируются, переполнение приведет к значению +/- бесконечность.
- Если массив не содержит числовых значений, функция возвращает
NULL.
Примеры:
| множество | sum(array) |
|---|---|
| [1, 2, 3] | 6 л |
| [1 л, 2 л, 3 л] | 6 л |
| [2000000000, 2000000000] | 4000000000 л |
| [10, 20.5] | 30.5 |
| [1, "а", 2] | 3 л |
| [INT64.MAX_VALUE, 1] | ошибка |
| [INT64.MAX_VALUE, 1, -1.0] | ошибка |
| [INT64.MAX_VALUE, 1.0] | 9.223372036854776e+18 |
ПРИСОЕДИНИТЬСЯ
Синтаксис:
join[T <: STRING | BYTES](array: ARRAY<T>, delimiter: T) -> STRING
join[T <: STRING | BYTES](array: ARRAY<T>, delimiter: T, null_text: T) -> STRING
Описание:
Возвращает конкатенацию элементов array в виде STRING . array может иметь тип данных STRING или BYTES .
- Все элементы в
array,delimiterиnull_textдолжны быть одного типа; все они должны бытьSTRINGилиBYTES. - Если указан
null_text, все значенияNULLвarrayзаменяются наnull_text. - Если
null_textне указан, значенияNULLвarrayисключаются из результата.
Примеры:
Если null_text не указан:
| множество | разделитель | join(array, delimiter) |
|---|---|---|
| ["a", "b", "c"] | "," | "a,b,c" |
| ["a", null, "c"] | "," | "а,с" |
| [b'a', b'b', b'c'] | б',' | б'а,б,с' |
| ["а", б'с'] | "," | ошибка |
| ["а", "с"] | б',' | ошибка |
| [b'a', b'c'] | "," | ошибка |
Если предоставлен null_text :
| множество | разделитель | нулевой текст | join(array, delimiter, null_text) |
|---|---|---|---|
| ["a", null, "c"] | "," | "ОТСУТСТВУЮЩИЙ" | "a,MISSING,c" |
| [b'a', null, b'c'] | б',' | b'NULL' | b'a,NULL,c' |
| [null, "b", null] | "," | "ОТСУТСТВУЮЩИЙ" | "ПРОПАВШИЙ,b,ПРОПАВШИЙ" |
| [b'a', null, null] | б',' | b'NULL' | b'a,NULL,NULL' |
| ["a", null] | "," | б'Н' | ошибка |
| [b'a', null] | б',' | "Н" | ошибка |
Функции сравнения
| Имя | Описание |
EQUAL | Сравнение равенства |
GREATER_THAN | Больше, чем сравнение |
GREATER_THAN_OR_EQUAL | сравнение «больше или равно» |
LESS_THAN | Меньше, чем в сравнении |
LESS_THAN_OR_EQUAL | сравнение меньше или равно |
NOT_EQUAL | Сравнение не равно |
CMP | Общее сравнение |
РАВНЫЙ
Синтаксис:
equal(x: ANY, y: ANY) -> BOOLEAN
Примеры:
x | y | equal(x, y) |
|---|---|---|
| 1 л | 1 л | TRUE |
| 1.0 | 1 л | TRUE |
| -1.0 | 1 л | FALSE |
| NaN | NaN | TRUE |
NULL | NULL | TRUE |
NULL | ABSENT | FALSE |
Описание:
Возвращает TRUE если x и y равны, и FALSE в противном случае.
Node.js
const result = await db.pipeline() .collection("books") .select(field("rating").equal(5).as("hasPerfectRating")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("rating").equal(5).as("hasPerfectRating")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("rating").equal(5).as("hasPerfectRating")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("rating").equal(5).alias("hasPerfectRating")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("rating").equal(5).alias("hasPerfectRating")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").equal(5).as_("hasPerfectRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(equal(field("rating"), 5).as("hasPerfectRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Equal(firestore.FieldOf("rating"), 5).As("hasPerfectRating"), )). Execute(ctx)
БОЛЬШЕ_ЧЕМ
Синтаксис:
greater_than(x: ANY, y: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если x больше y , и FALSE в противном случае.
Если x и y несравнимы, возвращает FALSE .
Примеры:
x | y | greater_than(x, y) |
|---|---|---|
| 1 л | 0.0 | TRUE |
| 1 л | 1 л | FALSE |
| 1 л | 2 л | FALSE |
| "фу" | 0 л | FALSE |
| 0L | "фу" | FALSE |
| NaN | 0 л | FALSE |
| 0 л | NaN | FALSE |
NULL | NULL | FALSE |
Node.js
const result = await db.pipeline() .collection("books") .select(field("rating").greaterThan(4).as("hasHighRating")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("rating").greaterThan(4).as("hasHighRating")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("rating").greaterThan(4).as("hasHighRating")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("rating").greaterThan(4).alias("hasHighRating")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("rating").greaterThan(4).alias("hasHighRating")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").greater_than(4).as_("hasHighRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(greaterThan(field("rating"), 4).as("hasHighRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.GreaterThan(firestore.FieldOf("rating"), 4).As("hasHighRating"), )). Execute(ctx)
GREATER_THAN_OR_EQUAL
Синтаксис:
greater_than_or_equal(x: ANY, y: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если x больше или равно y , и FALSE в противном случае.
Если x и y несравнимы, возвращает FALSE .
Примеры:
x | y | greater_than_or_equal(x, y) |
|---|---|---|
| 1 л | 0.0 | TRUE |
| 1 л | 1 л | TRUE |
| 1 л | 2 л | FALSE |
| "фу" | 0 л | FALSE |
| 0 л | "фу" | FALSE |
| NaN | 0 л | FALSE |
| 0 л | NaN | FALSE |
NULL | NULL | TRUE |
Node.js
const result = await db.pipeline() .collection("books") .select(field("published").greaterThanOrEqual(1900).as("publishedIn20thCentury")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("published").greaterThanOrEqual(1900).as("publishedIn20thCentury")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("published").greaterThanOrEqual(1900).as("publishedIn20thCentury")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("published").greaterThanOrEqual(1900).alias("publishedIn20thCentury")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("published").greaterThanOrEqual(1900).alias("publishedIn20thCentury")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("published") .greater_than_or_equal(1900) .as_("publishedIn20thCentury") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(greaterThanOrEqual(field("published"), 1900).as("publishedIn20thCentury")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.GreaterThanOrEqual(firestore.FieldOf("published"), 1900).As("publishedIn20thCentury"), )). Execute(ctx)
МЕНЬШЕ, ЧЕМ
Синтаксис:
less_than(x: ANY, y: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если x меньше y , и FALSE в противном случае.
Если x и y несравнимы, возвращает FALSE .
Примеры:
x | y | less_than(x, y) |
|---|---|---|
| 1 л | 0.0 | FALSE |
| 1 л | 1 л | FALSE |
| 1 л | 2 л | TRUE |
| "фу" | 0 л | FALSE |
| 0 л | "фу" | FALSE |
| NaN | 0 л | FALSE |
| 0 л | NaN | FALSE |
NULL | NULL | FALSE |
Node.js
const result = await db.pipeline() .collection("books") .select(field("published").lessThan(1923).as("isPublicDomainProbably")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("published").lessThan(1923).as("isPublicDomainProbably")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("published").lessThan(1923).as("isPublicDomainProbably")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("published").lessThan(1923).alias("isPublicDomainProbably")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("published").lessThan(1923).alias("isPublicDomainProbably")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("published").less_than(1923).as_("isPublicDomainProbably")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(lessThan(field("published"), 1923).as("isPublicDomainProbably")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.LessThan(firestore.FieldOf("published"), 1923).As("isPublicDomainProbably"), )). Execute(ctx)
МЕНЬШЕ ИЛИ РАВНО
Синтаксис:
less_than_or_equal(x: ANY, y: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если x меньше или равно y , и FALSE в противном случае.
Если x и y несравнимы, возвращает FALSE .
Примеры:
x | y | less_than(x, y) |
|---|---|---|
| 1 л | 0.0 | FALSE |
| 1 л | 1 л | TRUE |
| 1 л | 2 л | TRUE |
| "фу" | 0 л | FALSE |
| 0 л | "фу" | FALSE |
| NaN | 0 л | FALSE |
| 0 л | NaN | FALSE |
NULL | NULL | TRUE |
Node.js
const result = await db.pipeline() .collection("books") .select(field("rating").lessThanOrEqual(2).as("hasBadRating")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("rating").lessThanOrEqual(2).as("hasBadRating")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("rating").lessThanOrEqual(2).as("hasBadRating")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("rating").lessThanOrEqual(2).alias("hasBadRating")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("rating").lessThanOrEqual(2).alias("hasBadRating")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").less_than_or_equal(2).as_("hasBadRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(lessThanOrEqual(field("rating"), 2).as("hasBadRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.LessThanOrEqual(firestore.FieldOf("rating"), 2).As("hasBadRating"), )). Execute(ctx)
НЕ РАВНО
Синтаксис:
not_equal(x: ANY, y: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если x не равно y , и FALSE в противном случае.
Примеры:
x | y | not_equal(x, y) |
|---|---|---|
| 1 л | 1 л | FALSE |
| 1.0 | 1 л | FALSE |
| -1.0 | 1 л | TRUE |
| NaN | 0L | TRUE |
| NaN | NaN | FALSE |
NULL | NULL | FALSE |
NULL | ABSENT | TRUE |
Node.js
const result = await db.pipeline() .collection("books") .select(field("title").notEqual("1984").as("not1984")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("title").notEqual("1984").as("not1984")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("title").notEqual("1984").as("not1984")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("title").notEqual("1984").alias("not1984")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("title").notEqual("1984").alias("not1984")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("title").not_equal("1984").as_("not1984")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(notEqual(field("title"), "1984").as("not1984")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.NotEqual(firestore.FieldOf("title"), "1984").As("not1984"), )). Execute(ctx)
CMP
Синтаксис:
cmp(x: ANY, y: ANY) -> Int64
Описание:
Compares x & y , returning:
-
1Lifxis greater thany. -
-1Lеслиxменьшеy. - В противном случае
0L.
В отличие от других функций сравнения, функция cmp(...) работает с разными типами данных, следуя тому же порядку, что и на этапе sort(...) . Порядок значений по типам см. в разделе «Порядок типов значений».
Примеры:
x | y | cmp(x, y) |
|---|---|---|
| 1 л | 1 л | 0 л |
| 1.0 | 1 л | 0L |
| -1.0 | 1 л | -1 л |
| 42.5D | "фу" | -1 л |
NULL | NULL | 0 л |
NULL | ABSENT | 0L |
Debugging Functions
| Имя | Описание |
EXISTS | Returns TRUE if the value is not an absent value |
IS_ABSENT | Returns TRUE if the value is an absent value |
IF_ABSENT | Заменяет значение выражением, если оно отсутствует. |
IS_ERROR | Перехватывает и проверяет, была ли сгенерирована ошибка базовым выражением. |
IF_ERROR | Заменяет значение выражением, если возникла ошибка. |
ERROR | Завершает вычисление и возвращает ошибку с указанным сообщением. |
EXISTS
Синтаксис:
exists(value: ANY) -> BOOLEAN
Описание:
Returns TRUE if value is not the absent value.
Примеры:
value | exists(value) |
|---|---|
| 0L | TRUE |
| "фу" | TRUE |
NULL | TRUE |
ABSENT | FALSE |
Node.js
const result = await db.pipeline() .collection("books") .select(field("rating").exists().as("hasRating")) .execute();
Web
Пример:
const result = await execute(db.pipeline() .collection("books") .select(field("rating").exists().as("hasRating")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("rating").exists().as("hasRating")]) .execute()
Kotlin
Пример:
val result = db.pipeline() .collection("books") .select(field("rating").exists().alias("hasRating")) .execute()
Java
Пример:
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("rating").exists().alias("hasRating")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").exists().as_("hasRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(exists(field("rating")).as("hasRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.FieldExists(firestore.FieldOf("rating")).As("hasRating"), )). Execute(ctx)
IS_ABSENT
Синтаксис:
is_absent(value: ANY) -> BOOLEAN
Описание:
Возвращает TRUE если value отсутствует, и FALSE в противном случае. Отсутствующие значения — это значения, которые отсутствуют во входных данных, например, отсутствует поле документа.
Примеры:
value | is_absent(value) |
|---|---|
| 0L | FALSE |
| "фу" | FALSE |
NULL | FALSE |
ABSENT | TRUE |
IF_ABSENT
Синтаксис:
if_absent(value: ANY, replacement: ANY) -> ANY
Описание:
Если value отсутствует, выполняется вычисление и возвращается replacement . В противном случае возвращается value .
Примеры:
value | replacement | if_absent(value, replacement) |
|---|---|---|
| 5 л | 0L | 5 л |
NULL | 0L | NULL |
ABSENT | 0L | 0L |
IS_ERROR
Синтаксис:
is_error(try: ANY) -> BOOLEAN
Описание:
Возвращает TRUE , если во время выполнения конструкции try возникает ошибка. В противном случае возвращает FALSE .
IF_ERROR
Синтаксис:
if_error(try: ANY, catch: ANY) -> ANY
Описание:
Если во время вычисления конструкции try возникает ошибка, выполняется вычисление и возвращается replacement . В противном случае возвращается полученное значение конструкции try .
ОШИБКА
Синтаксис:
error(message: STRING) -> ANY
Описание:
Вычисление функции error приводит к выводу о завершении работы конвейера с ошибкой. Приведенное message включено в сообщение об ошибке.
Примеры:
cond | res | switch_on(cond, res, error("no condition matched")) |
|---|---|---|
TRUE | 1 л | 1 л |
FALSE | 1 л | ERROR ("no condition matched") |
Опорные функции
Тип REFERENCE выступает в роли «указателя» на другие документы в базе данных (или даже на другие базы данных). Следующие функции позволяют управлять этим типом во время выполнения запроса.
| Имя | Описание |
COLLECTION_ID | Возвращает идентификатор коллекции конечных элементов в указанной ссылке. |
DOCUMENT_ID | Возвращает идентификатор документа в указанной ссылке. |
PARENT | Returns the parent reference |
REFERENCE_SLICE | Возвращает подмножество сегментов из заданной ссылки. |
ИДЕНТИФИКАТОР КОЛЛЕКЦИИ
Синтаксис:
collection_id(ref: REFERENCE) -> STRING
Описание:
Возвращает идентификатор коллекции листьев для заданной REFERENCE .
Примеры:
ref | collection_id(ref) |
|---|---|
users/user1 | "users" |
users/user1/posts/post1 | "posts" |
DOCUMENT_ID
Синтаксис:
document_id(ref: REFERENCE) -> ANY
Описание:
Returns the document ID of the given REFERENCE .
Примеры:
ref | document_id(ref) |
|---|---|
users/user1 | "user1" |
users/user1/posts/post1 | "post1" |
РОДИТЕЛЬ
Синтаксис:
parent(ref: REFERENCE) -> REFERENCE
Описание:
Возвращает родительскую REFERENCE для заданной ссылки или NULL , если ссылка уже является корневой.
Примеры:
ref | parent(ref) |
|---|---|
/ | NULL |
users/user1 | / |
users/user1/posts/post1 | users/user1 |
REFERENCE_SLICE
Синтаксис:
reference_slice(ref: REFERENCE, offset: INT, length: INT) -> REFERENCE
Описание:
Объект REFERENCE представляет собой список кортежей (collection_id, document_id) , и он позволяет получить представление этого списка, подобно array_slice(...) .
Возвращает новый REFERENCE , являющийся подмножеством сегментов заданного объекта ref .
-
offset: Начальный индекс (от 0) среза. Если значение отрицательное, это смещение от конца опорной точки. -
length: количество сегментов, которые следует включить в фрагмент.
Примеры:
ref | offset | length | reference_slice(ref, offset, length) |
|---|---|---|---|
a/1/b/2/c/3 | 1 л | 2 л | b/2/c/3 |
a/1/b/2/c/3 | 0 л | 2 л | a/1/b/2 |
a/1/b/2/c/3 | -2L | 2 л | c/3 |
Логические функции
| Имя | Описание |
AND | Performs a logical AND |
OR | Выполняет логическое ИЛИ |
XOR | Performs a logical XOR |
NOT | Выполняет логическое НЕ |
NOR | Performs a logical NOR |
CONDITIONAL | Оценка ветвей на основе условного выражения. |
IF_NULL | Возвращает первое ненулевое значение. |
SWITCH_ON | Оценка филиалов на основе ряда условий. |
EQUAL_ANY | Проверяет, равно ли значение какому-либо элементу массива. |
NOT_EQUAL_ANY | Проверяет, не равно ли значение какому-либо элементу массива. |
MAXIMUM | Возвращает максимальное значение в наборе значений. |
MINIMUM | Returns the minimum value in a set of values |
И
Синтаксис:
and(x: BOOLEAN...) -> BOOLEAN
Описание:
Возвращает логическое И двух или более логических значений.
Возвращает NULL , если результат не может быть получен из-за ABSENT или значения NULL в заданных параметрах.
Примеры:
x | y | and(x, y) |
|---|---|---|
TRUE | TRUE | TRUE |
FALSE | TRUE | FALSE |
NULL | TRUE | NULL |
ABSENT | TRUE | NULL |
NULL | FALSE | FALSE |
FALSE | ABSENT | FALSE |
Node.js
const result = await db.pipeline() .collection("books") .select( and(field("rating").greaterThan(4), field("price").lessThan(10)) .as("under10Recommendation") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( and(field("rating").greaterThan(4), field("price").lessThan(10)) .as("under10Recommendation") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ (Field("rating").greaterThan(4) && Field("price").lessThan(10)) .as("under10Recommendation") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( Expression.and(field("rating").greaterThan(4), field("price").lessThan(10)) .alias("under10Recommendation") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( Expression.and( field("rating").greaterThan(4), field("price").lessThan(10) ).alias("under10Recommendation") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field, And result = ( client.pipeline() .collection("books") .select( And( Field.of("rating").greater_than(4), Field.of("price").less_than(10) ).as_("under10Recommendation") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( and(greaterThan(field("rating"), 4), lessThan(field("price"), 10)) .as("under10Recommendation")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.And( firestore.GreaterThan(firestore.FieldOf("rating"), 4), firestore.LessThan(firestore.FieldOf("price"), 10), ).As("under10Recommendation"), )). Execute(ctx)
ИЛИ
Синтаксис:
or(x: BOOLEAN...) -> BOOLEAN
Описание:
Возвращает логическое ИЛИ двух или более логических значений.
Возвращает NULL , если результат не может быть получен из-за ABSENT или значения NULL в заданных параметрах.
Примеры:
x | y | or(x, y) |
|---|---|---|
TRUE | TRUE | TRUE |
FALSE | TRUE | TRUE |
NULL | TRUE | TRUE |
ABSENT | TRUE | TRUE |
NULL | FALSE | NULL |
FALSE | ABSENT | NULL |
Node.js
const result = await db.pipeline() .collection("books") .select( or(field("genre").equal("Fantasy"), field("tags").arrayContains("adventure")) .as("matchesSearchFilters") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( or(field("genre").equal("Fantasy"), field("tags").arrayContains("adventure")) .as("matchesSearchFilters") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ (Field("genre").equal("Fantasy") || Field("tags").arrayContains("adventure")) .as("matchesSearchFilters") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( Expression.or(field("genre").equal("Fantasy"), field("tags").arrayContains("adventure")) .alias("matchesSearchFilters") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( Expression.or( field("genre").equal("Fantasy"), field("tags").arrayContains("adventure") ).alias("matchesSearchFilters") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field, And, Or result = ( client.pipeline() .collection("books") .select( Or( Field.of("genre").equal("Fantasy"), Field.of("tags").array_contains("adventure"), ).as_("matchesSearchFilters") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( or(equal(field("genre"), "Fantasy"), arrayContains(field("tags"), "adventure")) .as("matchesSearchFilters")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Or( firestore.Equal(firestore.FieldOf("genre"), "Fantasy"), firestore.ArrayContains(firestore.FieldOf("tags"), "adventure"), ).As("matchesSearchFilters"), )). Execute(ctx)
XOR
Синтаксис:
xor(x: BOOLEAN...) -> BOOLEAN
Описание:
Возвращает логическое XOR-операцию над двумя или более логическими значениями.
Возвращает NULL если какое-либо из заданных значений ABSENT или NULL .
Примеры:
x | y | xor(x, y) |
|---|---|---|
TRUE | TRUE | FALSE |
FALSE | FALSE | FALSE |
FALSE | TRUE | TRUE |
NULL | TRUE | NULL |
ABSENT | TRUE | NULL |
NULL | FALSE | NULL |
FALSE | ABSENT | NULL |
Node.js
const result = await execute(db.pipeline() .collection("books") .select( xor(field("tags").arrayContains("magic"), field("tags").arrayContains("nonfiction")) .as("matchesSearchFilters") ) );
Web
const result = await execute(db.pipeline() .collection("books") .select( xor(field("tags").arrayContains("magic"), field("tags").arrayContains("nonfiction")) .as("matchesSearchFilters") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ (Field("tags").arrayContains("magic") ^ Field("tags").arrayContains("nonfiction")) .as("matchesSearchFilters") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( Expression.xor(field("tags").arrayContains("magic"), field("tags").arrayContains("nonfiction")) .alias("matchesSearchFilters") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( Expression.xor( field("tags").arrayContains("magic"), field("tags").arrayContains("nonfiction") ).alias("matchesSearchFilters") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field, Xor result = ( client.pipeline() .collection("books") .select( Xor( [ Field.of("tags").array_contains("magic"), Field.of("tags").array_contains("nonfiction"), ] ).as_("matchesSearchFilters") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( xor( arrayContains(field("tags"), "magic"), arrayContains(field("tags"), "nonfiction")) .as("matchesSearchFilters")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Xor( firestore.ArrayContains(firestore.FieldOf("tags"), "magic"), firestore.ArrayContains(firestore.FieldOf("tags"), "nonfiction"), ).As("matchesSearchFilters"), )). Execute(ctx)
НИ
Синтаксис:
nor(x: BOOLEAN...) -> BOOLEAN
Описание:
Возвращает логическое NOR-выражение двух или более логических значений.
Возвращает NULL , если результат не может быть получен из-за ABSENT или значения NULL в заданных параметрах.
Примеры:
x | y | nor(x, y) |
|---|---|---|
TRUE | TRUE | FALSE |
FALSE | TRUE | FALSE |
FALSE | FALSE | TRUE |
NULL | TRUE | FALSE |
ABSENT | TRUE | FALSE |
NULL | FALSE | NULL |
FALSE | ABSENT | NULL |
НЕТ
Синтаксис:
not(x: BOOLEAN) -> BOOLEAN
Описание:
Возвращает логическое НЕ логического значения.
Node.js
const result = await execute(db.pipeline() .collection("books") .select( field("tags").arrayContains("nonfiction").not() .as("isFiction") ) );
Web
const result = await execute(db.pipeline() .collection("books") .select( field("tags").arrayContains("nonfiction").not() .as("isFiction") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ (!Field("tags").arrayContains("nonfiction")) .as("isFiction") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( Expression.not( field("tags").arrayContains("nonfiction") ).alias("isFiction") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( Expression.not( field("tags").arrayContains("nonfiction") ).alias("isFiction") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field, Not result = ( client.pipeline() .collection("books") .select(Not(Field.of("tags").array_contains("nonfiction")).as_("isFiction")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(not(arrayContains(field("tags"), "nonfiction")).as("isFiction")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Not(firestore.ArrayContains(firestore.FieldOf("tags"), "nonfiction")).As("isFiction"), )). Execute(ctx)
УСЛОВНЫЙ
Синтаксис:
conditional(condition: BOOLEAN, true_case: ANY, false_case: ANY) -> ANY
Описание:
Проверяет condition и возвращает true_case , если оно TRUE .
Выполняет оценку и возвращает значение false_case если условие принимает значение FALSE , NULL или ABSENT .
Примеры:
condition | true_case | false_case | conditional(condition, true_case, false_case) |
|---|---|---|---|
TRUE | 1 л | 0 л | 1 л |
FALSE | 1 л | 0 л | 0 л |
NULL | 1 л | 0 л | 0L |
ABSENT | 1 л | 0 л | 0 л |
Node.js
const result = await execute(db.pipeline() .collection("books") .select( field("tags").arrayConcat([ field("pages").greaterThan(100) .conditional(constant("longRead"), constant("shortRead")) ]).as("extendedTags") ) );
Web
const result = await execute(db.pipeline() .collection("books") .select( field("tags").arrayConcat([ field("pages").greaterThan(100) .conditional(constant("longRead"), constant("shortRead")) ]).as("extendedTags") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("tags").arrayConcat([ ConditionalExpression( Field("pages").greaterThan(100), then: Constant("longRead"), else: Constant("shortRead") ) ]).as("extendedTags") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("tags").arrayConcat( Expression.conditional( field("pages").greaterThan(100), constant("longRead"), constant("shortRead") ) ).alias("extendedTags") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("tags").arrayConcat( Expression.conditional( field("pages").greaterThan(100), constant("longRead"), constant("shortRead") ) ).alias("extendedTags") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import ( Field, Constant, Conditional, ) result = ( client.pipeline() .collection("books") .select( Field.of("tags") .array_concat( Conditional( Field.of("pages").greater_than(100), Constant.of("longRead"), Constant.of("shortRead"), ) ) .as_("extendedTags") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( arrayConcat( field("tags"), conditional( greaterThan(field("pages"), 100), constant("longRead"), constant("shortRead"))) .as("extendedTags")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ArrayConcat( firestore.FieldOf("tags"), firestore.Conditional( firestore.GreaterThan(firestore.FieldOf("pages"), 100), firestore.ConstantOf("longRead"), firestore.ConstantOf("shortRead"), ), ).As("extendedTags"), )). Execute(ctx)
ЕСЛИ_НУЛ
Синтаксис:
if_null(expr: ANY, replacement: ANY) -> ANY
Описание:
Возвращает выражение expr если оно не равно NULL , в противном случае вычисляет его и возвращает replacement . Выражение replacement не вычисляется, если используется expr .
Примеры:
expr | replacement | if_null(expr, replacement) |
|---|---|---|
| 1 л | 2 л | 1 л |
NULL | 2 л | 2 л |
ABSENT | 2 л | ABSENT |
SWITCH_ON
Синтаксис:
switch_on(cond1: BOOLEAN, res1: ANY, cond2: BOOLEAN, res2: ANY, ..., [default: ANY]) -> ANY
Описание:
Оценивает ряд условий и возвращает результат, соответствующий первому условию, имеющему значение TRUE . Если ни одно условие не имеет значения TRUE , возвращается значение default , если оно указано. Если значение default не указано, генерируется ошибка, если ни одно другое условие не имеет значения TRUE .
Чтобы задать значение default , передайте его в качестве последнего аргумента таким образом, чтобы количество аргументов было нечетным.
Примеры:
x | switch_on(eq(x, 1L), "one", eq(x, 2L), "two", "other") |
|---|---|
| 1 л | "один" |
| 2 л | "два" |
| 3 л | "другой" |
EQUAL_ANY
Синтаксис:
equal_any(value: ANY, search_space: ARRAY) -> BOOLEAN
Описание:
Возвращает TRUE если value находится в массиве search_space .
Примеры:
value | search_space | equal_any(value, search_space) |
|---|---|---|
| 0 л | [1 л, 2 л, 3 л] | FALSE |
| 2 л | [1 л, 2 л, 3 л] | TRUE |
NULL | [1 л, 2 л, 3 л] | FALSE |
NULL | [1L, NULL ] | TRUE |
ABSENT | [1L, NULL ] | FALSE |
| NaN | [1 л, NaN, 3 л] | TRUE |
Node.js
const result = await execute(db.pipeline() .collection("books") .select( field("genre").equalAny(["Science Fiction", "Psychological Thriller"]) .as("matchesGenreFilters") ) );
Web
const result = await execute(db.pipeline() .collection("books") .select( field("genre").equalAny(["Science Fiction", "Psychological Thriller"]) .as("matchesGenreFilters") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("genre").equalAny(["Science Fiction", "Psychological Thriller"]) .as("matchesGenreFilters") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("genre").equalAny(listOf("Science Fiction", "Psychological Thriller")) .alias("matchesGenreFilters") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("genre").equalAny(Arrays.asList("Science Fiction", "Psychological Thriller")) .alias("matchesGenreFilters") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("genre") .equal_any(["Science Fiction", "Psychological Thriller"]) .as_("matchesGenreFilters") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( equalAny(field("genre"), Arrays.asList("Science Fiction", "Psychological Thriller")) .as("matchesGenreFilters")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.EqualAny(firestore.FieldOf("genre"), []string{"Science Fiction", "Psychological Thriller"}).As("matchesGenreFilters"), )). Execute(ctx)
НЕ РАВНО НИ ОДНОМУ
Синтаксис:
not_equal_any(value: ANY, search_space: ARRAY) -> BOOLEAN
Описание:
Возвращает TRUE если value отсутствует в массиве search_space .
Примеры:
value | search_space | not_equal_any(value, search_space) |
|---|---|---|
| 0L | [1L, 2L, 3L] | TRUE |
| 2 л | [1 л, 2 л, 3 л] | FALSE |
NULL | [1 л, 2 л, 3 л] | TRUE |
NULL | [1L, NULL ] | FALSE |
ABSENT | [1L, NULL ] | TRUE |
| NaN | [1 л, NaN, 3 л] | FALSE |
Node.js
const result = await execute(db.pipeline() .collection("books") .select( field("author").notEqualAny(["George Orwell", "F. Scott Fitzgerald"]) .as("byExcludedAuthors") ) );
Web
const result = await execute(db.pipeline() .collection("books") .select( field("author").notEqualAny(["George Orwell", "F. Scott Fitzgerald"]) .as("byExcludedAuthors") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("author").notEqualAny(["George Orwell", "F. Scott Fitzgerald"]) .as("byExcludedAuthors") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("author").notEqualAny(listOf("George Orwell", "F. Scott Fitzgerald")) .alias("byExcludedAuthors") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("author").notEqualAny(Arrays.asList("George Orwell", "F. Scott Fitzgerald")) .alias("byExcludedAuthors") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("author") .not_equal_any(["George Orwell", "F. Scott Fitzgerald"]) .as_("byExcludedAuthors") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select( notEqualAny(field("author"), Arrays.asList("George Orwell", "F. Scott Fitzgerald")) .as("byExcludedAuthors")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.NotEqualAny(firestore.FieldOf("author"), []string{"George Orwell", "F. Scott Fitzgerald"}).As("byExcludedAuthors"), )). Execute(ctx)
МАКСИМУМ
Синтаксис:
maximum(x: ANY...) -> ANY
maximum(x: ARRAY) -> ANY
Описание:
Возвращает максимальное значение, отличное от NULL и ABSENT , в последовательности значений x .
Если отсутствуют значения, отличные от NULL или ABSENT , возвращается NULL .
Если существует несколько максимальных эквивалентных значений, может быть возвращено любое из этих значений. Порядок типов значений соответствует документированному порядку .
Примеры:
x | y | maximum(x, y) |
|---|---|---|
FALSE | TRUE | TRUE |
FALSE | -10L | -10L |
| 0.0 | -5L | 0.0 |
| "фу" | "бар" | "фу" |
| "фу" | ["foo"] | ["foo"] |
ABSENT | ABSENT | NULL |
NULL | NULL | NULL |
Node.js
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").maximum().as("maximumPrice")) );
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").maximum().as("maximumPrice")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("rating").logicalMaximum([1]).as("flooredRating") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("rating").logicalMaximum(1).alias("flooredRating") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("rating").logicalMaximum(1).alias("flooredRating") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").logical_maximum(1).as_("flooredRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(logicalMaximum(field("rating"), 1).as("flooredRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.LogicalMaximum(firestore.FieldOf("rating"), 1).As("flooredRating"), )). Execute(ctx)
МИНИМУМ
Синтаксис:
minimum(x: ANY...) -> ANY
minimum(x: ARRAY) -> ANY
Описание:
Возвращает минимальное значение, отличное от NULL и ABSENT , в последовательности значений x .
Если отсутствуют значения, отличные от NULL или ABSENT , возвращается NULL .
Если существует несколько минимальных эквивалентных значений, может быть возвращено любое из этих значений. Порядок типов значений соответствует документированному порядку .
Примеры:
x | y | minimum(x, y) |
|---|---|---|
FALSE | TRUE | FALSE |
FALSE | -10L | FALSE |
| 0.0 | -5 л | -5L |
| "фу" | "бар" | "бар" |
| "фу" | ["foo"] | "фу" |
ABSENT | ABSENT | NULL |
NULL | NULL | NULL |
Node.js
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").minimum().as("minimumPrice")) );
Web
const result = await execute(db.pipeline() .collection("books") .aggregate(field("price").minimum().as("minimumPrice")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("rating").logicalMinimum([5]).as("cappedRating") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("rating").logicalMinimum(5).alias("cappedRating") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("rating").logicalMinimum(5).alias("cappedRating") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("rating").logical_minimum(5).as_("cappedRating")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(logicalMinimum(field("rating"), 5).as("cappedRating")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.LogicalMinimum(firestore.FieldOf("rating"), 5).As("cappedRating"), )). Execute(ctx)
Функции карты
| Имя | Описание |
MAP | Создает значение карты из ряда пар ключ-значение. |
MAP_GET | Returns the value in a map given a specified key |
MAP_SET | Возвращает копию карты с рядом обновленных ключей. |
MAP_REMOVE | Возвращает копию карты, из которой удален ряд ключей. |
MAP_MERGE | Merges a series of maps together. |
CURRENT_CONTEXT | Возвращает текущий контекст в виде карты. |
MAP_KEYS | Возвращает массив всех ключей в карте. |
MAP_VALUES | Returns an array of all values in a map. |
MAP_ENTRIES | Returns an array of key-value pairs of a map. |
КАРТА
Синтаксис:
map(key: STRING, value: ANY, ...) -> MAP
Описание:
Создаёт карту из ряда пар ключ-значение.
MAP_GET
Синтаксис:
map_get(map: ANY, key: STRING) -> ANY
Описание:
Возвращает значение из карты по заданному ключу. Возвращает значение ABSENT , если key отсутствует в карте или если аргумент map не является MAP .
Node.js
const result = await db.pipeline() .collection("books") .select( field("awards").mapGet("pulitzer").as("hasPulitzerAward") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("awards").mapGet("pulitzer").as("hasPulitzerAward") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("awards").mapGet("pulitzer").as("hasPulitzerAward") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("awards").mapGet("pulitzer").alias("hasPulitzerAward") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("awards").mapGet("pulitzer").alias("hasPulitzerAward") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("awards").map_get("pulitzer").as_("hasPulitzerAward")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(mapGet(field("awards"), "pulitzer").as("hasPulitzerAward")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.MapGet(firestore.FieldOf("awards"), "pulitzer").As("hasPulitzerAward"), )). Execute(ctx)
MAP_SET
Синтаксис:
map_set(map: MAP, key: STRING, value: ANY, ...) -> MAP
Описание:
Возвращает копию значения map , содержимое которой обновлено рядом пар ключ-значение.
Если заданное значение отсутствует, соответствующий ключ удаляется из карты.
Если аргумент map не является MAP , возвращает отсутствующее значение.
MAP_REMOVE
Синтаксис:
map_remove(map: MAP, key: STRING...) -> MAP
Описание:
Возвращает копию значения map , из которой удален ряд ключей.
MAP_MERGE
Синтаксис:
map_merge(maps: MAP...) -> MAP
Объединяет содержимое двух или более карт. Если значения в нескольких картах противоречат друг другу, используется последнее значение.
CURRENT_CONTEXT
Синтаксис:
current_context() -> MAP
Возвращает карту, содержащую все доступные поля в текущей точке выполнения.
MAP_KEYS
Синтаксис:
map_keys(map: MAP) -> ARRAY<STRING>
Описание:
Возвращает массив, содержащий все ключи значения map .
MAP_VALUES
Синтаксис:
map_values(map: MAP) -> ARRAY<ANY>
Описание:
Возвращает массив, содержащий все значения, заданные в map .
MAP_ENTRIES
Синтаксис:
map_entries(map: MAP) -> ARRAY<MAP>
Описание:
Возвращает массив, содержащий все пары ключ-значение в значении map .
Каждая пара ключ-значение будет представлена в виде карты с двумя элементами, k и v .
Примеры:
map | map_entries(map) |
|---|---|
| {} | [] |
| {"foo" : 2L} | [{"k": "foo", "v" : 2L}] |
| {"фу": "бар", "бар": "фу"} | [{"k": "foo", "v" : "bar" }, {"k" : "bar", "v": "foo"}] |
Строковые функции
| Имя | Описание |
BYTE_LENGTH | Возвращает количество BYTES в STRING или в BYTES значении. |
CHAR_LENGTH | Возвращает количество символов Юникода в STRING значении. |
STARTS_WITH | Возвращает TRUE если STRING начинается с заданного префикса. |
ENDS_WITH | Возвращает TRUE если STRING заканчивается заданным постфиксом. |
LIKE | Returns TRUE if a STRING matches a pattern |
REGEX_CONTAINS | Возвращает TRUE если значение частично или полностью соответствует регулярному выражению. |
REGEX_MATCH | Возвращает TRUE если хотя бы одна часть значения соответствует регулярному выражению. |
STRING_CONCAT | Concatenates multiple STRING into a STRING |
STRING_CONTAINS | Возвращает TRUE если значение содержит STRING |
STRING_INDEX_OF | Возвращает индекс первого вхождения STRING или BYTES значения (начиная с 0). |
TO_UPPER | Converts a STRING or BYTES value to uppercase. |
TO_LOWER | Преобразует значение STRING или BYTES в нижний регистр. |
SUBSTRING | Получает подстроку из значения типа STRING или BYTES . |
STRING_REVERSE | Переворачивает значение STRING или BYTES . |
STRING_REPEAT | Повторяет значение STRING или BYTES указанное количество раз. |
STRING_REPLACE_ALL | Заменяет все вхождения STRING или BYTES значения. |
STRING_REPLACE_ONE | Заменяет первое вхождение STRING или BYTES значения. |
TRIM | Удаляет начальные и конечные символы из STRING или BYTES значения. |
LTRIM | Удаляет начальные символы из STRING или BYTES значения. |
RTRIM | Удаляет лишние символы из STRING или BYTES значения. |
SPLIT | Разделяет STRING или BYTES значение на массив. |
ДЛИНА_БАЙТА
Синтаксис:
byte_length[T <: STRING | BYTES](value: T) -> INT64
Описание:
Возвращает количество BYTES в STRING или в BYTES .
Примеры:
| ценить | byte_length(value) |
|---|---|
| "abc" | 3 |
| "xyzabc" | 6 |
| б"абк" | 3 |
Node.js
const result = await db.pipeline() .collection("books") .select( field("title").byteLength().as("titleByteLength") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("title").byteLength().as("titleByteLength") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("title").byteLength().as("titleByteLength") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("title").byteLength().alias("titleByteLength") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("title").byteLength().alias("titleByteLength") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("title").byte_length().as_("titleByteLength")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(byteLength(field("title")).as("titleByteLength")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.ByteLength(firestore.FieldOf("title")).As("titleByteLength"), )). Execute(ctx)
ДЛИНА_СИМВОЛА
Синтаксис:
char_length(value: STRING) -> INT64
Описание:
Возвращает количество кодовых точек Юникода в STRING значении.
Примеры:
| ценить | char_length(value) |
|---|---|
| "abc" | 3 |
| "привет" | 5 |
| "мир" | 5 |
Node.js
const result = await db.pipeline() .collection("books") .select( field("title").charLength().as("titleCharLength") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("title").charLength().as("titleCharLength") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("title").charLength().as("titleCharLength") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("title").charLength().alias("titleCharLength") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("title").charLength().alias("titleCharLength") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("title").char_length().as_("titleCharLength")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(charLength(field("title")).as("titleCharLength")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.CharLength(firestore.FieldOf("title")).As("titleCharLength"), )). Execute(ctx)
STARTS_WITH
Синтаксис:
starts_with(value: STRING, prefix: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value начинается с prefix .
Примеры:
| ценить | префикс | starts_with(value, prefix) |
|---|---|---|
| "abc" | "а" | истинный |
| "abc" | "б" | ЛОЖЬ |
| "abc" | "" | истинный |
Node.js
const result = await db.pipeline() .collection("books") .select( field("title").startsWith("The") .as("needsSpecialAlphabeticalSort") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("title").startsWith("The") .as("needsSpecialAlphabeticalSort") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("title").startsWith("The") .as("needsSpecialAlphabeticalSort") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("title").startsWith("The") .alias("needsSpecialAlphabeticalSort") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("title").startsWith("The") .alias("needsSpecialAlphabeticalSort") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("title").starts_with("The").as_("needsSpecialAlphabeticalSort") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(startsWith(field("title"), "The").as("needsSpecialAlphabeticalSort")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.StartsWith(firestore.FieldOf("title"), "The").As("needsSpecialAlphabeticalSort"), )). Execute(ctx)
ЗАВЕРШАЕТСЯ
Синтаксис:
ends_with(value: STRING, postfix: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value заканчивается postfix .
Примеры:
| ценить | постфикс | ends_with(value, postfix) |
|---|---|---|
| "abc" | "с" | истинный |
| "abc" | "б" | ЛОЖЬ |
| "abc" | "" | истинный |
Node.js
const result = await db.pipeline() .collection("inventory/devices/laptops") .select( field("name").endsWith("16 inch") .as("16InLaptops") ) .execute();
Быстрый
let result = try await db.pipeline() .collection("inventory/devices/laptops") .select([ Field("name").endsWith("16 inch") .as("16InLaptops") ]) .execute()
Kotlin
val result = db.pipeline() .collection("inventory/devices/laptops") .select( field("name").endsWith("16 inch") .alias("16InLaptops") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("inventory/devices/laptops") .select( field("name").endsWith("16 inch") .alias("16InLaptops") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("inventory/devices/laptops") .select(Field.of("name").ends_with("16 inch").as_("16InLaptops")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("inventory/devices/laptops") .select(endsWith(field("name"), "16 inch").as("16InLaptops")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("inventory/devices/laptops"). Select(firestore.Fields( firestore.EndsWith(firestore.FieldOf("name"), "16 inch").As("`Laptops16in`"), )). Execute(ctx)
НРАВИТЬСЯ
Синтаксис:
like(value: STRING, pattern: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value соответствует pattern .
Примеры:
| ценить | шаблон | like(value, pattern) |
|---|---|---|
| "Магазин пожарных" | "Огонь%" | истинный |
| "Магазин пожарных" | "%магазин" | истинный |
| "Хранилище данных" | "Data_store" | истинный |
| «100%» | "100%" | истинный |
Node.js
const result = await db.pipeline() .collection("books") .select( field("genre").like("%Fiction") .as("anyFiction") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("genre").like("%Fiction") .as("anyFiction") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("genre").like("%Fiction") .as("anyFiction") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("genre").like("%Fiction") .alias("anyFiction") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("genre").like("%Fiction") .alias("anyFiction") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("genre").like("%Fiction").as_("anyFiction")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(like(field("genre"), "%Fiction").as("anyFiction")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Like(firestore.FieldOf("genre"), "%Fiction").As("anyFiction"), )). Execute(ctx)
REGEX_CONTAINS
Синтаксис:
regex_contains(value: STRING, pattern: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если какая-либо часть value соответствует pattern . Если pattern не является допустимым регулярным выражением, функция возвращает error .
Регулярные выражения следуют синтаксису библиотеки re2 .
Примеры:
| ценить | шаблон | regex_contains(value, pattern) |
|---|---|---|
| "Магазин пожарных" | "Огонь" | истинный |
| "Магазин пожарных" | "магазин$" | истинный |
| "Магазин пожарных" | "данные" | ЛОЖЬ |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("title").regexContains("Firestore (Enterprise|Standard)") .as("isFirestoreRelated") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("title").regexContains("Firestore (Enterprise|Standard)") .as("isFirestoreRelated") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("title").regexContains("Firestore (Enterprise|Standard)") .as("isFirestoreRelated") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("title").regexContains("Firestore (Enterprise|Standard)") .alias("isFirestoreRelated") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("title").regexContains("Firestore (Enterprise|Standard)") .alias("isFirestoreRelated") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select( Field.of("title") .regex_contains("Firestore (Enterprise|Standard)") .as_("isFirestoreRelated") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select( regexContains(field("title"), "Firestore (Enterprise|Standard)") .as("isFirestoreRelated")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.RegexContains(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreRelated"), )). Execute(ctx)
REGEX_MATCH
Синтаксис:
regex_match(value: STRING, pattern: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value полностью соответствует pattern . Если pattern не является допустимым регулярным выражением, функция возвращает error .
Регулярные выражения следуют синтаксису библиотеки re2 .
Примеры:
| ценить | шаблон | regex_match(value, pattern) |
|---|---|---|
| "Магазин пожарных" | "F.*store" | истинный |
| "Магазин пожарных" | "Огонь" | ЛОЖЬ |
| "Магазин пожарных" | "^F.*e$" | истинный |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("title").regexMatch("Firestore (Enterprise|Standard)") .as("isFirestoreExactly") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("title").regexMatch("Firestore (Enterprise|Standard)") .as("isFirestoreExactly") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("title").regexMatch("Firestore (Enterprise|Standard)") .as("isFirestoreExactly") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("title").regexMatch("Firestore (Enterprise|Standard)") .alias("isFirestoreExactly") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("title").regexMatch("Firestore (Enterprise|Standard)") .alias("isFirestoreExactly") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select( Field.of("title") .regex_match("Firestore (Enterprise|Standard)") .as_("isFirestoreExactly") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select( regexMatch(field("title"), "Firestore (Enterprise|Standard)") .as("isFirestoreExactly")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.RegexMatch(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreExactly"), )). Execute(ctx)
STRING_CONCAT
Синтаксис:
string_concat(values: STRING...) -> STRING
Описание:
Объединяет два или более STRING значения в один результат.
Примеры:
| аргументы | string_concat(values...) |
|---|---|
() | ошибка |
("a") | "а" |
("abc", "def") | "abcdef" |
("a", "", "c") | "ac" |
Node.js
const result = await db.pipeline() .collection("books") .select( field("title").stringConcat(" by ", field("author")) .as("fullyQualifiedTitle") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("title").stringConcat(" by ", field("author")) .as("fullyQualifiedTitle") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("title").concat([" by ", Field("author")]) .as("fullyQualifiedTitle") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("title").concat(" by ", field("author")) .alias("fullyQualifiedTitle") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("title").concat(" by ", field("author")) .alias("fullyQualifiedTitle") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select( Field.of("title") .concat(" by ", Field.of("author")) .as_("fullyQualifiedTitle") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(stringConcat(field("title"), " by ", field("author")).as("fullyQualifiedTitle")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.StringConcat(firestore.FieldOf("title"), " by ", firestore.FieldOf("author")).As("fullyQualifiedTitle"), )). Execute(ctx)
STRING_CONTAINS
Синтаксис:
string_contains(value: STRING, substring: STRING) -> BOOLEAN
Описание:
Проверяет, содержит ли value строковый литерал substring String.
Примеры:
| ценить | подстрока | string_contains(value, substring) |
|---|---|---|
| "abc" | "б" | истинный |
| "abc" | "д" | ЛОЖЬ |
| "abc" | "" | истинный |
| "ac" | "." | истинный |
| "☃☃☃" | "☃" | истинный |
Node.js
const result = await db.pipeline() .collection("articles") .select( field("body").stringContains("Firestore") .as("isFirestoreRelated") ) .execute();
Web
const result = await execute(db.pipeline() .collection("articles") .select( field("body").stringContains("Firestore") .as("isFirestoreRelated") ) );
Быстрый
let result = try await db.pipeline() .collection("articles") .select([ Field("body").stringContains("Firestore") .as("isFirestoreRelated") ]) .execute()
Kotlin
val result = db.pipeline() .collection("articles") .select( field("body").stringContains("Firestore") .alias("isFirestoreRelated") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("articles") .select( field("body").stringContains("Firestore") .alias("isFirestoreRelated") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("articles") .select(Field.of("body").string_contains("Firestore").as_("isFirestoreRelated")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("articles") .select(stringContains(field("body"), "Firestore").as("isFirestoreRelated")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("articles"). Select(firestore.Fields( firestore.StringContains(firestore.FieldOf("body"), "Firestore").As("isFirestoreRelated"), )). Execute(ctx)
STRING_INDEX_OF
Синтаксис:
string_index_of[T <: STRING | BYTES](value: T, search: T) -> INT64
Описание:
Возвращает индекс первого вхождения search value , начинающийся с 0.
- Возвращает
-1еслиsearchне найден. - Если
valueявляетсяSTRING, результат измеряется в кодовых точках Юникода. Если это значениеBYTES, результат измеряется в байтах. - Если
searchзначение представляет собой пустуюSTRINGилиBYTES, результат равен0.
Примеры:
| ценить | поиск | string_index_of(value, search) |
|---|---|---|
| "Привет, мир" | "о" | 4 |
| "Привет, мир" | "л" | 2 |
| "Привет, мир" | "з" | -1 |
| "банан" | "на" | 2 |
| "abc" | "" | 0 |
| б"абк" | б"б" | 1 |
| "é" | "é" | 0 |
| быть" | быть" | 0 |
TO_UPPER
Синтаксис:
to_upper[T <: STRING | BYTES](value: T) -> T
Описание:
Преобразует значение STRING или BYTES в верхний регистр.
Если байт или символ не соответствует строчному буквенному символу UTF-8, он передается без изменений.
Примеры:
| ценить | to_upper(value) |
|---|---|
| "abc" | "ABC" |
| "АбС" | "ABC" |
| б"абк" | б"ABC" |
| б"а1с" | б"А1С" |
Node.js
const result = await db.pipeline() .collection("authors") .select( field("name").toUpper() .as("uppercaseName") ) .execute();
Web
const result = await execute(db.pipeline() .collection("authors") .select( field("name").toUpper() .as("uppercaseName") ) );
Быстрый
let result = try await db.pipeline() .collection("authors") .select([ Field("name").toUpper() .as("uppercaseName") ]) .execute()
Kotlin
val result = db.pipeline() .collection("authors") .select( field("name").toUpper() .alias("uppercaseName") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("authors") .select( field("name").toUpper() .alias("uppercaseName") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("authors") .select(Field.of("name").to_upper().as_("uppercaseName")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("authors") .select(toUpper(field("name")).as("uppercaseName")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("authors"). Select(firestore.Fields( firestore.ToUpper(firestore.FieldOf("name")).As("uppercaseName"), )). Execute(ctx)
TO_LOWER
Синтаксис:
to_lower[T <: STRING | BYTES](value: T) -> T
Описание:
Преобразует значение STRING или BYTES в нижний регистр.
Если байт или символ не соответствует заглавной букве алфавита UTF-8, он передается без изменений.
Примеры:
| ценить | to_lower(value) |
|---|---|
| "ABC" | "abc" |
| "АбС" | "abc" |
| "A1C" | "a1c" |
| б"ABC" | б"абк" |
Node.js
const result = await db.pipeline() .collection("authors") .select( field("genre").toLower().equal("fantasy") .as("isFantasy") ) .execute();
Web
const result = await execute(db.pipeline() .collection("authors") .select( field("genre").toLower().equal("fantasy") .as("isFantasy") ) );
Быстрый
let result = try await db.pipeline() .collection("authors") .select([ Field("genre").toLower().equal("fantasy") .as("isFantasy") ]) .execute()
Kotlin
val result = db.pipeline() .collection("authors") .select( field("genre").toLower().equal("fantasy") .alias("isFantasy") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("authors") .select( field("genre").toLower().equal("fantasy") .alias("isFantasy") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("authors") .select(Field.of("genre").to_lower().equal("fantasy").as_("isFantasy")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("authors") .select(equal(toLower(field("genre")), "fantasy").as("isFantasy")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("authors"). Select(firestore.Fields( firestore.Equal(firestore.ToLower(firestore.FieldOf("genre")), "fantasy").As("isFantasy"), )). Execute(ctx)
ПОДСТРОКА
Синтаксис:
substring[T <: STRING | BYTES](input: T, position: INT64) -> T
substring[T <: STRING | BYTES](input: T, position: INT64, length: INT64) -> T
Описание:
Возвращает подстроку из input , начиная с position (индекс от нуля) и включая до length . Если length не указана, возвращает подстроку от position до конца input .
Если
inputпредставляют собойSTRING,positionиlengthизмеряются в кодовых точках Юникода. Если это значениеBYTES, они измеряются в байтах.Если
positionпревышает длинуinput, возвращается пустая подстрока. Если суммаpositionиlengthпревышает длинуinput, подстрока обрезается до концаinput.Если
positionотрицательное, позиция берется с конца входного потока. Если отрицательное значениеpositionпревышает размер входного потока, position устанавливается равным нулю.lengthдолжно быть неотрицательным.
Примеры:
Если length не указана:
| вход | позиция | substring(input, position) |
|---|---|---|
| "abc" | 0 | "abc" |
| "abc" | 1 | "до н.э." |
| "abc" | 3 | "" |
| "abc" | -1 | "с" |
| б"абк" | 1 | б"бк" |
Если указана length :
| вход | позиция | длина | substring(input, position, length) |
|---|---|---|---|
| "abc" | 0 | 1 | "а" |
| "abc" | 1 | 2 | "до н.э." |
| "abc" | -1 | 1 | "с" |
| б"абк" | 0 | 1 | б"а" |
Node.js
const result = await db.pipeline() .collection("books") .where(field("title").startsWith("The ")) .select( field("title").substring(4) .as("titleWithoutLeadingThe") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .where(field("title").startsWith("The ")) .select( field("title").substring(4) .as("titleWithoutLeadingThe") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .where(Field("title").startsWith("The ")) .select([ Field("title").substring(position: 4) .as("titleWithoutLeadingThe") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .where(field("title").startsWith("The ")) .select( field("title") .substring(constant(4), field("title").charLength().subtract(4)) .alias("titleWithoutLeadingThe") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .where(field("title").startsWith("The ")) .select( field("title").substring( constant(4), field("title").charLength().subtract(4)) .alias("titleWithoutLeadingThe") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .where(Field.of("title").starts_with("The ")) .select(Field.of("title").substring(4).as_("titleWithoutLeadingThe")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .where(startsWith(field("title"), "The ")) .select( substring(field("title"), constant(4), field("title").charLength()) .as("titleWithoutLeadingThe")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Where(firestore.StartsWith(firestore.FieldOf("title"), "The ")). Select(firestore.Fields( firestore.Substring(firestore.FieldOf("title"), firestore.ConstantOf(4), firestore.FieldOf("title").CharLength()).As("titleWithoutLeadingThe"), )). Execute(ctx)
STRING_REVERSE
Синтаксис:
string_reverse[T <: STRING | BYTES](input: T) -> T
Описание:
Возвращает введенные данные в обратном порядке.
Символы разграничиваются кодовыми точками Unicode, когда входные данные представляют собой STRING , и байтами, когда входные данные представляют собой значение BYTES .
Примеры:
| вход | string_reverse(input) |
|---|---|
| "abc" | "cba" |
| "a🌹b" | "б🌹а" |
| "привет" | "оллех" |
| б"абк" | б"кба" |
Node.js
const result = await db.pipeline() .collection("books") .select( field("name").reverse().as("reversedName") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("name").reverse().as("reversedName") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("name").reverse().as("reversedName") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("name").reverse().alias("reversedName") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("name").reverse().alias("reversedName") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("name").string_reverse().as_("reversedName")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(reverse(field("name")).as("reversedName")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Reverse(firestore.FieldOf("name")).As("reversedName"), )). Execute(ctx)
STRING_REPEAT
Синтаксис:
string_repeat[T <: STRING | BYTES](input: T, repetitions: INT64) -> T
Описание:
Возвращает input , repetitions раз.
-
repetitionsдолжно быть неотрицательным целым числом. - Если
repetitionsравно0, возвращает пустое значение того же типа, что иinput. - Если размер полученного результата превышает максимально допустимый (1 МБ), возвращается ошибка.
Примеры:
| вход | повторения | string_repeat(input, repetitions) |
|---|---|---|
| "фу" | 3 | "фуфуфу" |
| "фу" | 0 | "" |
| "а " | 3 | "ааа" |
| б"аб" | 2 | б"абаб" |
| "é🦆" | 2 | "é🦆é🦆" |
STRING_REPLACE_ALL
Синтаксис:
string_replace_all[T <: STRING | BYTES](input: T, find: T, replacement: T) -> T
Описание:
Заменяет все непересекающиеся вхождения find во input на replacement .
- В результатах поиска регистр имеет значение.
- Если
findпустое, замены не производятся.
Примеры:
| вход | находить | замена | string_replace_all(input, find, replacement) |
|---|---|---|---|
| "фубарфу" | "фу" | "баз" | "базбарбаз" |
| "абабаб" | "аба" | "с" | "cbab" |
| "фубар" | "о" | "" | "fbar" |
| "é🦆🌎🦆" | "🦆" | "а" | "éa🌎a" |
| б"абк" | б"б" | б"д" | б"адк" |
STRING_REPLACE_ONE
Синтаксис:
string_replace_one[T <: STRING | BYTES](input: T, find: T, replacement: T) -> T
Описание:
Заменяет первое вхождение слова find во input на replacement .
- В результатах поиска регистр имеет значение.
- Если
findпустое, замены не производятся.
Примеры:
| вход | находить | замена | string_replace_one(input, find, replacement) |
|---|---|---|---|
| "фубарфу" | "фу" | "баз" | "базбарфу" |
| "é" | "é" | "а" | "а" |
| b"фубар" | б"о" | б"з" | b"fzoobar" |
ПОДРЕЗАТЬ
Синтаксис:
trim[T <: STRING | BYTES](input: T, values_to_trim: T) -> T
trim[T <: STRING | BYTES](input: T) -> T
Описание:
Удаляет указанный набор BYTES или CHARS из начала и конца предоставленного input .
- Если
values_to_trimне указано, удаляются пробелы.
Примеры:
Если values_to_trim не указан:
| вход | trim(input) |
|---|---|
| "фу" | "фу" |
| б" фу " | б"фу" |
| "фу" | "фу" |
| "" | "" |
| " " | "" |
| "\t foo \n" | "фу" |
| б"\t фу \n" | б"фу" |
| "\r\f\v foo \r\f\v" | "фу" |
| b"\r\f\v foo \r\f\v" | б"фу" |
Если указан values_to_trim :
| вход | values_to_trim | trim(input, values_to_trim) |
|---|---|---|
| "abcbfooaacb" | "abc" | "фу" |
| "abcdaabadbac" | "abc" | "даабад" |
| б"C1C2C3" | б"С1" | б"C2C3" |
| б"C1C2" | "фу" | ошибка |
| "фу" | б"С1" | ошибка |
Web
const result = await execute(db.pipeline() .collection("books") .select( field("name").trim().as("whitespaceTrimmedName") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("name").trim(" \n\t").as("whitespaceTrimmedName") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("name").trim().alias("whitespaceTrimmedName") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("name").trim().alias("whitespaceTrimmedName") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("name").trim().as_("whitespaceTrimmedName")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(trim(field("name")).as("whitespaceTrimmedName")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.Trim(firestore.FieldOf("name")).As("whitespaceTrimmedName"), )). Execute(ctx)
ЛТРИМ
Синтаксис:
ltrim[T <: STRING | BYTES](value: T, to_trim: T) -> T
ltrim[T <: STRING | BYTES](value: T) -> T
Описание:
Удаляет указанный набор BYTES или CHARS из начала заданного value .
- Если
to_trimне указан, удаляются начальные пробельные символы.
Примеры:
When to_trim is not provided:
| ценить | ltrim(value) |
|---|---|
| "фу" | "фу" |
| "фу" | "фу" |
Если указан to_trim :
| ценить | to_trim | ltrim(value, to_trim) |
|---|---|---|
| "aaabc" | "a" | "до н.э." |
| "абакаба" | "ба" | "каба" |
| "é" | "é" | "" |
RTRIM
Синтаксис:
rtrim[T <: STRING | BYTES](value: T, to_trim: T) -> T
rtrim[T <: STRING | BYTES](value: T) -> T
Описание:
Удаляет указанный набор BYTES или CHARS с конца заданного value .
- Если
to_trimне указан, удаляются пробелы в конце символа.
Примеры:
Если to_trim не указан:
| ценить | rtrim(value) |
|---|---|
| "фу" | "фу" |
| "фу" | "фу" |
Если указан to_trim :
| ценить | to_trim | rtrim(value, to_trim) |
|---|---|---|
| "abccc" | "с" | "аб" |
| "абакаба" | "ба" | "абак" |
| "é" | "é" | "" |
РАСКОЛОТЬ
Синтаксис:
split(input: STRING) -> ARRAY<STRING>
split[T <: STRING | BYTES](input: T, delimiter: T) -> ARRAY<T>
Описание:
Разделяет STRING или BYTES значение с помощью разделителя.
Для
STRINGразделителем по умолчанию является запятая,. Разделитель рассматривается как единая строка.Для
BYTESнеобходимо указать разделитель.Разделение по пустому разделителю приводит к созданию массива кодовых точек Unicode для
STRINGзначений и массиваBYTESдляBYTESзначений.Разделение пустой
STRINGвозвращаетARRAY, содержащий одну пустуюSTRING.
Примеры:
Если delimiter не указан:
| вход | split(input) |
|---|---|
| "фу,бар,фу" | ["foo", "bar", "foo"] |
| "фу" | ["фу"] |
| ",фу," | ["", "фу", ""] |
| "" | [""] |
| б"C120C2C4" | ошибка |
Если указан delimiter :
| вход | разделитель | split(input, delimiter) |
|---|---|---|
| "фу бар фу" | " " | ["foo", "bar", "foo"] |
| "фу бар фу" | "з" | ["фу бар фу"] |
| "abc" | "" | ["a", "b", "c"] |
| б"C1,C2,C4" | б"," | [b"C1", b"C2", b"C4"] |
| б"ABC" | б"" | [б"А", б"Б", б"С"] |
| "фу" | б"С1" | ошибка |
Функции временных меток
| Имя | Описание |
CURRENT_TIMESTAMP | Генерирует TIMESTAMP соответствующую времени запроса. |
TIMESTAMP_TRUNC | Усекает TIMESTAMP до заданного значения. |
UNIX_MICROS_TO_TIMESTAMP | Преобразует количество микросекунд с 1970-01-01 00:00:00 UTC в TIMESTAMP |
UNIX_MILLIS_TO_TIMESTAMP | Преобразует количество миллисекунд с 1970-01-01 00:00:00 UTC в TIMESTAMP |
UNIX_SECONDS_TO_TIMESTAMP | Преобразует количество секунд с 1970-01-01 00:00:00 UTC в TIMESTAMP |
TIMESTAMP_ADD | Добавляет временной интервал к TIMESTAMP |
TIMESTAMP_SUB | Вычитает временной интервал из TIMESTAMP |
TIMESTAMP_TO_UNIX_MICROS | Преобразует TIMESTAMP в количество микросекунд с 1970-01-01 00:00:00 UTC |
TIMESTAMP_TO_UNIX_MILLIS | Преобразует TIMESTAMP в количество миллисекунд с 1970-01-01 00:00:00 UTC |
TIMESTAMP_TO_UNIX_SECONDS | Преобразует TIMESTAMP в количество секунд с 1970-01-01 00:00:00 UTC |
TIMESTAMP_DIFF | Возвращает общее количество заданных интервалов unit между двумя метками TIMESTAMP . |
TIMESTAMP_EXTRACT | Извлекает определенную part (например, год, месяц, день) из TIMESTAMP . |
ТЕКУЩАЯ_ВРЕМЕННАЯ_МЕТКА
Синтаксис:
current_timestamp() -> TIMESTAMP
Описание:
Получает метку времени в начале input времени запроса (интерпретируется как количество микросекунд с 1970-01-01 00:00:00 UTC ).
Это значение стабильно в рамках одного запроса и всегда будет возвращать одно и то же значение при многократном вызове.
TIMESTAMP_TRUNC
Синтаксис:
timestamp_trunc(timestamp: TIMESTAMP, granularity: STRING[, timezone: STRING]) -> TIMESTAMP
Описание:
Усекает временную метку до заданной точности.
Аргумент granularity должен быть строкой и одним из следующих значений:
-
microsecond -
millisecond -
second -
minute -
hour -
day -
week -
week([weekday]) -
month -
quarter -
year -
isoyear
Если указан аргумент timezone , обрезка будет производиться на основе календарных границ заданного часового пояса (например, обрезка дня будет производиться до полуночи в заданном часовом поясе). При обрезке будет учитываться переход на летнее время.
Если timezone не указан, обрезка будет производиться на основе границ календаря UTC .
Аргумент timezone должен представлять собой строковое значение часового пояса из базы данных tz, например, America/New_York . Также можно использовать пользовательское смещение времени, указав смещение относительно GMT .
Примеры:
timestamp | granularity | timezone | timestamp_trunc(timestamp, granularity, timezone) |
|---|---|---|---|
| 2000-01-01 10:20:30:123456 UTC | "второй" | Не предоставлено | 2001-01-01 10:20:30 UTC |
| 1997-05-31 04:30:30 UTC | "день" | Не предоставлено | 1997-05-31 00:00:00 UTC |
| 1997-05-31 04:30:30 UTC | "день" | "Америка/Лос-Анджелес" | 1997-05-30 07:00:00 UTC |
| 2001-03-16 04:00:00 UTC | "неделя (пятница) | Не предоставлено | 2001-03-16 00:00:00 UTC |
| 2001-03-23 04:00:00 UTC | "неделя (пятница) | "Америка/Лос-Анджелес" | 2001-03-23 17:00:00 UTC |
| 2026-01-24 20:00:00 UTC | "месяц" | "GMT+06:32:43" | 2026-01-01T06:32:43 UTC |
UNIX_MICROS_TO_TIMESTAMP
Синтаксис:
unix_micros_to_timestamp(input: INT64) -> TIMESTAMP
Описание:
Преобразует input (интерпретируемые как количество микросекунд с 1970-01-01 00:00:00 UTC ) в TIMESTAMP ). Выбрасывает error , если input не могут быть преобразованы в допустимую TIMESTAMP .
Примеры:
input | unix_micros_to_timestamp(input) |
|---|---|
| 0 л | 1970-01-01 00:00:00 UTC |
| 400123456L | 1970-01-01 00:06:40.123456 UTC |
| -1000000L | 1969-12-31 23:59:59 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("createdAtMicros").unixMicrosToTimestamp().alias("createdAtString") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("createdAtMicros").unixMicrosToTimestamp().alias("createdAtString") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select( Field.of("createdAtMicros") .unix_micros_to_timestamp() .as_("createdAtString") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(unixMicrosToTimestamp(field("createdAtMicros")).as("createdAtString")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.UnixMicrosToTimestamp(firestore.FieldOf("createdAtMicros")).As("createdAtString"), )). Execute(ctx)
UNIX_MILLIS_TO_TIMESTAMP
Синтаксис:
unix_millis_to_timestamp(input: INT64) -> TIMESTAMP
Описание:
Преобразует input (интерпретируемые как количество миллисекунд с 1970-01-01 00:00:00 UTC ) в тип TIMESTAMP . Выбрасывает error , если input не могут быть преобразованы в допустимый тип TIMESTAMP .
Примеры:
input | unix_millis_to_timestamp(input) |
|---|---|
| 0L | 1970-01-01 00:00:00 UTC |
| 4000123L | 1970-01-01 01:06:40.123 UTC |
| -1000000 л | 1969-12-31 23:43:20 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("createdAtMillis").unixMillisToTimestamp().as("createdAtString") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("createdAtMillis").unixMillisToTimestamp().as("createdAtString") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("createdAtMillis").unixMillisToTimestamp().as("createdAtString") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("createdAtMillis").unixMillisToTimestamp().alias("createdAtString") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("createdAtMillis").unixMillisToTimestamp().alias("createdAtString") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select( Field.of("createdAtMillis") .unix_millis_to_timestamp() .as_("createdAtString") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(unixMillisToTimestamp(field("createdAtMillis")).as("createdAtString")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.UnixMillisToTimestamp(firestore.FieldOf("createdAtMillis")).As("createdAtString"), )). Execute(ctx)
UNIX_SECONDS_TO_TIMESTAMP
Синтаксис:
unix_seconds_to_timestamp(input: INT64) -> TIMESTAMP
Описание:
Преобразует input (интерпретируемые как количество секунд с 1970-01-01 00:00:00 UTC ) в тип TIMESTAMP . Выбрасывает error , если input не могут быть преобразованы в допустимый тип TIMESTAMP .
Примеры:
input | unix_seconds_to_timestamp(input) |
|---|---|
| 0L | 1970-01-01 00:00:00 UTC |
| 60 л | 1970-01-01 00:01:00 UTC |
| -300L | 1969-12-31 23:55:00 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("createdAtSeconds").unixSecondsToTimestamp().alias("createdAtString") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("createdAtSeconds").unixSecondsToTimestamp().alias("createdAtString") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select( Field.of("createdAtSeconds") .unix_seconds_to_timestamp() .as_("createdAtString") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(unixSecondsToTimestamp(field("createdAtSeconds")).as("createdAtString")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.UnixSecondsToTimestamp(firestore.FieldOf("createdAtSeconds")).As("createdAtString"), )). Execute(ctx)
TIMESTAMP_ADD
Синтаксис:
timestamp_add(timestamp: TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP
Описание:
Добавляет amount unit из timestamp . Аргумент amount может быть отрицательным, в этом случае он эквивалентен TIMESTAMP_SUB .
Аргумент unit должен быть строкой и содержать одно из следующих значений:
-
microsecond -
millisecond -
second -
minute -
hour -
day
Вызывает ошибку, если полученная метка времени не укладывается в диапазон TIMESTAMP .
Примеры:
timestamp | unit | amount | timestamp_add(timestamp, unit, amount) |
|---|---|---|---|
| 2025-02-20 00:00:00 UTC | "minute" | 2 л | 2025-02-20 00:02:00 UTC |
| 2025-02-20 00:00:00 UTC | "час" | -4L | 2025-02-19 20:00:00 UTC |
| 2025-02-20 00:00:00 UTC | "день" | 5 л | 2025-02-25 00:00:00 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("createdAt").timestampAdd("day", 3653).as("expiresAt") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("createdAt").timestampAdd("day", 3653).as("expiresAt") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("createdAt").timestampAdd(3653, .day).as("expiresAt") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("createdAt") .timestampAdd("day", 3653) .alias("expiresAt") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("createdAt").timestampAdd("day", 3653).alias("expiresAt") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select(Field.of("createdAt").timestamp_add("day", 3653).as_("expiresAt")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(timestampAdd(field("createdAt"), "day", 3653).as("expiresAt")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.TimestampAdd(firestore.FieldOf("createdAt"), "day", 3653).As("expiresAt"), )). Execute(ctx)
TIMESTAMP_SUB
Синтаксис:
timestamp_sub(timestamp: TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP
Описание:
Вычитает amount unit из timestamp . Аргумент amount может быть отрицательным, в этом случае он эквивалентен TIMESTAMP_ADD .
Аргумент unit должен быть строкой и содержать одно из следующих значений:
-
microsecond -
millisecond -
second -
minute -
hour -
day
Throws an error if the resulting timestamp does not fit within the TIMESTAMP range.
Примеры:
timestamp | unit | amount | timestamp_sub(timestamp, unit, amount) |
|---|---|---|---|
| 2026-07-04 00:00:00 UTC | "minute" | 40 л | 2026-07-03 23:20:00 UTC |
| 2026-07-04 00:00:00 UTC | "час" | -24L | 2026-07-05 00:00:00 UTC |
| 2026-07-04 00:00:00 UTC | "день" | 3 л | 2026-07-01 00:00:00 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("expiresAt").timestampSubtract(14, .day).as("sendWarningTimestamp") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("expiresAt") .timestampSubtract("day", 14) .alias("sendWarningTimestamp") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("expiresAt").timestampSubtract("day", 14).alias("sendWarningTimestamp") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select( Field.of("expiresAt") .timestamp_subtract("day", 14) .as_("sendWarningTimestamp") ) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(timestampSubtract(field("expiresAt"), "day", 14).as("sendWarningTimestamp")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.TimestampSubtract(firestore.FieldOf("expiresAt"), "day", 14).As("sendWarningTimestamp"), )). Execute(ctx)
TIMESTAMP_TO_UNIX_MICROS
Синтаксис:
timestamp_to_unix_micros(input: TIMESTAMP) -> INT64
Описание:
Converts input to the number of microseconds since 1970-01-01 00:00:00 UTC . Truncates higher levels of precision by rounding down to the beginning of the microsecond.
Примеры:
input | timestamp_to_unix_micros(input) |
|---|---|
| 1970-01-01 00:00:00 UTC | 0L |
| 1970-01-01 00:06:40.123456 UTC | 400123456L |
| 1969-12-31 23:59:59 UTC | -1000000L |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMicros().as("unixMicros") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMicros().as("unixMicros") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("dateString").timestampToUnixMicros().as("unixMicros") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMicros().alias("unixMicros") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMicros().alias("unixMicros") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select(Field.of("dateString").timestamp_to_unix_micros().as_("unixMicros")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(timestampToUnixMicros(field("dateString")).as("unixMicros")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.TimestampToUnixMicros(firestore.FieldOf("dateString")).As("unixMicros"), )). Execute(ctx)
TIMESTAMP_TO_UNIX_MILLIS
Синтаксис:
timestamp_to_unix_millis(input: TIMESTAMP) -> INT64
Описание:
Converts input to the number of milliseconds since 1970-01-01 00:00:00 UTC . Truncates higher levels of precision by rounding down to the beginning of the millisecond.
Примеры:
input | timestamp_to_unix_millis(input) |
|---|---|
| 1970-01-01 00:00:00 UTC | 0L |
| 1970-01-01 01:06:40.123 UTC | 4000123L |
| 1969-12-31 23:43:20 | -1000000L |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMillis().as("unixMillis") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMillis().as("unixMillis") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("dateString").timestampToUnixMillis().as("unixMillis") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMillis().alias("unixMillis") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixMillis().alias("unixMillis") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select(Field.of("dateString").timestamp_to_unix_millis().as_("unixMillis")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(timestampToUnixMillis(field("dateString")).as("unixMillis")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.TimestampToUnixMillis(firestore.FieldOf("dateString")).As("unixMillis"), )). Execute(ctx)
TIMESTAMP_TO_UNIX_SECONDS
Синтаксис:
timestamp_to_unix_seconds(input: TIMESTAMP) -> INT64
Описание:
Converts input to the number of seconds since 1970-01-01 00:00:00 UTC . Truncates higher levels of precision by rounding down to the beginning of the second.
Примеры:
input | timestamp_to_unix_seconds(input) |
|---|---|
| 1970-01-01 00:00:00 UTC | 0L |
| 1970-01-01 00:01:00 UTC | 60 л |
| 1969-12-31 23:55:00 UTC | -300L |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixSeconds().as("unixSeconds") ) .execute();
Web
const result = await execute(db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixSeconds().as("unixSeconds") ) );
Быстрый
let result = try await db.pipeline() .collection("documents") .select([ Field("dateString").timestampToUnixSeconds().as("unixSeconds") ]) .execute()
Kotlin
val result = db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixSeconds().alias("unixSeconds") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("documents") .select( field("dateString").timestampToUnixSeconds().alias("unixSeconds") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("documents") .select(Field.of("dateString").timestamp_to_unix_seconds().as_("unixSeconds")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("documents") .select(timestampToUnixSeconds(field("dateString")).as("unixSeconds")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("documents"). Select(firestore.Fields( firestore.TimestampToUnixSeconds(firestore.FieldOf("dateString")).As("unixSeconds"), )). Execute(ctx)
TIMESTAMP_DIFF
Синтаксис:
timestamp_diff(end: TIMESTAMP, start: TIMESTAMP, unit: STRING) -> INT64
Описание:
Returns the whole number of specified unit intervals between two TIMESTAMP s.
- Returns a negative value if
endis beforestart. - Truncates any fractional unit. For example,
timestamp_diff("2021-01-01 00:00:01", "2021-01-01 00:00:00", "minute")returns0.
The unit argument must be a string and one of the following:
-
microsecond -
millisecond -
second -
minute -
hour -
day
Примеры:
end | start | unit | timestamp_diff(end, start, unit) |
|---|---|---|---|
| 2026-07-04 00:01:00 UTC | 2026-07-04 00:00:00 UTC | "второй" | 60 л |
| 2026-07-04 00:00:00 UTC | 2026-07-05 00:00:00 UTC | "день" | -1L |
| 2026-07-04 00:00:59 UTC | 2026-07-04 00:00:00 UTC | "minute" | 0L |
TIMESTAMP_EXTRACT
Синтаксис:
timestamp_extract(timestamp: TIMESTAMP, part: STRING[, timezone: STRING]) -> INT64
Описание:
Extracts a specific part (eg year, month, day) from timestamp .
The part argument must be a string and one of the following:
-
microsecond -
millisecond -
second -
minute -
hour -
day -
dayofweek: Returns a value between 1 (Sunday) and 7 (Saturday). -
dayofyear -
week: Returns the week number of the year, starting at 1 for the first Sunday of the year. -
week([weekday]): Returns the week number of the year, starting on the specifiedweekday. -
month -
quarter -
year -
isoweek: Returns the ISO 8601 week number. -
isoyear: Returns the ISO 8601 week-numbering year.
If the timezone argument is provided, the extraction will be based on the given timezone's calendar. The extraction will respect daylight savings time.
If timezone is not provided, extraction will be based on UTC .
The timezone argument should be a string representation of a timezone from the timezone database, for example America/New_York . A custom time offset can also be used by specifying an offset from GMT .
Примеры:
timestamp | part | timezone | timestamp_extract(timestamp, part, timezone) |
|---|---|---|---|
| 2025-02-20 10:20:30 UTC | "год" | Не предоставлено | 2025 |
| 2025-02-20 10:20:30 UTC | "день" | Не предоставлено | 20 |
| 2025-12-31 23:59:59 UTC | "год" | "Asia/Tokyo" | 2026 |
Типы функций
| Имя | Описание |
TYPE | Возвращает тип значения в виде STRING . |
IS_TYPE | Возвращает true если значение соответствует указанному типу. |
ТИП
Синтаксис:
type(input: ANY) -> STRING
Описание:
Возвращает строковое представление input типа.
Если задано отсутствующее значение, возвращает NULL .
Примеры:
input | type(input) |
|---|---|
| НУЛЕВОЙ | "нулевой" |
| истинный | "булевый" |
| 1 | "int32" |
| -3 л | "int64" |
| 3.14 | "float64" |
| 2024-01-01T00:00:00Z UTC | "временная метка" |
| "фу" | "нить" |
| б"фу" | "байты" |
| [1, 2] | "множество" |
| {"а": 1} | "карта" |
path("c/d") | "ссылка" |
vector([1.0, 2.0]) | "вектор" |
| ОТСУТСТВУЮЩИЙ | НУЛЕВОЙ |
Примеры клиентов
Node.js
const result = await db.pipeline() .collection("books") .select(field("title").notEqual("1984").as("not1984")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("title").notEqual("1984").as("not1984")) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([Field("title").notEqual("1984").as("not1984")]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select(field("title").notEqual("1984").alias("not1984")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("title").notEqual("1984").alias("not1984")) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("title").not_equal("1984").as_("not1984")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(notEqual(field("title"), "1984").as("not1984")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.NotEqual(firestore.FieldOf("title"), "1984").As("not1984"), )). Execute(ctx)
IS_TYPE
Синтаксис:
is_type(input: ANY, type: STRING) -> BOOLEAN
Описание:
Возвращает true если input соответствуют указанному type , в противном случае false . Если input отсутствуют, возвращает NULL .
Поддерживаемые строковые type :
-
"null" -
"boolean" -
"int32" -
"int64" -
"float64" -
"decimal128" -
"number" -
"timestamp" -
"string" -
"bytes" -
"array" -
"map" -
"reference" -
"vector" -
"geo_point" -
"max_key" -
"min_key" -
"object_id" -
"regex" -
"bson_timestamp"
Примеры:
input | type | is_type(input, type) |
|---|---|---|
| НУЛЕВОЙ | "нулевой" | истинный |
| истинный | "булевый" | истинный |
| 3.14 | "float64" | истинный |
| "фу" | "нить" | истинный |
| б"фу" | "нить" | ЛОЖЬ |
| [1, 2] | "множество" | истинный |
| {"а": 1} | "карта" | истинный |
vector([1.0, 2.0]) | "вектор" | истинный |
| ОТСУТСТВУЮЩИЙ | "нить" | НУЛЕВОЙ |
| "бар" | "другой" | ОШИБКА |
Векторные функции
| Имя | Описание |
COSINE_DISTANCE | Returns the cosine distance between two vectors |
DOT_PRODUCT | Returns the dot product between two vectors |
EUCLIDEAN_DISTANCE | Returns the euclidean distance between two vectors |
MANHATTAN_DISTANCE | Returns the manhattan distance between two vectors |
VECTOR_LENGTH | Returns the number of elements in a vector |
COSINE_DISTANCE
Синтаксис:
cosine_distance(x: VECTOR, y: VECTOR) -> FLOAT64
Описание:
Returns the cosine distance between x and y .
Node.js
const sampleVector = [0.0, 1, 2, 3, 4, 5]; const result = await db.pipeline() .collection("books") .select( field("embedding").cosineDistance(sampleVector).as("cosineDistance") ) .execute();
Web
const sampleVector = [0.0, 1, 2, 3, 4, 5]; const result = await execute(db.pipeline() .collection("books") .select( field("embedding").cosineDistance(sampleVector).as("cosineDistance")));
Быстрый
let sampleVector = [0.0, 1, 2, 3, 4, 5] let result = try await db.pipeline() .collection("books") .select([ Field("embedding").cosineDistance(sampleVector).as("cosineDistance") ]) .execute()
Kotlin
val sampleVector = doubleArrayOf(0.0, 1.0, 2.0, 3.0, 4.0, 5.0) val result = db.pipeline() .collection("books") .select( field("embedding").cosineDistance(sampleVector).alias("cosineDistance") ) .execute()
Java
double[] sampleVector = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("embedding").cosineDistance(sampleVector).alias("cosineDistance") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field from google.cloud.firestore_v1.vector import Vector sample_vector = Vector([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) result = ( client.pipeline() .collection("books") .select( Field.of("embedding").cosine_distance(sample_vector).as_("cosineDistance") ) .execute() )
Java
double[] sampleVector = new double[] {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(cosineDistance(field("embedding"), sampleVector).as("cosineDistance")) .execute() .get();
Идти
sampleVector := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0} snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.CosineDistance(firestore.FieldOf("embedding"), sampleVector).As("cosineDistance"), )). Execute(ctx)
DOT_PRODUCT
Синтаксис:
dot_product(x: VECTOR, y: VECTOR) -> FLOAT64
Описание:
Returns the dot product of x and y .
Node.js
const sampleVector = [0.0, 1, 2, 3, 4, 5]; const result = await db.pipeline() .collection("books") .select( field("embedding").dotProduct(sampleVector).as("dotProduct") ) .execute();
Web
const sampleVector = [0.0, 1, 2, 3, 4, 5]; const result = await execute(db.pipeline() .collection("books") .select( field("embedding").dotProduct(sampleVector).as("dotProduct") ) );
Быстрый
let sampleVector = [0.0, 1, 2, 3, 4, 5] let result = try await db.pipeline() .collection("books") .select([ Field("embedding").dotProduct(sampleVector).as("dotProduct") ]) .execute()
Kotlin
val sampleVector = doubleArrayOf(0.0, 1.0, 2.0, 3.0, 4.0, 5.0) val result = db.pipeline() .collection("books") .select( field("embedding").dotProduct(sampleVector).alias("dotProduct") ) .execute()
Java
double[] sampleVector = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("embedding").dotProduct(sampleVector).alias("dotProduct") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field from google.cloud.firestore_v1.vector import Vector sample_vector = Vector([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) result = ( client.pipeline() .collection("books") .select(Field.of("embedding").dot_product(sample_vector).as_("dotProduct")) .execute() )
Java
double[] sampleVector = new double[] {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(dotProduct(field("embedding"), sampleVector).as("dotProduct")) .execute() .get();
Идти
sampleVector := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0} snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.DotProduct(firestore.FieldOf("embedding"), sampleVector).As("dotProduct"), )). Execute(ctx)
EUCLIDEAN_DISTANCE
Синтаксис:
euclidean_distance(x: VECTOR, y: VECTOR) -> FLOAT64
Описание:
Computes the euclidean distance between x and y .
Node.js
const sampleVector = [0.0, 1, 2, 3, 4, 5]; const result = await db.pipeline() .collection("books") .select( field("embedding").euclideanDistance(sampleVector).as("euclideanDistance") ) .execute();
Web
const sampleVector = [0.0, 1, 2, 3, 4, 5]; const result = await execute(db.pipeline() .collection("books") .select( field("embedding").euclideanDistance(sampleVector).as("euclideanDistance") ) );
Быстрый
let sampleVector = [0.0, 1, 2, 3, 4, 5] let result = try await db.pipeline() .collection("books") .select([ Field("embedding").euclideanDistance(sampleVector).as("euclideanDistance") ]) .execute()
Kotlin
val sampleVector = doubleArrayOf(0.0, 1.0, 2.0, 3.0, 4.0, 5.0) val result = db.pipeline() .collection("books") .select( field("embedding").euclideanDistance(sampleVector).alias("euclideanDistance") ) .execute()
Java
double[] sampleVector = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("embedding").euclideanDistance(sampleVector).alias("euclideanDistance") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field from google.cloud.firestore_v1.vector import Vector sample_vector = Vector([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) result = ( client.pipeline() .collection("books") .select( Field.of("embedding") .euclidean_distance(sample_vector) .as_("euclideanDistance") ) .execute() )
Java
double[] sampleVector = new double[] {0.0, 1.0, 2.0, 3.0, 4.0, 5.0}; Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(euclideanDistance(field("embedding"), sampleVector).as("euclideanDistance")) .execute() .get();
Идти
sampleVector := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0} snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.EuclideanDistance(firestore.FieldOf("embedding"), sampleVector).As("euclideanDistance"), )). Execute(ctx)
MANHATTAN_DISTANCE
Синтаксис:
manhattan_distance(x: VECTOR, y: VECTOR) -> FLOAT64
Описание:
Computes the manhattan distance between x and y .
VECTOR_LENGTH
Синтаксис:
vector_length(vector: VECTOR) -> INT64
Описание:
Returns the number of elements in a VECTOR .
Node.js
const result = await db.pipeline() .collection("books") .select( field("embedding").vectorLength().as("vectorLength") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("embedding").vectorLength().as("vectorLength") ) );
Быстрый
let result = try await db.pipeline() .collection("books") .select([ Field("embedding").vectorLength().as("vectorLength") ]) .execute()
Kotlin
val result = db.pipeline() .collection("books") .select( field("embedding").vectorLength().alias("vectorLength") ) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select( field("embedding").vectorLength().alias("vectorLength") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("books") .select(Field.of("embedding").vector_length().as_("vectorLength")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("books") .select(vectorLength(field("embedding")).as("vectorLength")) .execute() .get();
Идти
snapshot := client.Pipeline(). Collection("books"). Select(firestore.Fields( firestore.VectorLength(firestore.FieldOf("embedding")).As("vectorLength"), )). Execute(ctx)