Hàm số học

Hàm số học

Tất cả các hàm số học trong Cloud Firestore đều có các hành vi sau:

  • Trả về NULL nếu bất kỳ tham số đầu vào nào là NULL.
  • Cho kết quả là NaN nếu bất kỳ đối số nào là NaN.
  • Tạo lỗi nếu xảy ra tình trạng tràn số hoặc tràn dưới.

Cloud Firestore thực hiện mở rộng kiểu số dựa trên hệ phân cấp sau: INT32 < INT64 < FLOAT64 < DECIMAL128. Khi một hàm số học nhận nhiều đối số dạng số thuộc nhiều loại khác nhau (ví dụ: add(5.0D, 6L)), các loại hẹp hơn sẽ được chuyển đổi ngầm định thành loại rộng nhất có trong các toán hạng. Trong ví dụ trước, 6L được mở rộng thành 6.0D, dẫn đến biểu thức trả về loại FLOAT64.

Việc ép kiểu ngầm định từ INT64 -> FLOAT64 có thể làm giảm độ chính xác vì giá trị bị ép kiểu có thể mất đi các bit ít quan trọng nhất. Giá trị kết quả sẽ là phiên bản làm tròn của giá trị số nguyên ban đầu bằng cách sử dụng chế độ làm tròn đến số gần nhất theo IEEE 754.

Tên Mô tả
ABS Trả về giá trị tuyệt đối của number
ADD Trả về giá trị của x + y
SUBTRACT Trả về giá trị của x - y
MULTIPLY Trả về giá trị của x * y
DIVIDE Trả về giá trị của x / y
MOD Trả về số dư của phép chia x / y
CEIL Trả về giá trị trần của number
FLOOR Trả về giá trị làm tròn xuống của một number
ROUND Làm tròn number đến places chữ số thập phân
TRUNC Cắt bớt number thành places chữ số thập phân
POW Trả về giá trị của base^exponent
SQRT Trả về căn bậc hai của number
EXP Trả về số Euler được nâng lên luỹ thừa exponent
LN Trả về lôgarit tự nhiên của một number
LOG Trả về lôgarit của một number
LOG10 Trả về lôgarit của một number theo cơ số 10
RAND Trả về một số thực giả ngẫu nhiên

ABS

Cú pháp:

abs[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N

Nội dung mô tả:

Trả về giá trị tuyệt đối của một number.

  • Gây ra lỗi khi hàm làm tràn giá trị INT32 hoặc INT64.

Ví dụ:

số abs(number)
10 10
-10 10
10L 10L
-0 0,0
10.5 10.5
-10,5 10.5
-231 [error]
-263 [error]

THÊM

Cú pháp:

add[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

Nội dung mô tả:

Trả về giá trị của x + y.

Ví dụ:

x năm 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Add(firestore.FieldOf("soldBooks"), firestore.FieldOf("unsoldBooks")).As("totalBooks"),
	)).
	Execute(ctx)

SUBTRACT

Cú pháp:

subtract[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

Nội dung mô tả:

Trả về giá trị của x - y.

Ví dụ:

x năm 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"))
);
Swift
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();
Bắt đầu
storeCredit := 7
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Subtract(firestore.FieldOf("price"), storeCredit).As("totalCost"),
	)).
	Execute(ctx)

MULTIPLY

Cú pháp:

multiply[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

Nội dung mô tả:

Trả về giá trị của x * y.

Ví dụ:

x năm 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Multiply(firestore.FieldOf("price"), firestore.FieldOf("soldBooks")).As("revenue"),
	)).
	Execute(ctx)

DIVIDE

Cú pháp:

divide[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

Nội dung mô tả:

Trả về giá trị của x / y. Phép chia số nguyên bị cắt bớt.

Ví dụ:

x năm 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 -inf
0,0 0,0 NaN
+inf +inf NaN
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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Divide(firestore.FieldOf("ratings"), firestore.FieldOf("soldBooks")).As("reviewRate"),
	)).
	Execute(ctx)

Sửa đổi

Cú pháp:

mod[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](x: N, y: N) -> N

Nội dung mô tả:

Trả về phần còn lại của x / y.

  • Gửi error khi y bằng 0 đối với các loại số nguyên (INT64).
  • Trả về NaN khi y bằng 0 cho các kiểu số thực (FLOAT64).

Ví dụ:

x năm 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"))
);
Swift
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();
Bắt đầu
displayCapacity := 1000
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Mod(firestore.FieldOf("unsoldBooks"), displayCapacity).As("warehousedBooks"),
	)).
	Execute(ctx)

CEIL

Cú pháp:

ceil[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N

Nội dung mô tả:

Trả về giá trị số nguyên nhỏ nhất không nhỏ hơn number.

Ví dụ:

số ceil(number)
20 20
10 10
0 0
24L 24L
-0,4 -0
0,4 1.0
22,5 23
NaN NaN
+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")
  )
);
Swift
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();
Bắt đầu
booksPerShelf := 100
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Ceil(firestore.Divide(firestore.FieldOf("unsoldBooks"), booksPerShelf)).As("requiredShelves"),
	)).
	Execute(ctx)

FLOOR

Cú pháp:

floor[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N

Nội dung mô tả:

Trả về giá trị số nguyên lớn nhất không lớn hơn number.

Ví dụ:

số floor(number)
20 20
10 10
0 0
2147483648 2147483648
-0,4 -1
0,4 0,0
22,5 22
NaN NaN
+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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	AddFields(firestore.Selectables(
		firestore.Floor(firestore.Divide(firestore.FieldOf("wordCount"), firestore.FieldOf("pages"))).As("wordsPerPage"),
	)).
	Execute(ctx)

ROUND

Cú pháp:

round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N
round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N, places: INT64) -> N

Nội dung mô tả:

Làm tròn places chữ số của một number. Làm tròn các chữ số ở bên phải dấu thập phân nếu places là số dương và ở bên trái dấu thập phân nếu là số âm.

  • Nếu chỉ cung cấp number, thì hàm sẽ làm tròn đến giá trị nguyên gần nhất.
  • Làm tròn ra xa số 0 trong các trường hợp nửa chừng.
  • error sẽ được gửi nếu việc làm tròn bằng giá trị places âm dẫn đến tràn số.

Ví dụ:

số địa điểm round(number, places)
15,5 0 16.0
-15,5 0 -16
15 1 15
15 0 15
15 -1 20
15 -2 0
15.48924 1 15,5
231-1 -1 [error]
263-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"))
  );
Swift
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();
Bắt đầu
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

Cú pháp:

trunc[N <: Number](number: N) -> N
trunc[N <: Number](number:  N, places: INT64) -> N

Nội dung mô tả:

Cắt bớt một number thành một số lượng places chữ số thập phân được chỉ định. Cắt bớt các chữ số ở bên phải dấu thập phân nếu places là số dương và ở bên trái dấu thập phân nếu là số âm.

  • Nếu chỉ cung cấp number, hàm sẽ cắt bớt thành giá trị nguyên gần nhất về phía 0.
  • Hệ thống sẽ gửi một error nếu việc cắt bớt dẫn đến tràn số.

Ví dụ:

số địa điểm trunc(number, places)
15,5 0 15
-15,5 0 -15
15 1 15
15 0 15
15 -1 10
15 -2 0
15.48924 1 15,4
-15,48924 2 -15,48

POW

Cú pháp:

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

Nội dung mô tả:

Trả về giá trị base được nâng lên luỹ thừa exponent.

  • Gửi lỗi nếu base <= 0 và exponent là số âm.

  • Đối với mọi exponent (bao gồm cả NaN), pow(1, exponent) là 1.

  • Đối với mọi base (bao gồm cả NaN), pow(base, 0) là 1.

Ví dụ:

chân đế số mũ pow(base, exponent)
2 3 8.0
2 -3 0,125
+inf 0 1.0
1 +inf 1.0
NaN 0 1.0
1 NaN 1.0
NaN Numeric NaN
Numeric NaN NaN
-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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

sqrt[N <: FLOAT64 | DECIMAL128](number: N) -> N

Nội dung mô tả:

Trả về căn bậc hai của một number.

  • Gửi error nếu number là số âm.

Ví dụ:

số 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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

exp(exponent: FLOAT64) -> FLOAT64

Nội dung mô tả:

Trả về giá trị của số Euler được nâng lên luỹ thừa exponent, còn được gọi là hàm mũ tự nhiên.

Ví dụ:

số mũ exp(exponent)
0,0 1.0
10 e^10 (FLOAT64)
NaN NaN
+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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Exp(firestore.FieldOf("rating")).As("expRating"),
	)).
	Execute(ctx)

LN

Cú pháp:

ln(number: FLOAT64) -> FLOAT64

Nội dung mô tả:

Trả về lôgarit tự nhiên của number. Hàm này tương đương với log(number).

Ví dụ:

số ln(number)
1 0,0
2L 0,693...
1.0 0,0
e (FLOAT64) 1.0
NaN NaN
-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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Ln(firestore.FieldOf("rating")).As("lnRating"),
	)).
	Execute(ctx)

GHI NHẬT KÝ

Cú pháp:

log(number: FLOAT64, base: FLOAT64) -> FLOAT64
log(number: FLOAT64) -> FLOAT64

Nội dung mô tả:

Trả về lôgarit của number theo base.

  • Nếu chỉ cung cấp number, thì hàm sẽ trả về lôgarit của number theo base (đồng nghĩa với ln(number)).

Ví dụ:

số chân đế log(number, base)
100 10 2.0
NaN Numeric NaN
Numeric NaN NaN
-inf Numeric NaN
Numeric. +inf NaN
number <= 0 Numeric [error]
Numeric base <= 0 [error]
Numeric 1.0 [error]

LOG10

Cú pháp:

log10(x: FLOAT64) -> FLOAT64

Nội dung mô tả:

Trả về lôgarit của một number theo cơ số 10.

Ví dụ:

số log10(number)
100 2.0
NaN NaN
-inf NaN
+inf +inf
x <= 0 [error]

RAND

Cú pháp:

rand() -> FLOAT64

Nội dung mô tả:

Trả về một số thực dấu phẩy động giả ngẫu nhiên, được chọn đồng đều giữa 0.0 (bao gồm) và 1.0 (không bao gồm).