Арифметические функции

Арифметические функции

Все арифметические функции в 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 после запятой.
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]

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()
)

ВЫЧИТАТЬ

Синтаксис:

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]

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()
)

УМНОЖИТЬ

Синтаксис:

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

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()
)

РАЗДЕЛЯТЬ

Синтаксис:

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

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()
)

МОД

Синтаксис:

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]

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()
)

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

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()
)

ПОЛ

Синтаксис:

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

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()
)

КРУГЛЫЙ

Синтаксис:

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]

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()
)

ПАВ

Синтаксис:

pow(base: FLOAT64, exponent: FLOAT64) -> FLOAT64

Описание:

Возвращает base возведенное в степень exponent .

  • Вызывает ошибку, если base <= 0 и exponent отрицательный.

  • Для любого exponent pow(1, exponent) равно 1.

  • Для любой base pow(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]

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()
)

Квадратный корень

Синтаксис:

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]

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()
)

ЭКСП

Синтаксис:

exp(exponent: FLOAT64) -> FLOAT64

Описание:

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

Примеры:

показатель степени exp(exponent)
0.0 1.0
10 e^10 ( FLOAT64 )
+inf +inf
-inf 0

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()
)

ЛН

Синтаксис:

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]

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()
)

БРЕВНО

Синтаксис:

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 (исключительно).