Tất cả các hàm

Tổng hợp

Bạn có thể sử dụng tất cả hàm tổng hợp làm biểu thức cấp cao nhất trong giai đoạn aggregate(...).

Tên Mô tả
COUNT Trả về số lượng tài liệu.
COUNT_IF Trả về số lượng tài liệu mà một biểu thức cho kết quả là TRUE
COUNT_DISTINCT Trả về số lượng giá trị riêng biệt, không phải NULL
SUM Trả về tổng của tất cả giá trị NUMERIC
AVERAGE Trả về giá trị trung bình của tất cả các giá trị NUMERIC
MINIMUM Trả về giá trị không phải NULL nhỏ nhất
MAXIMUM Trả về giá trị không phải NULL lớn nhất
FIRST Trả về giá trị expression cho tài liệu đầu tiên.
LAST Trả về giá trị expression cho tài liệu gần đây nhất.
ARRAY_AGG Trả về một mảng gồm tất cả giá trị đầu vào.
ARRAY_AGG_DISTINCT Trả về một mảng gồm tất cả các giá trị đầu vào riêng biệt.

COUNT

Cú pháp:

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

Nội dung mô tả:

Trả về số lượng tài liệu từ giai đoạn trước, trong đó expression đánh giá thành bất kỳ giá trị nào không phải NULL. Nếu không có expression nào được cung cấp, thì hàm này sẽ trả về tổng số tài liệu từ giai đoạn trước.

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

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

Web

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

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

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

Kotlin

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

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

Java

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

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

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

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

// Number of books with nonnull `ratings` field
Pipeline.Snapshot countField =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(count("ratings").as("count"))
        .execute()
        .get();
Bắt đầu
// 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

Cú pháp:

count_if(expression: BOOLEAN) -> INT64

Nội dung mô tả:

Trả về số lượng tài liệu từ giai đoạn trước, trong đó expression được đánh giá là TRUE.

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

Web

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

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("rating").greater_than(4).count_if().as_("filteredCount"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(countIf(field("rating").greaterThan(4)).as("filteredCount"))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.CountIf(firestore.FieldOf("rating").GreaterThan(4)).As("filteredCount"),
	)).
	Execute(ctx)

COUNT_DISTINCT

Cú pháp:

count_distinct(expression: ANY) -> INT64

Nội dung mô tả:

Trả về số lượng giá trị riêng biệt không phải NULL, không phải ABSENT của expression.

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

Web

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

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("author").count_distinct().as_("unique_authors"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(countDistinct("author").as("unique_authors"))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.CountDistinct("author").As("unique_authors"),
	)).
	Execute(ctx)

SUM

Cú pháp:

sum(expression: ANY) -> NUMBER

Nội dung mô tả:

Trả về tổng của tất cả các giá trị số, bỏ qua các giá trị không phải số. Trả về NaN nếu có giá trị là NaN.

Kết quả sẽ có cùng loại với loại dữ liệu đầu vào rộng nhất, ngoại trừ những trường hợp sau:

  • INTEGER sẽ được chuyển đổi thành DOUBLE nếu không thể biểu thị dưới dạng INTEGER.
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").sum().as("totalPopulation"))
  .execute();

Web

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

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("cities")
    .aggregate(Field.of("population").sum().as_("totalPopulation"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("cities")
        .aggregate(sum("population").as("totalPopulation"))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	Collection("cities").
	Aggregate(firestore.Accumulators(
		firestore.Sum("population").As("totalPopulation"),
	)).
	Execute(ctx)

AVERAGE

Cú pháp:

average(expression: ANY) -> FLOAT64

Nội dung mô tả:

Trả về giá trị trung bình cho tất cả các giá trị dạng số, bỏ qua các giá trị không phải dạng số. Đánh giá thành NaN nếu có bất kỳ giá trị nào là NaN hoặc NULL nếu không có giá trị số nào được tổng hợp.

Kết quả sẽ có cùng loại với loại đầu vào, ngoại trừ các trường hợp sau:

  • INTEGER sẽ được chuyển đổi thành DOUBLE nếu không thể biểu thị dưới dạng INTEGER.
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").average().as("averagePopulation"))
  .execute();

Web

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

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("cities")
    .aggregate(Field.of("population").average().as_("averagePopulation"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("cities")
        .aggregate(average("population").as("averagePopulation"))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	Collection("cities").
	Aggregate(firestore.Accumulators(
		firestore.Average("population").As("averagePopulation"),
	)).
	Execute(ctx)

TỐI THIỂU

Cú pháp:

minimum(expression: ANY) -> ANY

Nội dung mô tả:

Trả về giá trị nhỏ nhất không phải NULL, không phải giá trị vắng mặt của expression khi được đánh giá trên mỗi tài liệu.

Nếu không có giá trị nào khác NULL và không có giá trị nào bị thiếu, thì hàm sẽ trả về NULL. Điều này bao gồm cả trường hợp không có tài liệu nào được xem xét.

Nếu có nhiều giá trị tương đương tối thiểu, thì hàm có thể trả về bất kỳ giá trị nào trong số đó. Thứ tự loại giá trị tuân theo thứ tự được ghi nhận.

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

Web

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

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("price").minimum().as_("minimumPrice"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(minimum("price").as("minimumPrice"))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.Minimum("price").As("minimumPrice"),
	)).
	Execute(ctx)

TỐI ĐA

Cú pháp:

maximum(expression: ANY) -> ANY

Nội dung mô tả:

Trả về giá trị tối đa không phải NULL, không phải giá trị vắng mặt của expression khi được đánh giá trên mỗi tài liệu.

Nếu không có giá trị nào khác NULL và không có giá trị nào bị thiếu, thì hàm sẽ trả về NULL. Điều này bao gồm cả trường hợp không có tài liệu nào được xem xét.

Nếu có nhiều giá trị tương đương tối đa, thì hàm có thể trả về bất kỳ giá trị nào trong số đó. Thứ tự loại giá trị tuân theo thứ tự được ghi nhận.

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

Web

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

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .aggregate(Field.of("price").maximum().as_("maximumPrice"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .aggregate(maximum("price").as("maximumPrice"))
        .execute()
        .get();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Aggregate(firestore.Accumulators(
		firestore.Maximum("price").As("maximumPrice"),
	)).
	Execute(ctx)

ĐẦU TIÊN

Cú pháp:

first(expression: ANY) -> ANY

Nội dung mô tả:

Trả về giá trị của expression cho tài liệu được trả về đầu tiên.

CUỐI CÙNG

Cú pháp:

last(expression: ANY) -> ANY

Nội dung mô tả:

Trả về giá trị của expression cho tài liệu được trả về gần đây nhất.

ARRAY_AGG

Cú pháp:

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

Nội dung mô tả:

Trả về một mảng chứa tất cả giá trị của expression khi được đánh giá trên mỗi tài liệu.

Nếu biểu thức phân giải thành một giá trị vắng mặt, thì biểu thức đó sẽ được chuyển đổi thành NULL.

Thứ tự của các phần tử trong mảng đầu ra không ổn định và không nên dựa vào đó.

ARRAY_AGG_DISTINCT

Cú pháp:

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

Nội dung mô tả:

Trả về một mảng chứa tất cả các giá trị riêng biệt của expression khi được đánh giá trên mỗi tài liệu.

Nếu biểu thức phân giải thành một giá trị vắng mặt, thì biểu thức đó sẽ được chuyển đổi thành NULL.

Thứ tự của các phần tử trong mảng đầu ra không ổn định và không nên dựa vào đó.

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

Hàm mảng

Tên Mô tả
ARRAY Trả về một ARRAY chứa một phần tử cho mỗi đối số đầu vào
ARRAY_CONCAT Nối nhiều mảng thành một mảng ARRAY duy nhất
ARRAY_CONTAINS Trả về TRUE nếu ARRAY đã cho chứa một giá trị cụ thể
ARRAY_CONTAINS_ALL Trả về TRUE nếu tất cả giá trị đều có trong ARRAY
ARRAY_CONTAINS_ANY Trả về TRUE nếu có bất kỳ giá trị nào trong ARRAY
ARRAY_FILTER Lọc ra các phần tử khỏi một ARRAY không đáp ứng một vị từ
ARRAY_FIRST Trả về phần tử đầu tiên trong ARRAY
ARRAY_FIRST_N Trả về n phần tử đầu tiên trong ARRAY
ARRAY_GET Trả về phần tử tại một chỉ mục nhất định trong ARRAY
ARRAY_INDEX_OF Trả về chỉ mục của lần xuất hiện đầu tiên của một giá trị trong ARRAY
ARRAY_INDEX_OF_ALL Trả về tất cả chỉ mục của một giá trị trong ARRAY
ARRAY_LENGTH Trả về số lượng phần tử trong ARRAY
ARRAY_LAST Trả về phần tử cuối cùng trong ARRAY
ARRAY_LAST_N Trả về n phần tử cuối cùng trong ARRAY
ARRAY_REVERSE Đảo ngược thứ tự của các phần tử trong ARRAY
ARRAY_SLICE Trả về một lát cắt của ARRAY
ARRAY_TRANSFORM Biến đổi các phần tử trong ARRAY bằng cách áp dụng biểu thức cho từng phần tử
MAXIMUM Trả về giá trị lớn nhất trong ARRAY
MAXIMUM_N Trả về n giá trị lớn nhất trong ARRAY
MINIMUM Trả về giá trị nhỏ nhất trong ARRAY
MINIMUM_N Trả về n giá trị nhỏ nhất trong ARRAY
SUM Trả về tổng của tất cả giá trị NUMERIC trong một ARRAY.
JOIN Tạo một phép nối các phần tử trong ARRAY dưới dạng giá trị STRING.

ARRAY

Cú pháp:

array(values: ANY...) -> ARRAY

Nội dung mô tả:

Tạo một mảng từ các phần tử đã cho.

  • Nếu một đối số không tồn tại, thì đối số đó sẽ được thay thế bằng NULL trong mảng kết quả.

Ví dụ:

giá trị array(values)
() []
(1, 2, 3) [1, 2, 3]
("a", 1, true) ["a", 1, true]
(1, null) [1, null]
(1, [2, 3]) [1, [2, 3]]

ARRAY_CONCAT

Cú pháp:

array_concat(arrays: ARRAY...) -> ARRAY

Nội dung mô tả:

Nối hai hoặc nhiều mảng thành một ARRAY duy nhất.

Ví dụ:

mảng 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();
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ArrayConcat(firestore.FieldOf("genre"), firestore.FieldOf("subGenre")).As("allGenres"),
	)).
	Execute(ctx)

ARRAY_CONTAINS

Cú pháp:

array_contains(array: ARRAY, value: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu tìm thấy value trong array, nếu không thì trả về FALSE.

Ví dụ:

array value array_contains(array, value)
[1, 2, 3] 2 đúng
[[1, 2], [3]] [1, 2] đúng
[1, null] null đúng
"abc" BẤT KỲ error
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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ArrayContains(firestore.FieldOf("genre"), "mystery").As("isMystery"),
	)).
	Execute(ctx)

ARRAY_CONTAINS_ALL

Cú pháp:

array_contains_all(array: ARRAY, search_values: ARRAY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu tìm thấy tất cả search_values trong array, nếu không thì trả về FALSE.

Ví dụ:

array giá_trị_tìm_kiếm array_contains_all(array, search_values)
[1, 2, 3] [1, 2] đúng
[1, 2, 3] [1, 4] false
[1, null] [không] đúng
[NaN] [NaN] đúng
[] [] đúng
[1, 2, 3] [] đúng
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ArrayContainsAll(firestore.FieldOf("genre"), []string{"fantasy", "adventure"}).As("isFantasyAdventure"),
	)).
	Execute(ctx)

ARRAY_CONTAINS_ANY

Cú pháp:

array_contains_any(array: ARRAY, search_values: ARRAY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu tìm thấy bất kỳ search_values nào trong array, nếu không thì trả về FALSE.

Ví dụ:

array giá_trị_tìm_kiếm array_contains_any(array, search_values)
[1, 2, 3] [4, 1] đúng
[1, 2, 3] [4, 5] false
[1, 2, null] [không] đúng
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ArrayContainsAny(firestore.FieldOf("genre"), []string{"fantasy", "nonfiction"}).As("isMysteryOrFantasy"),
	)).
	Execute(ctx)

ARRAY_FILTER

Cú pháp:

array_filter(array: ARRAY, predicate: (ANY) -> BOOLEAN) -> ARRAY

Nội dung mô tả:

Lọc array bằng biểu thức predicate, trả về một mảng mới chỉ có các phần tử thoả mãn vị từ.

  • Đối với mỗi phần tử trong array, predicate sẽ được đánh giá. Nếu hàm trả về true, phần tử sẽ được đưa vào kết quả; nếu không (nếu hàm trả về false hoặc null), phần tử sẽ bị bỏ qua.
  • Nếu predicate đánh giá thành một giá trị không phải boolean hoặc không rỗng, thì hàm sẽ trả về lỗi.

Ví dụ:

array vị ngữ 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

Cú pháp:

array_get(array: ARRAY, index: INT64) -> ANY

Nội dung mô tả:

Trả về phần tử tại index dựa trên 0 trong array.

  • Nếu index là số âm, thì các phần tử sẽ được truy cập từ cuối mảng, trong đó -1 là phần tử cuối cùng.
  • Nếu array không thuộc loại ARRAY và không phải là null, thì hàm sẽ trả về lỗi.
  • Nếu index nằm ngoài giới hạn, hàm sẽ trả về một giá trị vắng mặt.
  • Nếu index không thuộc loại INT64, hàm sẽ trả về lỗi.

Ví dụ:

array index array_get(array, index)
[1, 2, 3] 0 1
[1, 2, 3] -1 3
[1, 2, 3] 3 vắng mặt
[1, 2, 3] -4 vắng mặt
"abc" 0 error
null 0 null
Array "a" error
Array 2.0 error

ARRAY_LENGTH

Cú pháp:

array_length(array: ARRAY) -> INT64

Nội dung mô tả:

Trả về số lượng phần tử trong array.

Ví dụ:

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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ArrayLength(firestore.FieldOf("genre")).As("genreCount"),
	)).
	Execute(ctx)

ARRAY_REVERSE

Cú pháp:

array_reverse(array: ARRAY) -> ARRAY

Nội dung mô tả:

Đảo ngược array đã cho.

Ví dụ:

array array_reverse(array)
[1, 2, 3] [3, 2, 1]
["a", "b"] ["b", "a"]
[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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ArrayReverse(firestore.FieldOf("genre")).As("reversedGenres"),
	)).
	Execute(ctx)

ARRAY_FIRST

Cú pháp:

array_first(array: ARRAY) -> ANY

Nội dung mô tả:

Trả về phần tử đầu tiên trong array. Điều này tương đương với array_get(array, 0).

  • Nếu array trống, hàm sẽ trả về một giá trị vắng mặt.

Ví dụ:

array array_first(array)
[1, 2, 3] 1
[] vắng mặt

ARRAY_FIRST_N

Cú pháp:

array_first_n(array: ARRAY, n: INT64) -> ARRAY

Nội dung mô tả:

Trả về n phần tử đầu tiên của array. Điều này tương đương với array_slice(array, 0, n).

  • Nếu n là số âm, hàm sẽ trả về lỗi.

Ví dụ:

array 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

Cú pháp:

array_index_of(array: ARRAY, value: ANY) -> INT64

Nội dung mô tả:

Trả về chỉ mục dựa trên 0 của lần xuất hiện đầu tiên của value trong array. Trả về -1 nếu không tìm thấy value.

Ví dụ:

array value array_index_of(array, value)
[1, 2, 3, 2] 2 1
[1, 2, 3] 4 -1
[1, null, 3] null 1

ARRAY_INDEX_OF_ALL

Cú pháp:

array_index_of_all(array: ARRAY, value: ANY) -> ARRAY<INT64>

Nội dung mô tả:

Trả về một mảng chứa các chỉ mục dựa trên 0 của tất cả các lần xuất hiện của value trong array. Trả về [] nếu không tìm thấy value.

Ví dụ:

array value array_index_of_all(array, value)
[1, 2, 3, 2] 2 [1, 3]
[1, 2, 3] 4 []
[1, null, 3, null] null [1, 3]

ARRAY_LAST

Cú pháp:

array_last(array: ARRAY) -> ANY

Nội dung mô tả:

Trả về phần tử cuối cùng trong array. Điều này tương đương với array_get(array, -1).

  • Nếu array trống, hàm sẽ trả về một giá trị vắng mặt.

Ví dụ:

array array_last(array)
[1, 2, 3] 3
[] vắng mặt

ARRAY_LAST_N

Cú pháp:

array_last_n(array: ARRAY, n: INT64) -> ARRAY

Nội dung mô tả:

Trả về n phần tử cuối cùng của array.

  • Nếu n là số âm, hàm sẽ trả về lỗi.

Ví dụ:

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

Cú pháp:

array_slice(array: ARRAY, offset: INT64, length: INT64) -> ARRAY

Nội dung mô tả:

Trả về một tập hợp con của array bắt đầu từ chỉ mục dựa trên 0 offset và bao gồm các phần tử length.

  • Nếu offset là số âm, thì giá trị này cho biết vị trí bắt đầu từ cuối mảng, trong đó -1 là phần tử cuối cùng.
  • Nếu length lớn hơn số phần tử còn lại trong mảng sau offset, thì kết quả sẽ kéo dài đến cuối mảng.
  • length phải là số không âm, nếu không sẽ trả về lỗi.

Ví dụ:

array độ lệch chiều dài 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

Cú pháp:

array_transform(array: ARRAY, expression: (ANY) -> ANY) -> ARRAY
array_transform(array: ARRAY, expression: (ANY, INT64) -> ANY) -> ARRAY

Nội dung mô tả:

Biến đổi array bằng cách áp dụng expression cho từng phần tử, trả về một mảng mới có các phần tử đã biến đổi. Mảng đầu ra sẽ luôn có cùng kích thước với mảng đầu vào.

  • expression có thể là hàm một ngôi element -> result hoặc hàm nhị phân (element, index) -> result.
  • Nếu expression là hàm một ngôi, thì hàm này sẽ được gọi với mỗi phần tử của array.
  • Nếu expression là nhị phân, thì hàm này sẽ được gọi với mỗi phần tử của array và chỉ mục tương ứng dựa trên 0.

Ví dụ:

array biểu thức 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 []

TỐI ĐA

Cú pháp:

maximum(array: ARRAY) -> ANY

Nội dung mô tả:

Trả về giá trị lớn nhất trong array.

  • Giá trị NULL bị bỏ qua trong quá trình so sánh.
  • Nếu array trống hoặc chỉ chứa các giá trị NULL, thì hàm sẽ trả về NULL.

Ví dụ:

array maximum(array)
[1, 5, 2] 5
[1, null, 5] 5
["a", "c", "b"] "c"
[null, null] null
[] null

MAXIMUM_N

Cú pháp:

maximum_n(array: ARRAY, n: INT64) -> ARRAY

Nội dung mô tả:

Trả về một mảng gồm n giá trị lớn nhất trong array theo thứ tự giảm dần.

  • Giá trị NULL sẽ bị bỏ qua.
  • Nếu n là số âm, hàm sẽ trả về lỗi.

Ví dụ:

array n maximum_n(array, n)
[1, 5, 2, 4, 3] 3 [5, 4, 3]
[1, null, 5] 3 [5, 1]

TỐI THIỂU

Cú pháp:

minimum(array: ARRAY) -> ANY

Nội dung mô tả:

Trả về giá trị nhỏ nhất trong array.

  • Giá trị NULL bị bỏ qua trong quá trình so sánh.
  • Nếu array trống hoặc chỉ chứa các giá trị NULL, thì hàm sẽ trả về NULL.

Ví dụ:

array minimum(array)
[1, 5, 2] 1
[5, null, 1] 1
["a", "c", "b"] "a"
[null, null] null
[] null

MINIMUM_N

Cú pháp:

minimum_n(array: ARRAY, n: INT64) -> ARRAY

Nội dung mô tả:

Trả về một mảng gồm n giá trị nhỏ nhất trong array theo thứ tự tăng dần.

  • Giá trị NULL sẽ bị bỏ qua.
  • Nếu n là số âm, hàm sẽ trả về lỗi.

Ví dụ:

array n minimum_n(array, n)
[1, 5, 2, 4, 3] 3 [1, 2, 3]
[5, null, 1] 3 [1, 5]

SUM

Cú pháp:

sum(array: ARRAY) -> INT64 | FLOAT64

Nội dung mô tả:

Trả về tổng của tất cả giá trị NUMERIC trong một ARRAY.

  • Các giá trị không phải dạng số trong mảng sẽ bị bỏ qua.
  • Nếu bất kỳ giá trị số nào trong mảng là NaN, thì hàm sẽ trả về NaN.
  • Kiểu dữ liệu trả về được xác định bằng kiểu số rộng nhất trong mảng: INT64 < FLOAT64.
  • Nếu xảy ra lỗi tràn số nguyên 64 bit trước khi tính tổng bất kỳ giá trị dấu phẩy động nào, thì hệ thống sẽ trả về lỗi. Nếu các giá trị dấu phẩy động được cộng lại, thì kết quả tràn số sẽ là +/- vô cực.
  • Nếu mảng không chứa giá trị số nào, thì hàm sẽ trả về NULL.

Ví dụ:

array sum(array)
[1, 2, 3] 6L
[1L, 2L, 3L] 6L
[2000000000, 2000000000] 4000000000L
[10, 20,5] 30,5
[1, "a", 2] 3L
[INT64.MAX_VALUE, 1] error
[INT64.MAX_VALUE, 1, -1.0] error
[INT64.MAX_VALUE, 1.0] 9.223372036854776e+18

THAM GIA

Cú pháp:

join[T <: STRING | BYTES](array: ARRAY<T>, delimiter: T) -> STRING
join[T <: STRING | BYTES](array: ARRAY<T>, delimiter: T, null_text: T) -> STRING

Nội dung mô tả:

Trả về một phép nối các phần tử trong array dưới dạng STRING. array có thể thuộc kiểu dữ liệu STRING hoặc BYTES.

  • Tất cả các phần tử trong array, delimiter và null_text phải cùng loại; tất cả phải là STRING hoặc tất cả phải là BYTES.
  • Nếu bạn cung cấp null_text, thì mọi giá trị NULL trong array sẽ được thay thế bằng null_text.
  • Nếu bạn không cung cấp null_text, thì các giá trị NULL trong array sẽ bị bỏ qua khỏi kết quả.

Ví dụ:

Khi không cung cấp null_text:

array dấu phân tách join(array, delimiter)
"a", "b", "c" "," "a,b,c"
["a", null, "c"] "," "a,c"
[b'a', b'b', b'c'] b',' b'a,b,c'
["a", b'c'] "," error
["a", "c"] b',' error
[b'a', b'c'] "," error

Khi null_text được cung cấp:

array dấu phân tách null_text join(array, delimiter, null_text)
["a", null, "c"] "," "MISSING" "a,MISSING,c"
[b'a', null, b'c'] b',' b'NULL' b'a,NULL,c'
[null, "b", null] "," "MISSING" "MISSING,b,MISSING"
[b'a', null, null] b',' b'NULL' b'a,NULL,NULL'
["a", null] "," b'N' error
[b'a', null] b',' "N" error

Hàm so sánh

Tên Mô tả
EQUAL So sánh bằng
GREATER_THAN Lớn hơn so với kết quả so sánh
GREATER_THAN_OR_EQUAL Phép so sánh lớn hơn hoặc bằng
LESS_THAN Phép so sánh nhỏ hơn
LESS_THAN_OR_EQUAL Phép so sánh nhỏ hơn hoặc bằng
NOT_EQUAL Phép so sánh không bằng
CMP So sánh chung

EQUAL

Cú pháp:

equal(x: ANY, y: ANY) -> BOOLEAN

Ví dụ:

x y equal(x, y)
1L 1L TRUE
1.0 1L TRUE
-1 1L FALSE
NaN (Không phải số) NaN (Không phải số) TRUE
NULL NULL TRUE
NULL ABSENT FALSE

Nội dung mô tả:

Trả về TRUE nếu x và y bằng nhau, nếu không thì trả về 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Equal(firestore.FieldOf("rating"), 5).As("hasPerfectRating"),
	)).
	Execute(ctx)

GREATER_THAN

Cú pháp:

greater_than(x: ANY, y: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu x lớn hơn y, nếu không thì trả về FALSE.

Nếu không thể so sánh x và y, hàm sẽ trả về FALSE.

Ví dụ:

x y greater_than(x, y)
1L 0,0 TRUE
1L 1L FALSE
1L 2L FALSE
"foo" 0L FALSE
0L "foo" FALSE
NaN (Không phải số) 0L FALSE
0L NaN (Không phải số) 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.GreaterThan(firestore.FieldOf("rating"), 4).As("hasHighRating"),
	)).
	Execute(ctx)

GREATER_THAN_OR_EQUAL

Cú pháp:

greater_than_or_equal(x: ANY, y: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu x lớn hơn hoặc bằng y, nếu không thì trả về FALSE.

Nếu không thể so sánh x và y, hàm sẽ trả về FALSE.

Ví dụ:

x y greater_than_or_equal(x, y)
1L 0,0 TRUE
1L 1L TRUE
1L 2L FALSE
"foo" 0L FALSE
0L "foo" FALSE
NaN (Không phải số) 0L FALSE
0L NaN (Không phải số) 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.GreaterThanOrEqual(firestore.FieldOf("published"), 1900).As("publishedIn20thCentury"),
	)).
	Execute(ctx)

LESS_THAN

Cú pháp:

less_than(x: ANY, y: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu x nhỏ hơn y, nếu không thì trả về FALSE.

Nếu không thể so sánh x và y, hàm sẽ trả về FALSE.

Ví dụ:

x y less_than(x, y)
1L 0,0 FALSE
1L 1L FALSE
1L 2L TRUE
"foo" 0L FALSE
0L "foo" FALSE
NaN (Không phải số) 0L FALSE
0L NaN (Không phải số) 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.LessThan(firestore.FieldOf("published"), 1923).As("isPublicDomainProbably"),
	)).
	Execute(ctx)

LESS_THAN_OR_EQUAL

Cú pháp:

less_than_or_equal(x: ANY, y: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu x nhỏ hơn hoặc bằng y, nếu không thì trả về FALSE.

Nếu không thể so sánh x và y, hàm sẽ trả về FALSE.

Ví dụ:

x y less_than(x, y)
1L 0,0 FALSE
1L 1L TRUE
1L 2L TRUE
"foo" 0L FALSE
0L "foo" FALSE
NaN (Không phải số) 0L FALSE
0L NaN (Không phải số) 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.LessThanOrEqual(firestore.FieldOf("rating"), 2).As("hasBadRating"),
	)).
	Execute(ctx)

NOT_EQUAL

Cú pháp:

not_equal(x: ANY, y: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu x không bằng y, nếu không thì trả về FALSE.

Ví dụ:

x y not_equal(x, y)
1L 1L FALSE
1.0 1L FALSE
-1 1L TRUE
NaN (Không phải số) 0L TRUE
NaN (Không phải số) NaN (Không phải số) 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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.NotEqual(firestore.FieldOf("title"), "1984").As("not1984"),
	)).
	Execute(ctx)

LHT

Cú pháp:

cmp(x: ANY, y: ANY) -> Int64

Nội dung mô tả:

So sánh x và y, trả về:

  • 1L nếu x lớn hơn y.
  • -1L nếu x nhỏ hơn y.
  • Nếu không thì là 0L.

Không giống như các hàm so sánh khác, hàm cmp(...) hoạt động trên nhiều loại, theo cùng thứ tự được sử dụng trong giai đoạn sort(...). Hãy xem phần thứ tự loại giá trị để biết cách sắp xếp giá trị theo loại.

Ví dụ:

x y cmp(x, y)
1L 1L 0L
1.0 1L 0L
-1 1L -1L
42,5D "foo" -1L
NULL NULL 0L
NULL ABSENT 0L

Các hàm gỡ lỗi

Tên Mô tả
EXISTS Trả về TRUE nếu giá trị không phải là giá trị vắng mặt
IS_ABSENT Trả về TRUE nếu giá trị là giá trị vắng mặt
IF_ABSENT Thay thế giá trị bằng một biểu thức nếu giá trị đó không có
IS_ERROR Bắt và kiểm tra xem biểu thức cơ bản có gửi lỗi hay không
IF_ERROR Thay thế giá trị bằng một biểu thức nếu giá trị đó gây ra lỗi
ERROR Chấm dứt việc đánh giá và trả về lỗi kèm theo thông báo được chỉ định

EXISTS

Cú pháp:

exists(value: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value không phải là giá trị vắng mặt.

Ví dụ:

value exists(value)
0L TRUE
"foo" TRUE
NULL TRUE
ABSENT FALSE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").exists().as("hasRating"))
  .execute();

Web

Ví dụ:

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").exists().as("hasRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").exists().as("hasRating")])
  .execute()

Kotlin

Ví dụ:

val result = db.pipeline()
    .collection("books")
    .select(field("rating").exists().alias("hasRating"))
    .execute()

Java

Ví dụ:

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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.FieldExists(firestore.FieldOf("rating")).As("hasRating"),
	)).
	Execute(ctx)

IS_ABSENT

Cú pháp:

is_absent(value: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value là giá trị vắng mặt, nếu không thì trả về FALSE. Giá trị vắng mặt là những giá trị bị thiếu trong dữ liệu đầu vào, chẳng hạn như trường tài liệu bị thiếu.

Ví dụ:

value is_absent(value)
0L FALSE
"foo" FALSE
NULL FALSE
ABSENT TRUE

IF_ABSENT

Cú pháp:

if_absent(value: ANY, replacement: ANY) -> ANY

Nội dung mô tả:

Nếu value là một giá trị vắng mặt, thì hàm sẽ đánh giá và trả về replacement. Nếu không, hàm sẽ trả về value.

Ví dụ:

value replacement if_absent(value, replacement)
5L 0L 5L
NULL 0L NULL
ABSENT 0L 0L

IS_ERROR

Cú pháp:

is_error(try: ANY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu xảy ra lỗi trong quá trình đánh giá try. Nếu không, hàm sẽ trả về FALSE.

IF_ERROR

Cú pháp:

if_error(try: ANY, catch: ANY) -> ANY

Nội dung mô tả:

Nếu xảy ra lỗi trong quá trình đánh giá try, thì hàm sẽ đánh giá và trả về replacement. Nếu không, hàm sẽ trả về giá trị đã phân giải của try.

LỖI

Cú pháp:

error(message: STRING) -> ANY

Nội dung mô tả:

Kết quả đánh giá hàm error khiến quá trình đánh giá quy trình bị chấm dứt kèm theo lỗi. message đã cho được đưa vào lỗi.

Ví dụ:

cond res switch_on(cond, res, error("no condition matched"))
TRUE 1L 1L
FALSE 1L ERROR ("no condition matched")

Hàm tham chiếu

Loại REFERENCE đóng vai trò là "con trỏ" đến các tài liệu khác trong cơ sở dữ liệu (hoặc thậm chí là các cơ sở dữ liệu khác). Các hàm sau đây cho phép thao tác với loại này trong quá trình thực thi truy vấn.

Tên Mô tả
COLLECTION_ID Trả về mã nhận dạng của tập hợp lá trong tệp đối chiếu đã cho
DOCUMENT_ID Trả về mã nhận dạng của tài liệu trong tệp đối chiếu đã cho
PARENT Trả về tệp đối chiếu gốc
REFERENCE_SLICE Trả về một tập hợp con các đoạn trong tệp đối chiếu đã cho

COLLECTION_ID

Cú pháp:

collection_id(ref: REFERENCE) -> STRING

Nội dung mô tả:

Trả về mã nhận dạng tập hợp lá của REFERENCE đã cho.

Ví dụ:

ref collection_id(ref)
users/user1 "users"
users/user1/posts/post1 "posts"

DOCUMENT_ID

Cú pháp:

document_id(ref: REFERENCE) -> ANY

Nội dung mô tả:

Trả về mã tài liệu của REFERENCE đã cho.

Ví dụ:

ref document_id(ref)
users/user1 "user1"
users/user1/posts/post1 "post1"

CHA MẸ

Cú pháp:

parent(ref: REFERENCE) -> REFERENCE

Nội dung mô tả:

Trả về REFERENCE mẹ của tệp đối chiếu đã cho hoặc NULL nếu tệp đối chiếu đó đã là tệp đối chiếu gốc.

Ví dụ:

ref parent(ref)
/ NULL
users/user1 /
users/user1/posts/post1 users/user1

REFERENCE_SLICE

Cú pháp:

reference_slice(ref: REFERENCE, offset: INT, length: INT) -> REFERENCE

Nội dung mô tả:

REFERENCE là danh sách các bộ dữ liệu (collection_id, document_id) và cho phép xem danh sách đó, giống như array_slice(...).

Trả về một REFERENCE mới là một tập hợp con của các phân đoạn của ref đã cho.

  • offset: Chỉ mục bắt đầu (bắt đầu từ 0) của lát cắt. Nếu là số âm, thì đây là độ lệch so với điểm cuối của tệp đối chiếu.
  • length: Số lượng phân đoạn cần đưa vào lát cắt.

Ví dụ:

ref offset length reference_slice(ref, offset, length)
a/1/b/2/c/3 1L 2L b/2/c/3
a/1/b/2/c/3 0L 2L a/1/b/2
a/1/b/2/c/3 -2L 2L c/3

Hàm logic

Tên Mô tả
AND Thực hiện phép toán logic AND
OR Thực hiện phép toán logic OR
XOR Thực hiện phép XOR logic
NOT Thực hiện phép phủ định logic
NOR Thực hiện phép toán logic NOR
CONDITIONAL Đánh giá nhánh dựa trên biểu thức có điều kiện.
IF_NULL Trả về giá trị không rỗng đầu tiên
SWITCH_ON Đánh giá các nhánh dựa trên một loạt điều kiện
EQUAL_ANY Kiểm tra xem một giá trị có bằng với bất kỳ phần tử nào trong một mảng hay không
NOT_EQUAL_ANY Kiểm tra xem một giá trị có khác với mọi phần tử trong một mảng hay không
MAXIMUM Trả về giá trị lớn nhất trong một tập hợp giá trị
MINIMUM Trả về giá trị nhỏ nhất trong một tập hợp giá trị

VÀ

Cú pháp:

and(x: BOOLEAN...) -> BOOLEAN

Nội dung mô tả:

Trả về giá trị logic AND của hai hoặc nhiều giá trị boolean.

Trả về NULL nếu không thể lấy được kết quả do bất kỳ giá trị nào đã cho là ABSENT hoặc NULL.

Ví dụ:

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

HOẶC

Cú pháp:

or(x: BOOLEAN...) -> BOOLEAN

Nội dung mô tả:

Trả về giá trị logic HOẶC của hai hoặc nhiều giá trị boolean.

Trả về NULL nếu không thể lấy được kết quả do bất kỳ giá trị nào đã cho là ABSENT hoặc NULL.

Ví dụ:

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

Cú pháp:

xor(x: BOOLEAN...) -> BOOLEAN

Nội dung mô tả:

Trả về giá trị XOR logic của hai hoặc nhiều giá trị boolean.

Trả về NULL nếu bất kỳ giá trị nào đã cho là ABSENT hoặc NULL.

Ví dụ:

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

Cú pháp:

nor(x: BOOLEAN...) -> BOOLEAN

Nội dung mô tả:

Trả về giá trị logic NOR của hai hoặc nhiều giá trị boolean.

Trả về NULL nếu không thể lấy được kết quả do bất kỳ giá trị nào đã cho là ABSENT hoặc NULL.

Ví dụ:

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

Cú pháp:

not(x: BOOLEAN) -> BOOLEAN

Nội dung mô tả:

Trả về giá trị phủ định logic của một giá trị 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Not(firestore.ArrayContains(firestore.FieldOf("tags"), "nonfiction")).As("isFiction"),
	)).
	Execute(ctx)

CÓ ĐIỀU KIỆN

Cú pháp:

conditional(condition: BOOLEAN, true_case: ANY, false_case: ANY) -> ANY

Nội dung mô tả:

Đánh giá và trả về true_case nếu condition cho kết quả là TRUE.

Đánh giá và trả về false_case nếu điều kiện được phân giải thành FALSE, NULL hoặc giá trị ABSENT.

Ví dụ:

condition true_case false_case conditional(condition, true_case, false_case)
TRUE 1L 0L 1L
FALSE 1L 0L 0L
NULL 1L 0L 0L
ABSENT 1L 0L 0L
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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

if_null(expr: ANY, replacement: ANY) -> ANY

Nội dung mô tả:

Trả về expr nếu không phải là NULL, nếu không thì đánh giá và trả về replacement. Biểu thức replacement sẽ không được đánh giá nếu bạn sử dụng expr.

Ví dụ:

expr replacement if_null(expr, replacement)
1L 2L 1L
NULL 2L 2L
ABSENT 2L ABSENT

SWITCH_ON

Cú pháp:

switch_on(cond1: BOOLEAN, res1: ANY, cond2: BOOLEAN, res2: ANY, ..., [default: ANY]) -> ANY

Nội dung mô tả:

Đánh giá một loạt điều kiện và trả về kết quả liên quan đến điều kiện TRUE đầu tiên. Nếu không có điều kiện nào được đánh giá là TRUE, thì giá trị default sẽ được trả về nếu được cung cấp. Nếu không có giá trị default nào được cung cấp, thì lỗi sẽ được gửi nếu không có điều kiện nào khác được đánh giá là TRUE.

Để cung cấp giá trị default, hãy truyền giá trị đó dưới dạng đối số cuối cùng sao cho có một số đối số lẻ.

Ví dụ:

x switch_on(eq(x, 1L), "one", eq(x, 2L), "two", "other")
1L "one"
2L "hai"
3L "other"

EQUAL_ANY

Cú pháp:

equal_any(value: ANY, search_space: ARRAY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value nằm trong mảng search_space.

Ví dụ:

value search_space equal_any(value, search_space)
0L [1L, 2L, 3L] FALSE
2L [1L, 2L, 3L] TRUE
NULL [1L, 2L, 3L] FALSE
NULL [1L, NULL] TRUE
ABSENT [1L, NULL] FALSE
NaN (Không phải số) [1L, NaN, 3L] 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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

not_equal_any(value: ANY, search_space: ARRAY) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value không nằm trong mảng search_space.

Ví dụ:

value search_space not_equal_any(value, search_space)
0L [1L, 2L, 3L] TRUE
2L [1L, 2L, 3L] FALSE
NULL [1L, 2L, 3L] TRUE
NULL [1L, NULL] FALSE
ABSENT [1L, NULL] TRUE
NaN (Không phải số) [1L, NaN, 3L] 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.NotEqualAny(firestore.FieldOf("author"), []string{"George Orwell", "F. Scott Fitzgerald"}).As("byExcludedAuthors"),
	)).
	Execute(ctx)

TỐI ĐA

Cú pháp:

maximum(x: ANY...) -> ANY
maximum(x: ARRAY) -> ANY

Nội dung mô tả:

Trả về giá trị lớn nhất không phải là NULL, không phải là ABSENT trong một chuỗi giá trị x.

Nếu không có giá trị nào khác NULL và ABSENT, thì hàm sẽ trả về NULL.

Nếu có nhiều giá trị tương đương tối đa, thì hàm có thể trả về bất kỳ giá trị nào trong số đó. Thứ tự loại giá trị tuân theo thứ tự được ghi nhận.

Ví dụ:

x y maximum(x, y)
FALSE TRUE TRUE
FALSE -10L -10L
0,0 -5L 0,0
"foo" "bar" "foo"
"foo" ["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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.LogicalMaximum(firestore.FieldOf("rating"), 1).As("flooredRating"),
	)).
	Execute(ctx)

TỐI THIỂU

Cú pháp:

minimum(x: ANY...) -> ANY
minimum(x: ARRAY) -> ANY

Nội dung mô tả:

Trả về giá trị không phải NULL, không phải ABSENT nhỏ nhất trong một chuỗi giá trị x.

Nếu không có giá trị nào khác NULL và ABSENT, thì hàm sẽ trả về NULL.

Nếu có nhiều giá trị tương đương tối thiểu, thì hàm có thể trả về bất kỳ giá trị nào trong số đó. Thứ tự loại giá trị tuân theo thứ tự được ghi nhận.

Ví dụ:

x y minimum(x, y)
FALSE TRUE FALSE
FALSE -10L FALSE
0,0 -5L -5L
"foo" "bar" "bar"
"foo" ["foo"] "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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.LogicalMinimum(firestore.FieldOf("rating"), 5).As("cappedRating"),
	)).
	Execute(ctx)

Hàm bản đồ

Tên Mô tả
MAP Tạo một giá trị bản đồ từ một loạt cặp khoá-giá trị
MAP_GET Trả về giá trị trong bản đồ dựa trên khoá được chỉ định
MAP_SET Trả về bản sao của một bản đồ có một loạt khoá đã cập nhật
MAP_REMOVE Trả về bản sao của một bản đồ đã xoá một loạt khoá
MAP_MERGE Hợp nhất một loạt bản đồ với nhau.
CURRENT_CONTEXT Trả về bối cảnh hiện tại dưới dạng bản đồ.
MAP_KEYS Trả về một mảng gồm tất cả khoá trong một bản đồ.
MAP_VALUES Trả về một mảng gồm tất cả giá trị trong một bản đồ.
MAP_ENTRIES Trả về một mảng gồm các cặp khoá-giá trị của một bản đồ.

MAP

Cú pháp:

map(key: STRING, value: ANY, ...) -> MAP

Nội dung mô tả:

Tạo một bản đồ từ một loạt cặp khoá-giá trị.

MAP_GET

Cú pháp:

map_get(map: ANY, key: STRING) -> ANY

Nội dung mô tả:

Trả về giá trị trong một bản đồ dựa trên khoá được chỉ định. Trả về giá trị ABSENT nếu key không tồn tại trong bản đồ hoặc nếu đối số map không phải là 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.MapGet(firestore.FieldOf("awards"), "pulitzer").As("hasPulitzerAward"),
	)).
	Execute(ctx)

MAP_SET

Cú pháp:

map_set(map: MAP, key: STRING, value: ANY, ...) -> MAP

Nội dung mô tả:

Trả về bản sao của giá trị map có nội dung được cập nhật bằng một loạt cặp khoá-giá trị.

Nếu giá trị đã cho phân giải thành một giá trị không có, thì khoá liên kết sẽ bị xoá khỏi bản đồ.

Nếu đối số map không phải là MAP, thì hàm sẽ trả về một giá trị vắng mặt.

MAP_REMOVE

Cú pháp:

map_remove(map: MAP, key: STRING...) -> MAP

Nội dung mô tả:

Trả về bản sao của giá trị map sau khi xoá một loạt khoá.

MAP_MERGE

Cú pháp:

map_merge(maps: MAP...) -> MAP

Hợp nhất nội dung của 2 bản đồ trở lên. Nếu nhiều bản đồ có giá trị xung đột, thì giá trị cuối cùng sẽ được sử dụng.

CURRENT_CONTEXT

Cú pháp:

current_context() -> MAP

Trả về một bản đồ bao gồm tất cả các trường có sẵn tại điểm thực thi hiện tại.

MAP_KEYS

Cú pháp:

map_keys(map: MAP) -> ARRAY<STRING>

Nội dung mô tả:

Trả về một mảng chứa tất cả khoá của giá trị map.

MAP_VALUES

Cú pháp:

map_values(map: MAP) -> ARRAY<ANY>

Nội dung mô tả:

Trả về một mảng chứa tất cả giá trị của giá trị map.

MAP_ENTRIES

Cú pháp:

map_entries(map: MAP) -> ARRAY<MAP>

Nội dung mô tả:

Trả về một mảng chứa tất cả các cặp khoá-giá trị trong giá trị map.

Mỗi cặp khoá-giá trị sẽ có dạng một bản đồ với hai mục nhập, k và v.

Ví dụ:

map map_entries(map)
{} []
{"foo" : 2L} [{"k": "foo", "v" : 2L}]
{"foo" : "bar", "bar" : "foo"} [{"k": "foo", "v" : "bar" }, {"k" : "bar", "v": "foo"}]

Hàm chuỗi

Tên Mô tả
BYTE_LENGTH Trả về số lượng BYTES trong một giá trị STRING hoặc BYTES
CHAR_LENGTH Trả về số lượng ký tự unicode trong một giá trị STRING
STARTS_WITH Trả về TRUE nếu STRING bắt đầu bằng một tiền tố nhất định
ENDS_WITH Trả về TRUE nếu STRING kết thúc bằng một hậu tố đã cho
LIKE Trả về TRUE nếu STRING khớp với một mẫu
REGEX_CONTAINS Trả về TRUE nếu một giá trị khớp một phần hoặc khớp hoàn toàn với một biểu thức chính quy
REGEX_FIND Trả về chuỗi con đầu tiên khớp với biểu thức chính quy hoặc NULL nếu không có kết quả khớp.
REGEX_FIND_ALL Trả về một mảng gồm tất cả chuỗi con khớp với một biểu thức chính quy hoặc một mảng trống nếu không có kết quả khớp.
REGEX_MATCH Trả về TRUE nếu bất kỳ phần nào của giá trị khớp với một biểu thức chính quy
STRING_CONCAT Nối nhiều STRING thành một STRING
STRING_CONTAINS Trả về TRUE nếu một giá trị chứa STRING
STRING_INDEX_OF Trả về chỉ mục (bắt đầu từ 0) của lần xuất hiện đầu tiên của giá trị STRING hoặc BYTES.
TO_UPPER Chuyển đổi giá trị STRING hoặc BYTES thành chữ hoa.
TO_LOWER Chuyển đổi giá trị STRING hoặc BYTES thành chữ thường.
SUBSTRING Lấy một chuỗi con của giá trị STRING hoặc BYTES.
STRING_REVERSE Đảo ngược giá trị STRING hoặc BYTES.
STRING_REPEAT Lặp lại giá trị STRING hoặc BYTES theo số lần được chỉ định.
STRING_REPLACE_ALL Thay thế tất cả các lần xuất hiện của giá trị STRING hoặc BYTES.
STRING_REPLACE_ONE Thay thế lần xuất hiện đầu tiên của giá trị STRING hoặc BYTES.
TRIM Cắt bớt các ký tự ở đầu và cuối của một giá trị STRING hoặc BYTES.
LTRIM Cắt bớt các ký tự ở đầu khỏi giá trị STRING hoặc BYTES.
RTRIM Cắt bớt các ký tự ở cuối khỏi giá trị STRING hoặc BYTES.
SPLIT Tách một giá trị STRING hoặc BYTES thành một mảng.

BYTE_LENGTH

Cú pháp:

byte_length[T <: STRING | BYTES](value: T) -> INT64

Nội dung mô tả:

Trả về số lượng BYTES trong một giá trị STRING hoặc BYTES.

Ví dụ:

value byte_length(value)
"abc" 3
"xyzabc" 6
b"abc" 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ByteLength(firestore.FieldOf("title")).As("titleByteLength"),
	)).
	Execute(ctx)

CHAR_LENGTH

Cú pháp:

char_length(value: STRING) -> INT64

Nội dung mô tả:

Trả về số lượng điểm mã unicode trong giá trị STRING.

Ví dụ:

value char_length(value)
"abc" 3
"xin chào" 5
"thế giới" 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.CharLength(firestore.FieldOf("title")).As("titleCharLength"),
	)).
	Execute(ctx)

STARTS_WITH

Cú pháp:

starts_with(value: STRING, prefix: STRING) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value bắt đầu bằng prefix.

Ví dụ:

value tiền tố starts_with(value, prefix)
"abc" "a" đúng
"abc" "b" false
"abc" "" đúng
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.StartsWith(firestore.FieldOf("title"), "The").As("needsSpecialAlphabeticalSort"),
	)).
	Execute(ctx)

ENDS_WITH

Cú pháp:

ends_with(value: STRING, postfix: STRING) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value kết thúc bằng postfix.

Ví dụ:

value hậu tố ends_with(value, postfix)
"abc" "c" đúng
"abc" "b" false
"abc" "" đúng
Node.js
const result = await db.pipeline()
  .collection("inventory/devices/laptops")
  .select(
    field("name").endsWith("16 inch")
      .as("16InLaptops")
  )
  .execute();
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("inventory/devices/laptops").
	Select(firestore.Fields(
		firestore.EndsWith(firestore.FieldOf("name"), "16 inch").As("`Laptops16in`"),
	)).
	Execute(ctx)

THÍCH

Cú pháp:

like(value: STRING, pattern: STRING) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value khớp với pattern.

Ví dụ:

value mẫu like(value, pattern)
"Firestore" "Fire%" đúng
"Firestore" "%store" đúng
"Datastore" "Data_tore" đúng
"100%" "100\%" đúng
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Like(firestore.FieldOf("genre"), "%Fiction").As("anyFiction"),
	)).
	Execute(ctx)

REGEX_CONTAINS

Cú pháp:

regex_contains(value: STRING, regexp: STRING | REGEX) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu một phần của value khớp với regexp. Nếu regexp không phải là một biểu thức chính quy hợp lệ, thì hàm này sẽ trả về error.

Đối số regexp cũng có thể là giá trị REGEX được tạo bằng regex("pattern", "options"). Định dạng này cho phép bạn cung cấp các tuỳ chọn biểu thức chính quy cùng với mẫu. Các tuỳ chọn được hỗ trợ là:

  • i: Kết quả khớp không phân biệt chữ hoa chữ thường.
  • m: Chế độ nhiều dòng (^ và $ khớp với phần đầu hoặc phần cuối của dòng).
  • s: Chế độ Dotall (. khớp với dòng mới).

Nếu regexp là STRING, thì không có tuỳ chọn nào được áp dụng ngoài những tuỳ chọn được nhúng trong chính mẫu (ví dụ: (?i)).

Biểu thức chính quy tuân theo cú pháp của thư viện re2.

Ví dụ:

value regexp regex_contains(value, regexp)
"Firestore" "Lửa" đúng
"Firestore" "store$" đúng
"Firestore" "data" false
"Firestore" regex("fire", "i") đúng
"Firestore" regex("FIRE", "") false
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.RegexContains(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreRelated"),
	)).
	Execute(ctx)

REGEX_FIND

Cú pháp:

regex_find(value: STRING, regexp: STRING | REGEX) -> STRING

Nội dung mô tả:

Trả về chuỗi con đầu tiên trong value khớp với regexp hoặc NULL nếu không có kết quả khớp. Nếu regexp không phải là một biểu thức chính quy hợp lệ, thì hàm này sẽ trả về lỗi error.

Đối số regexp cũng có thể là giá trị REGEX được tạo bằng regex("pattern", "options"). Định dạng này cho phép bạn cung cấp các tuỳ chọn biểu thức chính quy cùng với mẫu. Các tuỳ chọn được hỗ trợ là:

  • i: Kết quả khớp không phân biệt chữ hoa chữ thường.
  • m: Chế độ nhiều dòng (^ và $ khớp với phần đầu hoặc phần cuối của dòng).
  • s: Chế độ Dotall (. khớp với dòng mới).

Nếu regexp là STRING, thì không có tuỳ chọn nào được áp dụng ngoài những tuỳ chọn được nhúng trong chính mẫu (ví dụ: (?i)).

Biểu thức chính quy tuân theo cú pháp của thư viện re2.

Ví dụ:

value regexp regex_find(value, regexp)
"Sometext MATCH" "SomeText" "Sometext"
"Sometext MATCH" regex("match", "i") "MATCH"
"Sometext MATCH" regex("(match)", "i") "MATCH"
"Khớp một số văn bản" regex("MATCH", "") null

REGEX_FIND_ALL

Cú pháp:

regex_find_all(value: STRING, regexp: STRING | REGEX) -> ARRAY<STRING>

Nội dung mô tả:

Trả về một mảng gồm tất cả chuỗi con trong value khớp với regexp hoặc một mảng trống nếu không có kết quả khớp. Nếu regexp không phải là biểu thức chính quy hợp lệ, thì hàm này sẽ trả về lỗi error.

Đối số regexp cũng có thể là giá trị REGEX được tạo bằng regex("pattern", "options"). Định dạng này cho phép bạn cung cấp các tuỳ chọn biểu thức chính quy cùng với mẫu. Các tuỳ chọn được hỗ trợ là:

  • i: Kết quả khớp không phân biệt chữ hoa chữ thường.
  • m: Chế độ nhiều dòng (^ và $ khớp với phần đầu hoặc phần cuối của dòng).
  • s: Chế độ Dotall (. khớp với dòng mới).

Nếu regexp là STRING, thì không có tuỳ chọn nào được áp dụng ngoài những tuỳ chọn được nhúng trong chính mẫu (ví dụ: (?i)).

Biểu thức chính quy tuân theo cú pháp của thư viện re2.

Ví dụ:

value regexp regex_find_all(value, regexp)
"một hai ba hai" "one" ["one"]
"one TWO three Two" regex("two", "i") ["TWO", "Two"]
"một hai ba hai" regex("TWO", "") []

REGEX_MATCH

Cú pháp:

regex_match(value: STRING, regexp: STRING | REGEX) -> BOOLEAN

Nội dung mô tả:

Trả về TRUE nếu value khớp hoàn toàn với regexp. Nếu regexp không phải là một biểu thức chính quy hợp lệ, thì hàm này sẽ trả về error.

Đối số regexp cũng có thể là giá trị REGEX được tạo bằng regex("pattern", "options"). Định dạng này cho phép bạn cung cấp các tuỳ chọn biểu thức chính quy cùng với mẫu. Các tuỳ chọn được hỗ trợ là:

  • i: Kết quả khớp không phân biệt chữ hoa chữ thường.
  • m: Chế độ nhiều dòng (^ và $ khớp với phần đầu hoặc phần cuối của dòng).
  • s: Chế độ Dotall (. khớp với dòng mới).

Nếu regexp là STRING, thì không có tuỳ chọn nào được áp dụng ngoài những tuỳ chọn được nhúng trong chính mẫu (ví dụ: (?i)).

Biểu thức chính quy tuân theo cú pháp của thư viện re2.

Ví dụ:

value regexp regex_match(value, regexp)
"Firestore" "F.*store" đúng
"Firestore" "Lửa" false
"Firestore" "^F.*e$" đúng
"FiReStOrE" regex("firestore", "i") đúng
"Firestore" regex("firestore", "") false
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.RegexMatch(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreExactly"),
	)).
	Execute(ctx)

STRING_CONCAT

Cú pháp:

string_concat(values: STRING...) -> STRING

Nội dung mô tả:

Nối hai hoặc nhiều giá trị STRING thành một kết quả duy nhất.

Ví dụ:

đối số string_concat(values...)
() error
("a") "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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.StringConcat(firestore.FieldOf("title"), " by ", firestore.FieldOf("author")).As("fullyQualifiedTitle"),
	)).
	Execute(ctx)

STRING_CONTAINS

Cú pháp:

string_contains(value: STRING, substring: STRING) -> BOOLEAN

Nội dung mô tả:

Kiểm tra xem value có chứa Chuỗi ký tự substring hay không.

Ví dụ:

value chuỗi con string_contains(value, substring)
"abc" "b" đúng
"abc" "d" false
"abc" "" đúng
"a.c" "." đúng
"☃☃☃" "☃" đúng
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("articles").
	Select(firestore.Fields(
		firestore.StringContains(firestore.FieldOf("body"), "Firestore").As("isFirestoreRelated"),
	)).
	Execute(ctx)

STRING_INDEX_OF

Cú pháp:

string_index_of[T <: STRING | BYTES](value: T, search: T) -> INT64

Nội dung mô tả:

Trả về chỉ mục dựa trên 0 của lần xuất hiện đầu tiên của search trong value.

  • Trả về -1 nếu không tìm thấy search.
  • Nếu value là một giá trị STRING, thì kết quả sẽ được đo bằng điểm mã unicode. Nếu là giá trị BYTES, thì giá trị này được đo bằng byte.
  • Nếu search là giá trị STRING hoặc BYTES trống, thì kết quả sẽ là 0.

Ví dụ:

value tìm-kiếm string_index_of(value, search)
"hello world" "o" 4
"hello world" "l" 2
"hello world" "z" -1
"chuối" "ana" 1
"abc" "" 0
b"abc" b"b" 1
"é" "é" 0
b"é" b"é" 0

TO_UPPER

Cú pháp:

to_upper[T <: STRING | BYTES](value: T) -> T

Nội dung mô tả:

Chuyển đổi giá trị STRING hoặc BYTES thành chữ hoa.

Nếu một byte hoặc ký tự không tương ứng với một ký tự chữ cái viết thường UTF-8, thì byte hoặc ký tự đó sẽ được chuyển qua mà không thay đổi.

Ví dụ:

value to_upper(value)
"abc" "ABC"
"AbC" "ABC"
b"abc" "ABC"
b"a1c" b"A1C"
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("authors").
	Select(firestore.Fields(
		firestore.ToUpper(firestore.FieldOf("name")).As("uppercaseName"),
	)).
	Execute(ctx)

TO_LOWER

Cú pháp:

to_lower[T <: STRING | BYTES](value: T) -> T

Nội dung mô tả:

Chuyển đổi giá trị STRING hoặc BYTES thành chữ thường.

Nếu một byte hoặc ký tự không tương ứng với một ký tự chữ cái viết hoa UTF-8, thì byte hoặc ký tự đó sẽ được chuyển qua mà không thay đổi.

Ví dụ:

value to_lower(value)
"ABC" "abc"
"AbC" "abc"
"A1C" "a1c"
"ABC" b"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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("authors").
	Select(firestore.Fields(
		firestore.Equal(firestore.ToLower(firestore.FieldOf("genre")), "fantasy").As("isFantasy"),
	)).
	Execute(ctx)

SUBSTRING

Cú pháp:

substring[T <: STRING | BYTES](input: T, position: INT64) -> T
substring[T <: STRING | BYTES](input: T, position: INT64, length: INT64) -> T

Nội dung mô tả:

Trả về một chuỗi con của input bắt đầu từ position (chỉ mục dựa trên số 0) và bao gồm tối đa length mục. Nếu không cung cấp length, hàm sẽ trả về chuỗi con từ position đến cuối input.

  • Nếu input là giá trị STRING, thì position và length được đo bằng điểm mã unicode. Nếu là giá trị BYTES, thì các giá trị này được đo bằng byte.

  • Nếu position lớn hơn độ dài của input, thì hàm sẽ trả về một chuỗi con trống. Nếu position cộng với length lớn hơn độ dài của input, thì chuỗi con sẽ bị cắt bớt đến cuối input.

  • Nếu position là số âm, thì vị trí sẽ được lấy từ cuối dữ liệu đầu vào. Nếu giá trị âm position lớn hơn kích thước của dữ liệu đầu vào, thì vị trí sẽ được đặt thành 0. length không được là số âm.

Ví dụ:

Khi không cung cấp length:

nhập liệu position substring(input, position)
"abc" 0 "abc"
"abc" 1 "bc"
"abc" 3 ""
"abc" -1 "c"
b"abc" 1 b"bc"

Khi length được cung cấp:

nhập liệu position chiều dài substring(input, position, length)
"abc" 0 1 "a"
"abc" 1 2 "bc"
"abc" -1 1 "c"
b"abc" 0 1 b"a"
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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

string_reverse[T <: STRING | BYTES](input: T) -> T

Nội dung mô tả:

Trả về dữ liệu đầu vào được cung cấp theo thứ tự đảo ngược.

Các ký tự được phân định bằng điểm mã Unicode khi dữ liệu đầu vào là STRING, và byte khi dữ liệu đầu vào là giá trị BYTES.

Ví dụ:

nhập liệu string_reverse(input)
"abc" "cba"
"a🌹b" "b🌹a"
"xin chào" "olleh"
b"abc" b"cba"
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Reverse(firestore.FieldOf("name")).As("reversedName"),
	)).
	Execute(ctx)

STRING_REPEAT

Cú pháp:

string_repeat[T <: STRING | BYTES](input: T, repetitions: INT64) -> T

Nội dung mô tả:

Trả về input được lặp lại repetitions lần.

  • repetitions phải là số nguyên không âm.
  • Nếu repetitions là 0, thì hàm sẽ trả về một giá trị trống có cùng loại với input.
  • Nếu kết quả vượt quá kích thước tối đa cho phép (1 MB), thì hệ thống sẽ trả về lỗi.

Ví dụ:

nhập liệu lần lặp lại string_repeat(input, repetitions)
"foo" 3 "foofoofoo"
"foo" 0 ""
"a " 3 "a a a "
b"ab" 2 b"abab"
"é🦆" 2 "é🦆é🦆"

STRING_REPLACE_ALL

Cú pháp:

string_replace_all[T <: STRING | BYTES](input: T, find: T, replacement: T) -> T

Nội dung mô tả:

Thay thế tất cả các lần xuất hiện không trùng lặp của find trong input bằng replacement.

  • Kết quả trùng khớp có phân biệt chữ hoa chữ thường.
  • Nếu find trống, thì không có nội dung thay thế nào được thực hiện.

Ví dụ:

nhập liệu tìm thay thế string_replace_all(input, find, replacement)
"foobarfoo" "foo" "baz" "bazbarbaz"
"ababab" "aba" "c" "cbab"
"foobar" "o" "" "fbar"
"é🦆🌎🦆" "🦆" "a" "éa🌎a"
b"abc" b"b" b"d" b"adc"

STRING_REPLACE_ONE

Cú pháp:

string_replace_one[T <: STRING | BYTES](input: T, find: T, replacement: T) -> T

Nội dung mô tả:

Thay thế lần xuất hiện đầu tiên của find trong input bằng replacement.

  • Kết quả trùng khớp có phân biệt chữ hoa chữ thường.
  • Nếu find trống, thì không có nội dung thay thế nào được thực hiện.

Ví dụ:

nhập liệu tìm thay thế string_replace_one(input, find, replacement)
"foobarfoo" "foo" "baz" "bazbarfoo"
"é" "é" "a" "a"
b"foobar" b"o" b"z" b"fzoobar"

TRIM

Cú pháp:

trim[T <: STRING | BYTES](input: T, values_to_trim: T) -> T
trim[T <: STRING | BYTES](input: T) -> T

Nội dung mô tả:

Cắt bớt một tập hợp BYTES hoặc CHARS được chỉ định từ đầu và cuối của input được cung cấp.

  • Nếu không có values_to_trim nào được cung cấp, hàm sẽ cắt bớt các ký tự khoảng trắng.

Ví dụ:

Khi không cung cấp values_to_trim:

nhập liệu trim(input)
" foo " "foo"
b" foo " b"foo"
"foo" "foo"
"" ""
" " ""
"\t foo \n" "foo"
b"\t foo \n" b"foo"
"\r\f\v foo \r\f\v" "foo"
b"\r\f\v foo \r\f\v" b"foo"

Khi values_to_trim được cung cấp:

nhập liệu values_to_trim trim(input, values_to_trim)
"abcbfooaacb" "abc" "foo"
"abcdaabadbac" "abc" "daabad"
b"C1C2C3" b"C1" b"C2C3"
b"C1C2" "foo" error
"foo" b"C1" error

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("name").trim().as("whitespaceTrimmedName")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Trim(firestore.FieldOf("name")).As("whitespaceTrimmedName"),
	)).
	Execute(ctx)

LTRIM

Cú pháp:

ltrim[T <: STRING | BYTES](value: T, to_trim: T) -> T
ltrim[T <: STRING | BYTES](value: T) -> T

Nội dung mô tả:

Cắt bớt một tập hợp BYTES hoặc CHARS được chỉ định từ đầu của value được cung cấp.

  • Nếu bạn không cung cấp to_trim, hàm này sẽ cắt bớt các ký tự khoảng trắng ở đầu.

Ví dụ:

Khi không cung cấp to_trim:

value ltrim(value)
" foo " "foo "
"foo" "foo"

Khi to_trim được cung cấp:

value to_trim ltrim(value, to_trim)
"aaabc" "a" "bc"
"abacaba" "ba" "caba"
"é" "é" ""

RTRIM

Cú pháp:

rtrim[T <: STRING | BYTES](value: T, to_trim: T) -> T
rtrim[T <: STRING | BYTES](value: T) -> T

Nội dung mô tả:

Cắt bớt một tập hợp BYTES hoặc CHARS đã chỉ định ở cuối value được cung cấp.

  • Nếu không cung cấp to_trim, hàm sẽ cắt bớt các ký tự khoảng trắng ở cuối.

Ví dụ:

Khi không cung cấp to_trim:

value rtrim(value)
" foo " " foo"
"foo" "foo"

Khi to_trim được cung cấp:

value to_trim rtrim(value, to_trim)
"abccc" "c" "ab"
"abacaba" "ba" "abac"
"é" "é" ""

SPLIT

Cú pháp:

split(input: STRING) -> ARRAY<STRING>
split[T <: STRING | BYTES](input: T, delimiter: T) -> ARRAY<T>

Nội dung mô tả:

Tách một giá trị STRING hoặc BYTES bằng dấu phân cách.

  • Đối với STRING, dấu phân tách mặc định là dấu phẩy ,. Dấu phân cách được coi là một chuỗi duy nhất.

  • Đối với BYTES, bạn phải chỉ định một dấu phân tách.

  • Việc phân tách trên một dấu phân tách trống sẽ tạo ra một mảng điểm mã Unicode cho các giá trị STRING và một mảng BYTES cho các giá trị BYTES.

  • Việc phân tách một STRING trống sẽ trả về một ARRAY có một STRING trống.

Ví dụ:

Khi không cung cấp delimiter:

nhập liệu split(input)
"foo,bar,foo" ["foo", "bar", "foo"]
"foo" ["foo"]
",foo," ["", "foo", ""]
"" [""]
b"C120C2C4" error

Khi delimiter được cung cấp:

nhập liệu dấu phân tách split(input, delimiter)
"foo bar foo" " " ["foo", "bar", "foo"]
"foo bar foo" "z" ["foo bar foo"]
"abc" "" "a", "b", "c"
b"C1,C2,C4" b"," [b"C1", b"C2", b"C4"]
"ABC" b"" [b"A", b"B", b"C"]
"foo" b"C1" error

Hàm dấu thời gian

Tên Mô tả
CURRENT_TIMESTAMP Tạo TIMESTAMP tương ứng với thời gian yêu cầu.
TIMESTAMP_TRUNC Cắt bớt TIMESTAMP theo mức độ chi tiết nhất định.
UNIX_MICROS_TO_TIMESTAMP Chuyển đổi số micrô giây kể từ 1970-01-01 00:00:00 UTC thành TIMESTAMP
UNIX_MILLIS_TO_TIMESTAMP Chuyển đổi số mili giây kể từ 1970-01-01 00:00:00 UTC thành TIMESTAMP
UNIX_SECONDS_TO_TIMESTAMP Chuyển đổi số giây kể từ 1970-01-01 00:00:00 UTC thành TIMESTAMP
TIMESTAMP_ADD Thêm khoảng thời gian vào TIMESTAMP
TIMESTAMP_SUB Trừ một khoảng thời gian khỏi TIMESTAMP
TIMESTAMP_TO_UNIX_MICROS Chuyển đổi TIMESTAMP thành số micrô giây kể từ 1970-01-01 00:00:00 UTC
TIMESTAMP_TO_UNIX_MILLIS Chuyển đổi TIMESTAMP thành số mili giây kể từ 1970-01-01 00:00:00 UTC
TIMESTAMP_TO_UNIX_SECONDS Chuyển đổi TIMESTAMP thành số giây kể từ 1970-01-01 00:00:00 UTC
TIMESTAMP_DIFF Trả về số nguyên của các khoảng unit được chỉ định giữa hai TIMESTAMP.
TIMESTAMP_EXTRACT Trích xuất một part cụ thể (ví dụ: năm, tháng, ngày) từ một TIMESTAMP.

CURRENT_TIMESTAMP

Cú pháp:

current_timestamp() -> TIMESTAMP

Nội dung mô tả:

Lấy dấu thời gian khi bắt đầu thời gian yêu cầu input (được hiểu là số micrô giây kể từ 1970-01-01 00:00:00 UTC).

Giá trị này ổn định trong một truy vấn và sẽ luôn phân giải thành cùng một giá trị nếu được gọi nhiều lần.

TIMESTAMP_TRUNC

Cú pháp:

timestamp_trunc(timestamp: TIMESTAMP | BSON_TIMESTAMP, granularity: STRING[, timezone: STRING]) -> TIMESTAMP

Nội dung mô tả:

Cắt bớt dấu thời gian xuống một mức độ chi tiết nhất định.

Đối số granularity phải là một chuỗi và là một trong những giá trị sau:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day
  • week
  • week([weekday])
  • month
  • quarter
  • year
  • isoyear

Nếu bạn cung cấp đối số timezone, thì việc cắt bớt sẽ dựa trên ranh giới lịch của múi giờ đã cho (ví dụ: việc cắt bớt ngày sẽ cắt bớt đến nửa đêm theo múi giờ đã cho). Việc cắt bớt sẽ tuân theo giờ mùa hè.

Nếu bạn không cung cấp timezone, thì việc cắt bớt sẽ dựa trên ranh giới lịch UTC.

Đối số timezone phải là chuỗi đại diện cho múi giờ trong cơ sở dữ liệu tz, ví dụ: America/New_York. Bạn cũng có thể sử dụng độ lệch thời gian tuỳ chỉnh bằng cách chỉ định độ lệch từ GMT.

Ví dụ:

timestamp granularity timezone timestamp_trunc(timestamp, granularity, timezone)
2000-01-01 10:20:30:123456 UTC "second" Không được cung cấp 2001-01-01 10:20:30 UTC
1997-05-31 04:30:30 UTC "ngày" Không được cung cấp 1997-05-31 00:00:00 UTC
1997-05-31 04:30:30 UTC "ngày" "America/Los_Angeles" 1997-05-30 07:00:00 UTC
2001-03-16 04:00:00 UTC "week(friday) Không được cung cấp 2001-03-16 00:00:00 UTC
2001-03-23 04:00:00 UTC "week(friday) "America/Los_Angeles" 2001-03-23 17:00:00 UTC
20:00:00 ngày 24 tháng 1 năm 2026 (giờ UTC) "month" "GMT+06:32:43" 2026-01-01T06:32:43 UTC

UNIX_MICROS_TO_TIMESTAMP

Cú pháp:

unix_micros_to_timestamp(input: INT64) -> TIMESTAMP

Nội dung mô tả:

Chuyển đổi input (được hiểu là số micrô giây kể từ 1970-01-01 00:00:00 UTC) thành TIMESTAMP. Gửi error nếu không thể chuyển đổi input thành TIMESTAMP hợp lệ.

Ví dụ:

input unix_micros_to_timestamp(input)
0L 01-01-1970 00:00:00 (giờ 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.UnixMicrosToTimestamp(firestore.FieldOf("createdAtMicros")).As("createdAtString"),
	)).
	Execute(ctx)

UNIX_MILLIS_TO_TIMESTAMP

Cú pháp:

unix_millis_to_timestamp(input: INT64) -> TIMESTAMP

Nội dung mô tả:

Chuyển đổi input (được diễn giải là số mili giây kể từ 1970-01-01 00:00:00 UTC) thành TIMESTAMP. Gửi error nếu không thể chuyển đổi input thành TIMESTAMP hợp lệ.

Ví dụ:

input unix_millis_to_timestamp(input)
0L 01-01-1970 00:00:00 (giờ UTC)
4000123L 1970-01-01 01:06:40.123 UTC
-1000000L 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.UnixMillisToTimestamp(firestore.FieldOf("createdAtMillis")).As("createdAtString"),
	)).
	Execute(ctx)

UNIX_SECONDS_TO_TIMESTAMP

Cú pháp:

unix_seconds_to_timestamp(input: INT64) -> TIMESTAMP

Nội dung mô tả:

Chuyển đổi input (được hiểu là số giây kể từ 1970-01-01 00:00:00 UTC) thành TIMESTAMP. Gửi error nếu không thể chuyển đổi input thành TIMESTAMP hợp lệ.

Ví dụ:

input unix_seconds_to_timestamp(input)
0L 01-01-1970 00:00:00 (giờ UTC)
60L 01-01-1970 00:01:00 (giờ 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.UnixSecondsToTimestamp(firestore.FieldOf("createdAtSeconds")).As("createdAtString"),
	)).
	Execute(ctx)

TIMESTAMP_ADD

Cú pháp:

timestamp_add(timestamp: TIMESTAMP | BSON_TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP

Nội dung mô tả:

Thêm amount của unit từ timestamp. Đối số amount có thể là số âm, trong trường hợp đó, đối số này tương đương với TIMESTAMP_SUB.

Đối số unit phải là một chuỗi và là một trong những giá trị sau:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day

Trả về lỗi nếu dấu thời gian thu được không nằm trong phạm vi TIMESTAMP.

Ví dụ:

timestamp unit amount timestamp_add(timestamp, unit, amount)
00:00:00 ngày 20 tháng 2 năm 2025 (giờ UTC) "phút" 2L 2025-02-20 00:02:00 UTC
00:00:00 ngày 20 tháng 2 năm 2025 (giờ UTC) "giờ" -4L 2025-02-19 20:00:00 UTC
00:00:00 ngày 20 tháng 2 năm 2025 (giờ UTC) "ngày" 5L 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampAdd(firestore.FieldOf("createdAt"), "day", 3653).As("expiresAt"),
	)).
	Execute(ctx)

TIMESTAMP_SUB

Cú pháp:

timestamp_sub(timestamp: TIMESTAMP | BSON_TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP

Nội dung mô tả:

Trừ amount của unit khỏi timestamp. Đối số amount có thể là số âm, trong trường hợp đó, đối số này tương đương với TIMESTAMP_ADD.

Đối số unit phải là một chuỗi và là một trong những giá trị sau:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day

Trả về lỗi nếu dấu thời gian thu được không nằm trong phạm vi TIMESTAMP.

Ví dụ:

timestamp unit amount timestamp_sub(timestamp, unit, amount)
00:00, 04-07-2026 (giờ UTC) "phút" 40L 2026-07-03 23:20:00 UTC
00:00, 04-07-2026 (giờ UTC) "giờ" -24L 00:00, 05-07-2026 (giờ UTC)
00:00, 04-07-2026 (giờ UTC) "ngày" 3L 00:00, 01-07-2026 (giờ 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampSubtract(firestore.FieldOf("expiresAt"), "day", 14).As("sendWarningTimestamp"),
	)).
	Execute(ctx)

TIMESTAMP_TO_UNIX_MICROS

Cú pháp:

timestamp_to_unix_micros(input: TIMESTAMP | BSON_TIMESTAMP) -> INT64

Nội dung mô tả:

Chuyển đổi input thành số micrô giây kể từ 1970-01-01 00:00:00 UTC. Cắt bớt các mức độ chính xác cao hơn bằng cách làm tròn xuống đầu micro giây.

Ví dụ:

input timestamp_to_unix_micros(input)
01-01-1970 00:00:00 (giờ 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampToUnixMicros(firestore.FieldOf("dateString")).As("unixMicros"),
	)).
	Execute(ctx)

TIMESTAMP_TO_UNIX_MILLIS

Cú pháp:

timestamp_to_unix_millis(input: TIMESTAMP | BSON_TIMESTAMP) -> INT64

Nội dung mô tả:

Chuyển đổi input thành số mili giây kể từ 1970-01-01 00:00:00 UTC. Cắt bớt các mức độ chính xác cao hơn bằng cách làm tròn xuống đầu mili giây.

Ví dụ:

input timestamp_to_unix_millis(input)
01-01-1970 00:00:00 (giờ 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampToUnixMillis(firestore.FieldOf("dateString")).As("unixMillis"),
	)).
	Execute(ctx)

TIMESTAMP_TO_UNIX_SECONDS

Cú pháp:

timestamp_to_unix_seconds(input: TIMESTAMP | BSON_TIMESTAMP) -> INT64

Nội dung mô tả:

Chuyển đổi input thành số giây kể từ 1970-01-01 00:00:00 UTC. Cắt bớt các mức độ chính xác cao hơn bằng cách làm tròn xuống đầu giây.

Ví dụ:

input timestamp_to_unix_seconds(input)
01-01-1970 00:00:00 (giờ UTC) 0L
01-01-1970 00:01:00 (giờ UTC) 60L
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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.TimestampToUnixSeconds(firestore.FieldOf("dateString")).As("unixSeconds"),
	)).
	Execute(ctx)

TIMESTAMP_DIFF

Cú pháp:

timestamp_diff(end: TIMESTAMP | BSON_TIMESTAMP, start: TIMESTAMP | BSON_TIMESTAMP, unit: STRING) -> INT64

Nội dung mô tả:

Trả về số nguyên của các khoảng unit được chỉ định giữa hai TIMESTAMP.

  • Trả về giá trị âm nếu end đứng trước start.
  • Cắt bớt mọi đơn vị phân số. Ví dụ: timestamp_diff("2021-01-01 00:00:01", "2021-01-01 00:00:00", "minute") trả về 0.

Đối số unit phải là một chuỗi và là một trong những giá trị sau:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day

Ví dụ:

end start unit timestamp_diff(end, start, unit)
00:01, 04-07-2026 (giờ UTC) 00:00, 04-07-2026 (giờ UTC) "second" 60L
00:00, 04-07-2026 (giờ UTC) 00:00, 05-07-2026 (giờ UTC) "ngày" -1L
00:00:59 ngày 4 tháng 7 năm 2026 (giờ UTC) 00:00, 04-07-2026 (giờ UTC) "phút" 0L

TIMESTAMP_EXTRACT

Cú pháp:

timestamp_extract(timestamp: TIMESTAMP | BSON_TIMESTAMP, part: STRING[, timezone: STRING]) -> INT64

Nội dung mô tả:

Trích xuất một part cụ thể (ví dụ: năm, tháng, ngày) từ timestamp.

Đối số part phải là một chuỗi và là một trong những giá trị sau:

  • microsecond
  • millisecond
  • second
  • minute
  • hour
  • day
  • dayofweek: Trả về một giá trị từ 1 (Chủ Nhật) đến 7 (thứ Bảy).
  • dayofyear
  • week: Trả về số tuần trong năm, bắt đầu từ 1 cho Chủ Nhật đầu tiên của năm.
  • week([weekday]): Trả về số tuần trong năm, bắt đầu từ weekday được chỉ định.
  • month
  • quarter
  • year
  • isoweek: Trả về số tuần theo tiêu chuẩn ISO 8601.
  • isoyear: Trả về năm đánh số tuần theo tiêu chuẩn ISO 8601.

Nếu bạn cung cấp đối số timezone, thì việc trích xuất sẽ dựa trên lịch của múi giờ đã cho. Quá trình trích xuất sẽ tuân theo giờ mùa hè.

Nếu bạn không cung cấp timezone, thì quá trình trích xuất sẽ dựa trên UTC.

Đối số timezone phải là chuỗi đại diện cho múi giờ trong cơ sở dữ liệu múi giờ, ví dụ: America/New_York. Bạn cũng có thể sử dụng độ lệch thời gian tuỳ chỉnh bằng cách chỉ định độ lệch so với GMT.

Ví dụ:

timestamp part timezone timestamp_extract(timestamp, part, timezone)
2025-02-20 10:20:30 UTC "year" Không được cung cấp 2025
2025-02-20 10:20:30 UTC "ngày" Không được cung cấp 20
2025-12-31 23:59:59 UTC "year" "Châu Á/Tokyo" 2026

Hàm kiểu dữ liệu

Tên Mô tả
TYPE Trả về loại giá trị dưới dạng STRING.
IS_TYPE Trả về true nếu giá trị khớp với loại đã chỉ định.

LOẠI

Cú pháp:

type(input: ANY) -> STRING

Nội dung mô tả:

Trả về một chuỗi đại diện của loại input.

Nếu không có giá trị, hàm sẽ trả về NULL.

Ví dụ:

input type(input)
NULL "null"
đúng "boolean"
1 "int32"
-3L "int64"
3.14 "float64"
2024-01-01T00:00:00Z UTC "timestamp"
"foo" "string"
b"foo" "bytes"
[1, 2] "array"
{"a": 1} "map"
path("c/d") "reference"
vector([1.0, 2.0]) "vector"
object_id "a7f2c9d18b3e4509f67c12d8" "object_id"
1.2e9m "decimal128"
regex "/pattern/i" "regex"
bson_timestamp(1732754912, 500) "bson_timestamp"
VẮNG MẶT NULL

Ví dụ về khách hàng

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"))
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.NotEqual(firestore.FieldOf("title"), "1984").As("not1984"),
	)).
	Execute(ctx)

IS_TYPE

Cú pháp:

is_type(input: ANY, type: STRING) -> BOOLEAN

Nội dung mô tả:

Trả về true nếu input khớp với type đã chỉ định, nếu không thì trả về false. Nếu không có input, hàm sẽ trả về NULL.

Các chuỗi type được hỗ trợ là:

  • "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"

Ví dụ:

input type is_type(input, type)
NULL "null" đúng
đúng "boolean" đúng
3.14 "float64" đúng
"foo" "string" đúng
b"foo" "string" false
[1, 2] "array" đúng
{"a": 1} "map" đúng
vector([1.0, 2.0]) "vector" đúng
VẮNG MẶT "string" NULL
"bar" "other" LỖI

Hàm vectơ

Tên Mô tả
COSINE_DISTANCE Trả về khoảng cách cosin giữa hai vectơ
DOT_PRODUCT Trả về tích vô hướng giữa hai vectơ
EUCLIDEAN_DISTANCE Trả về khoảng cách Euclid giữa hai vectơ
MANHATTAN_DISTANCE Trả về khoảng cách Manhattan giữa hai vectơ
VECTOR_LENGTH Trả về số phần tử trong một vectơ

COSINE_DISTANCE

Cú pháp:

cosine_distance(x: VECTOR, y: VECTOR) -> FLOAT64

Nội dung mô tả:

Trả về khoảng cách cosin giữa x và 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")));
Swift
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();
Bắt đầu
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

Cú pháp:

dot_product(x: VECTOR, y: VECTOR) -> FLOAT64

Nội dung mô tả:

Trả về tích vô hướng của x và 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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

euclidean_distance(x: VECTOR, y: VECTOR) -> FLOAT64

Nội dung mô tả:

Tính khoảng cách Euclid giữa x và 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")
  )
);
Swift
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();
Bắt đầu
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

Cú pháp:

manhattan_distance(x: VECTOR, y: VECTOR) -> FLOAT64

Nội dung mô tả:

Tính khoảng cách Manhattan giữa x và y.

VECTOR_LENGTH

Cú pháp:

vector_length(vector: VECTOR) -> INT64

Nội dung mô tả:

Trả về số phần tử trong một 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")
  )
);
Swift
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();
Bắt đầu
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.VectorLength(firestore.FieldOf("embedding")).As("vectorLength"),
	)).
	Execute(ctx)