所有函式參考資料

匯總

所有匯總函式都可以在 aggregate(...) 階段中做為頂層運算式使用。

名稱 說明
COUNT 傳回文件數量。
COUNT_IF 傳回運算式評估結果為 TRUE 的文件數
COUNT_DISTINCT 傳回不重複的非 NULL 值數量
SUM 傳回所有 NUMERIC 值的總和
AVERAGE 傳回所有 NUMERIC 值的平均值
MINIMUM 傳回非 NULL 的最小值
MAXIMUM 傳回非 NULL 的最大值
FIRST 傳回第一個文件的 expression 值。
LAST 傳回最後一個文件的 expression 值。
ARRAY_AGG 傳回所有輸入值的陣列。
ARRAY_AGG_DISTINCT 傳回所有不重複的輸入值所組成的陣列。

COUNT

語法:

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

說明:

傳回先前階段的文件計數,其中 expression 評估為任何非 NULL 值。如未提供 expression,則會傳回前一階段的文件總數。

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

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

網頁

// 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
Android
// 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
Android
// 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();

COUNT_IF

語法:

count_if(expression: BOOLEAN) -> INT64

說明:

傳回先前階段中 expression 評估為 TRUE 的文件數量。

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

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .aggregate(
        AggregateFunction.countIf(field("rating").greaterThan(4)).alias("filteredCount")
    )
    .execute()
Java
Android
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();

COUNT_DISTINCT

語法:

count_distinct(expression: ANY) -> INT64

說明:

傳回 expression 的不重複非 NULL、非 ABSENT 值數量。

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

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.countDistinct("author").alias("unique_authors"))
    .execute()
Java
Android
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();

SUM

語法:

sum(expression: ANY) -> NUMBER

說明:

傳回所有數值的總和,並忽略非數值。如果任何值為 NaN,則傳回 NaN

輸出內容的型別會與最寬的輸入型別相同,但下列情況除外:

  • 如果 INTEGER 無法以 INTEGER 表示,系統會將其轉換為 DOUBLE
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").sum().as("totalPopulation"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("cities")
    .aggregate(AggregateFunction.sum("population").alias("totalPopulation"))
    .execute()
Java
Android
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();

平均

語法:

average(expression: ANY) -> FLOAT64

說明:

傳回所有數值的平均值,並忽略非數值。 如果任何值為 NaN,則評估結果為 NaN;如果沒有任何數值匯總,則評估結果為 NULL

輸出內容的型別會與輸入型別相同,但下列情況除外:

  • 如果 INTEGER 無法以 INTEGER 表示,系統會將其轉換為 DOUBLE
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").average().as("averagePopulation"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("cities")
    .aggregate(AggregateFunction.average("population").alias("averagePopulation"))
    .execute()
Java
Android
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();

最低

語法:

minimum(expression: ANY) -> ANY

說明:

針對每個文件評估 expression 時,傳回非 NULL、非缺少的最小值。

如果沒有非 NULL、非缺少的任何值,則會傳回 NULL。包括未考慮任何文件的情況。

如果有多個最小值,系統可以傳回其中一個值。值類型排序方式遵循文件排序方式

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

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.minimum("price").alias("minimumPrice"))
    .execute()
Java
Android
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();

MAXIMUM

語法:

maximum(expression: ANY) -> ANY

說明:

針對每份文件評估 expression 時,傳回 expression 的最大非 NULL 值和非缺席值。

如果沒有非 NULL、非缺少的任何值,則會傳回 NULL。包括未考慮任何文件的情況。

如果有多個最大等值,則可以傳回其中任何一個值。值類型排序方式遵循文件排序方式

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

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .aggregate(AggregateFunction.maximum("price").alias("maximumPrice"))
    .execute()
Java
Android
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();

名字

語法:

first(expression: ANY) -> ANY

說明:

傳回第一個傳回的文件中 expression 的值。

姓氏

語法:

last(expression: ANY) -> ANY

說明:

傳回最後一個回傳文件的 expression 值。

ARRAY_AGG

語法:

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

說明:

針對每個文件評估時,傳回包含所有 expression 值的陣列。

如果運算式解析為缺席值,則會轉換為 NULL

輸出陣列中的元素順序不穩定,不應依賴。

ARRAY_AGG_DISTINCT

語法:

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

說明:

針對每份文件評估時,傳回包含所有不重複 expression 值的陣列。

如果運算式解析為缺席值,則會轉換為 NULL

輸出陣列中的元素順序不穩定,不應依賴。

算術函式

Firestore 中的所有算術函式都具有下列行為:

  • 如果任何輸入參數是 NULL,就會評估為 NULL
  • 如果任何引數是 NaN,則評估結果為 NaN
  • 如果發生溢位或下溢,就會產生錯誤。

此外,如果算術函式採用多個不同類型的數字引數 (例如:add(5.0, 6)),Firestore 會隱含地將引數轉換為最廣泛的輸入類型。如果只提供 INT32 輸入,傳回型別會是 INT64

名稱 說明
ABS 傳回 number 的絕對值
ADD 傳回 x + y 的值
SUBTRACT 傳回 x - y 的值
MULTIPLY 傳回 x * y 的值
DIVIDE 傳回 x / y 的值
MOD 傳回 x / y 除以 的餘數。
CEIL 傳回 number 的天花板值
FLOOR 傳回 number 的底數
ROUND number 四捨五入到 places 個小數位數
POW 傳回 base^exponent 的值
SQRT 傳回 number
EXP 傳回歐拉數的 exponent 次方
LN 傳回 number 的自然對數
LOG 傳回以 10 為底的number
LOG10 傳回 number 的對數 (以 10 為底)
RAND 傳回介於 0.0 和 1.0 之間的虛擬隨機浮點數

ABS

語法:

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

說明:

傳回 number 的絕對值。

  • 如果函式會溢位 INT32INT64 值,就會擲回錯誤。

範例:

數字 abs(number)
10 10
-10 10
10L 10L
-0.0 0.0
10.5 10.5
-10.5 10.5
-231 [error]
-263 [error]

新增

語法:

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

說明:

傳回 x + y 的值。

範例:

x y add(x, y)
20 3 23
10.0 1 11.0
22.5 2.0 24.5
INT64.MAX 1 [error]
INT64.MIN -1 [error]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.add(field("soldBooks"), field("unsoldBooks")).alias("totalBooks"))
    .execute()
Java
Android
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();

SUBTRACT

語法:

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

說明:

傳回 x - y 的值。

範例:

x y subtract(x, y)
20 3 17
10.0 1 9.0
22.5 2.0 20.5
INT64.MAX -1 [error]
INT64.MIN 1 [error]
Node.js
const storeCredit = 7;
const result = await db.pipeline()
  .collection("books")
  .select(field("price").subtract(constant(storeCredit)).as("totalCost"))
  .execute();

網頁

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
Android
val storeCredit = 7
val result = db.pipeline()
    .collection("books")
    .select(Expression.subtract(field("price"), storeCredit).alias("totalCost"))
    .execute()
Java
Android
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();

MULTIPLY

語法:

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

說明:

傳回 x * y 的值。

範例:

x y multiply(x, y)
20 3 60
10.0 1 10.0
22.5 2.0 45.0
INT64.MAX 2 [error]
INT64.MIN 2 [error]
FLOAT64.MAX FLOAT64.MAX +inf
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("price").multiply(field("soldBooks")).as("revenue"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.multiply(field("price"), field("soldBooks")).alias("revenue"))
    .execute()
Java
Android
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();

DIVIDE

語法:

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

說明:

傳回 x / y 的值。整數除法會截斷。

範例:

x y divide(x, y)
20 3 6
10.0 3 3.333...
22.5 2 11.25
10 0 [error]
1.0 0.0 +inf
-1.0 0.0 -inf
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("ratings").divide(field("soldBooks")).as("reviewRate"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.divide(field("ratings"), field("soldBooks")).alias("reviewRate"))
    .execute()
Java
Android
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();

MOD

語法:

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

說明:

傳回 x / y 的餘數。

  • 如果整數型別 (INT64) 的 y 為零,則會擲回 error
  • 如果浮點類型 (FLOAT64) 的 y 為零,就會傳回 NaN

範例:

x y 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();

網頁

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
Android
val displayCapacity = 1000
val result = db.pipeline()
    .collection("books")
    .select(Expression.mod(field("unsoldBooks"), displayCapacity).alias("warehousedBooks"))
    .execute()
Java
Android
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();

CEIL

語法:

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

說明:

傳回大於或等於 number 的最小整數值。

範例:

數字 ceil(number)
20 20
10 10
0 0
24L 24L
-0.4 -0.0
0.4 1.0
22.5 23.0
+inf +inf
-inf -inf
Node.js
const booksPerShelf = 100;
const result = await db.pipeline()
  .collection("books")
  .select(
    field("unsoldBooks").divide(constant(booksPerShelf)).ceil().as("requiredShelves")
  )
  .execute();

網頁

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
Android
val booksPerShelf = 100
val result = db.pipeline()
    .collection("books")
    .select(
        Expression.divide(field("unsoldBooks"), booksPerShelf).ceil().alias("requiredShelves")
    )
    .execute()
Java
Android
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();

FLOOR

語法:

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

說明:

傳回不大於 number 的最大整數值。

範例:

數字 floor(number)
20 20
10 10
0 0
2147483648 2147483648
-0.4 -1.0
0.4 0.0
22.5 22.0
+inf +inf
-inf -inf
Node.js
const result = await db.pipeline()
  .collection("books")
  .addFields(
    field("wordCount").divide(field("pages")).floor().as("wordsPerPage")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .addFields(
        Expression.divide(field("wordCount"), field("pages")).floor().alias("wordsPerPage")
    )
    .execute()
Java
Android
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();

ROUND

語法:

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

說明:

number 捨去 places 位數。如果 places 為正數,則會將小數點右側的數字進位或捨去;如果為負數,則會將小數點左側的數字進位或捨去。

  • 如果只提供 number,則會四捨五入至最接近的整數值。
  • 原則為四捨五入。
  • 如果使用負 places 值進行捨入作業時發生溢位,系統會擲回 error

範例:

數字 個地點 round(number, places)
15.5 0 16.0
-15.5 0 -16.0
15 1 15
15 0 15
15 -1 20
15 -2 0
15.48924 1 15.5
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();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(Expression.multiply(field("soldBooks"), field("price")).round().alias("partialRevenue"))
    .aggregate(AggregateFunction.sum("partialRevenue").alias("totalRevenue"))
    .execute()
Java
Android
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();

POW

語法:

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

說明:

傳回 baseexponent 次方。

  • 如果 base <= 0exponent 為負數,則會擲回錯誤。

  • 對於任何 exponentpow(1, exponent) 為 1。

  • 對於任何 basepow(base, 0) 為 1。

範例:

base 指數 pow(base, exponent)
2 3 8.0
2 -3 0.125
+inf 0 1.0
1 +inf 1.0
-1 0.5 [error]
0 -1 [error]
Node.js
const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
  .execute();

網頁

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

SQRT

語法:

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

說明:

傳回 number 的平方根。

  • 如果 number 為負數,則會擲回 error

範例:

數字 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();

網頁

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

匯出

語法:

exp(exponent: FLOAT64) -> FLOAT64

說明:

傳回歐拉數的 exponent 次方值,也稱為自然指數函式。

範例:

指數 exp(exponent)
0.0 1.0
10 e^10 (FLOAT64)
+inf +inf
-inf 0
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").exp().as("expRating"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").exp().alias("expRating"))
    .execute()
Java
Android
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();

LN

語法:

ln(number: FLOAT64) -> FLOAT64

說明:

傳回 number 的自然對數。這個函式等同於 log(number)

範例:

數字 ln(number)
1 0.0
2L 0.693...
1.0 0.0
e (FLOAT64) 1.0
-inf NaN
+inf +inf
x <= 0 [error]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").ln().as("lnRating"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").ln().alias("lnRating"))
    .execute()
Java
Android
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();

LOG

語法:

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

說明:

傳回 number 的對數 (以 base 為底)。

  • 如果只提供 number,則會傳回 numberbase 為底的對數 (與 ln(number) 同義)。

範例:

數字 base log(number, base)
100 10 2.0
-inf Numeric NaN
Numeric +inf NaN
number <= 0 Numeric [error]
Numeric base <= 0 [error]
Numeric 1.0 [error]

LOG10

語法:

log10(x: FLOAT64) -> FLOAT64

說明:

傳回 number10 為底的對數。

範例:

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

RAND

語法:

rand() -> FLOAT64

說明:

Return a pseudo-random floating point number, chosen uniformly between 0.0 (inclusive) and 1.0 (exclusive).

陣列函式

名稱 說明
ARRAY 傳回 ARRAY,其中每個輸入引數都有一個元素
ARRAY_CONCAT 將多個陣列連結成單一ARRAY
ARRAY_CONTAINS 如果指定 ARRAY 包含特定值,則傳回 TRUE
ARRAY_CONTAINS_ALL 如果所有值都存在於 ARRAY 中,則傳回 TRUE
ARRAY_CONTAINS_ANY 如果 ARRAY 中存在任何值,則傳回 TRUE
ARRAY_GET 傳回 ARRAY 中指定索引的元素。
ARRAY_LENGTH 傳回 ARRAY 中的元素數量
ARRAY_REVERSE 反轉 ARRAY 中的元素順序
SUM 傳回 ARRAY 中所有 NUMERIC 值的總和。
JOIN 產生 ARRAY 中元素的串連結果,做為 STRING 值。

ARRAY

語法:

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

說明:

根據指定元素建構陣列。

  • 如果引數不存在,系統會在產生的陣列中以 NULL 取代。

範例:

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

語法:

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

說明:

將兩個以上的陣列串連成單一 ARRAY

範例:

陣列 array_concat(arrays)
([1, 2], [3, 4]) [1, 2, 3, 4]
(["a", "b"], ["c"]) ["a", "b", "c"]
([1]、[2]、[3]) [1, 2, 3]
([], [1, 2]) [1, 2]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("genre").arrayConcat([field("subGenre")]).as("allGenres"))
  .execute();
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("genre").arrayConcat([Field("subGenre")]).as("allGenres")])
  .execute()
Kotlin
Android
val result = db.pipeline()
    .collection("books")
    .select(field("genre").arrayConcat(field("subGenre")).alias("allGenres"))
    .execute()
Java
Android
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();

ARRAY_CONTAINS

語法:

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

說明:

如果在 array 中找到 value,則傳回 TRUE,否則傳回 FALSE

範例:

陣列 array_contains(array, value)
[1, 2, 3] 2 true
[[1, 2], [3]] [1, 2] true
[1, null] null true
"abc" 下列任一項目 錯誤
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("genre").arrayContains(constant("mystery")).as("isMystery"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("genre").arrayContains("mystery").alias("isMystery"))
    .execute()
Java
Android
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();

ARRAY_CONTAINS_ALL

語法:

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

說明:

如果所有 search_values 都位於 array 中,則傳回 TRUE,否則傳回 FALSE

範例:

陣列 search_values array_contains_all(array, search_values)
[1, 2, 3] [1, 2] true
[1, 2, 3] [1, 4] false
[1, null] [null] true
[NaN] [NaN] true
[] [] true
[1, 2, 3] [] true
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("genre")
      .arrayContainsAll([constant("fantasy"), constant("adventure")])
      .as("isFantasyAdventure")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("genre")
            .arrayContainsAll(listOf("fantasy", "adventure"))
            .alias("isFantasyAdventure")
    )
    .execute()
Java
Android
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();

ARRAY_CONTAINS_ANY

語法:

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

說明:

如果 array 中有任何 search_values,則傳回 TRUE,否則傳回 FALSE

範例:

陣列 search_values array_contains_any(array, search_values)
[1, 2, 3] [4, 1] true
[1, 2, 3] [4, 5] false
[1, 2, null] [null] true
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("genre")
      .arrayContainsAny([constant("fantasy"), constant("nonfiction")])
      .as("isMysteryOrFantasy")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("genre")
            .arrayContainsAny(listOf("fantasy", "nonfiction"))
            .alias("isMysteryOrFantasy")
    )
    .execute()
Java
Android
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();

ARRAY_GET

語法:

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

說明:

傳回 array 中以 0 為基準的 index 元素。

  • 如果 index 為負數,系統會從陣列結尾存取元素,其中 -1 為最後一個元素。
  • 如果 array 不是 ARRAY 類型,函式會傳回缺席值。
  • 如果 index 超出範圍,函式會傳回缺席值。
  • 如果 index 不是 INT64 類型,函式會傳回錯誤。

範例:

陣列 索引 array_get(array, index)
[1, 2, 3] 0 1
[1, 2, 3] -1 3
[1, 2, 3] 3 缺席
[1, 2, 3] -4 缺席
"abc" 0 缺席
null 0 缺席
Array 「a」 錯誤
Array 2.0 錯誤

ARRAY_LENGTH

語法:

array_length(array: ARRAY) -> INT64

說明:

傳回 array 中的元素數量。

範例:

陣列 array_length(array)
[1, 2, 3] 3
[] 0
[1, 1, 1] 3
[1, null] 2
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("genre").arrayLength().as("genreCount"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("genre").arrayLength().alias("genreCount"))
    .execute()
Java
Android
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();

ARRAY_REVERSE

語法:

array_reverse(array: ARRAY) -> ARRAY

說明:

反轉指定的 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();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("genre").arrayReverse().alias("reversedGenres"))
    .execute()
    
Java
Android
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();

SUM

語法:

sum(array: ARRAY) -> INT64 | FLOAT64

說明:

傳回 ARRAY 中所有 NUMERIC 值的總和。

  • 系統會忽略陣列中的非數值。
  • 如果陣列中的任何數字值為 NaN,函式會傳回 NaN
  • 傳回型別取決於陣列中最寬的數值型別:INT64 < FLOAT64
  • 如果在加總任何浮點數值之前發生 64 位元整數溢位,系統就會傳回錯誤。如果加總浮點值,溢位會導致 +/- 無限大。
  • 如果陣列完全不含任何數字值,函式會傳回 NULL

範例:

陣列 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] 錯誤
[INT64.MAX_VALUE, 1, -1.0] 錯誤
[INT64.MAX_VALUE, 1.0] 9.223372036854776e+18

加入

語法:

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

說明:

STRING 形式傳回 array 中元素的串連結果。array 可以是 STRINGBYTES 資料類型。

  • arraydelimiternull_text 中的所有元素必須是相同類型,也就是必須全為 STRING 或全為 BYTES
  • 如果提供 null_textarray 中的任何 NULL 值都會取代為 null_text
  • 如未提供 null_text,系統會從結果中省略 array 中的 NULL 值。

範例:

如果未提供 null_text

陣列 delimiter 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'] "," 錯誤
["a", "c"] b',' 錯誤
[b'a', b'c'] "," 錯誤

如果提供 null_text

陣列 delimiter 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' 錯誤
[b'a', null] b',' 「N」 錯誤

比較函式

名稱 說明
EQUAL 相等比較
GREATER_THAN 大於比較
GREATER_THAN_OR_EQUAL 大於或等於比較
LESS_THAN 小於比較結果
LESS_THAN_OR_EQUAL 小於或等於比較
NOT_EQUAL 不等於比較

EQUAL

語法:

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

範例:

x y equal(x, y)
1L 1L TRUE
1.0 1L TRUE
-1.0 1L FALSE
NaN NaN TRUE
NULL NULL TRUE
NULL ABSENT FALSE

說明:

如果 xy 相等,則傳回 TRUE,否則傳回 FALSE

Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").equal(5).as("hasPerfectRating"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").equal(5).alias("hasPerfectRating"))
    .execute()
Java
Android
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();

GREATER_THAN

語法:

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

說明:

如果 x 大於 y,則傳回 TRUE,否則傳回 FALSE

如果 xy 無法比較,則傳回 FALSE

範例:

x y greater_than(x, y)
1L 0.0 TRUE
1L 1L FALSE
1L 2L FALSE
"foo" 0L FALSE
0L "foo" FALSE
NaN 0L FALSE
0L NaN FALSE
NULL NULL FALSE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").greaterThan(4).as("hasHighRating"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").greaterThan(4).alias("hasHighRating"))
    .execute()
Java
Android
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();

GREATER_THAN_OR_EQUAL

語法:

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

說明:

如果 x 大於或等於 y,則傳回 TRUE,否則傳回 FALSE

如果 xy 無法比較,則傳回 FALSE

範例:

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 0L FALSE
0L NaN FALSE
NULL NULL TRUE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("published").greaterThanOrEqual(1900).as("publishedIn20thCentury"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("published").greaterThanOrEqual(1900).alias("publishedIn20thCentury"))
    .execute()
Java
Android
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();

LESS_THAN

語法:

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

說明:

如果 x 小於 y,則會傳回 TRUE,否則會傳回 FALSE

如果 xy 無法比較,則傳回 FALSE

範例:

x y less_than(x, y)
1L 0.0 FALSE
1L 1L FALSE
1L 2L TRUE
"foo" 0L FALSE
0L "foo" FALSE
NaN 0L FALSE
0L NaN FALSE
NULL NULL FALSE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("published").lessThan(1923).as("isPublicDomainProbably"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("published").lessThan(1923).alias("isPublicDomainProbably"))
    .execute()
Java
Android
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();

LESS_THAN_OR_EQUAL

語法:

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

說明:

如果 x 小於或等於 y,則傳回 TRUE,否則傳回 FALSE

如果 xy 無法比較,則傳回 FALSE

範例:

x y less_than(x, y)
1L 0.0 FALSE
1L 1L TRUE
1L 2L TRUE
"foo" 0L FALSE
0L "foo" FALSE
NaN 0L FALSE
0L NaN FALSE
NULL NULL TRUE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").lessThanOrEqual(2).as("hasBadRating"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("rating").lessThanOrEqual(2).alias("hasBadRating"))
    .execute()
Java
Android
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();

NOT_EQUAL

語法:

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

說明:

如果 x 不等於 y,則傳回 TRUE,否則傳回 FALSE

範例:

x y not_equal(x, y)
1L 1L FALSE
1.0 1L FALSE
-1.0 1L TRUE
NaN 0L TRUE
NaN NaN FALSE
NULL NULL FALSE
NULL ABSENT TRUE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("title").notEqual("1984").as("not1984"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("title").notEqual("1984").alias("not1984"))
    .execute()
Java
Android
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();

偵錯函式

名稱 說明
EXISTS 如果值不是缺席值,則傳回 TRUE
IS_ABSENT 如果值為缺席值,則傳回 TRUE
IF_ABSENT 如果值不存在,則以運算式取代
IS_ERROR 擷取並檢查基礎運算式是否擲回錯誤
IF_ERROR 如果值擲回錯誤,則以運算式取代該值

EXISTS

語法:

exists(value: ANY) -> BOOLEAN

說明:

如果 value 不是缺席值,則傳回 TRUE

範例:

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

網頁

範例:

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
Android

範例:

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

範例:

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

IS_ABSENT

語法:

is_absent(value: ANY) -> BOOLEAN

說明:

如果 value 是缺席值,則傳回 TRUE,否則傳回 FALSE。缺少的輸入值 (例如缺少文件欄位)。

範例:

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

IF_ABSENT

語法:

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

說明:

如果 value 是缺席值,則會評估並傳回 replacement。否則會傳回 value

範例:

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

IS_ERROR

語法:

is_error(try: ANY) -> BOOLEAN

說明:

如果在評估 try 時擲回錯誤,則傳回 TRUE。如果是其他情況,則傳回 FALSE

IF_ERROR

語法:

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

說明:

如果在評估 try 時擲回錯誤,則會評估並傳回 replacement。否則會傳回 try 的已解析值。

邏輯函式

名稱 說明
AND 執行邏輯 AND
OR 執行邏輯 OR
XOR 執行邏輯 XOR
NOT 執行邏輯 NOT
CONDITIONAL 根據條件運算式評估分支。
EQUAL_ANY 檢查值是否等於陣列中的任何元素
NOT_EQUAL_ANY 檢查值是否不等於陣列中的任何元素
MAXIMUM 傳回一組值中的最大值
MINIMUM 傳回一組值中的最小值

語法:

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

說明:

傳回兩個以上布林值的邏輯 AND。

如果由於任何指定值為 ABSENTNULL 而無法推導出結果,則會傳回 NULL

範例:

x y and(x, y)
TRUE TRUE TRUE
FALSE TRUE FALSE
NULL TRUE NULL
ABSENT TRUE NULL
NULL FALSE FALSE
FALSE ABSENT FALSE
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    and(field("rating").greaterThan(4), field("price").lessThan(10))
      .as("under10Recommendation")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        Expression.and(field("rating").greaterThan(4),
          field("price").lessThan(10))
            .alias("under10Recommendation")
    )
    .execute()
Java
Android
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();

語法:

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

說明:

傳回兩個以上布林值的邏輯 OR。

如果由於任何指定值為 ABSENTNULL 而無法推導出結果,則會傳回 NULL

範例:

x y or(x, y)
TRUE TRUE TRUE
FALSE TRUE TRUE
NULL TRUE TRUE
ABSENT TRUE TRUE
NULL FALSE NULL
FALSE ABSENT NULL
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    or(field("genre").equal("Fantasy"), field("tags").arrayContains("adventure"))
      .as("matchesSearchFilters")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        Expression.or(field("genre").equal("Fantasy"),
          field("tags").arrayContains("adventure"))
            .alias("matchesSearchFilters")
    )
    .execute()
Java
Android
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();

XOR

語法:

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

說明:

傳回兩個以上布林值的邏輯 XOR。

如果任何指定值為 ABSENTNULL,則傳回 NULL

範例:

x y xor(x, y)
TRUE TRUE FALSE
FALSE FALSE FALSE
FALSE TRUE TRUE
NULL TRUE NULL
ABSENT TRUE NULL
NULL FALSE NULL
FALSE ABSENT NULL
Node.js
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    xor(field("tags").arrayContains("magic"), field("tags").arrayContains("nonfiction"))
      .as("matchesSearchFilters")
  )
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        Expression.xor(field("tags").arrayContains("magic"),
          field("tags").arrayContains("nonfiction"))
            .alias("matchesSearchFilters")
    )
    .execute()
Java
Android
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();

NOT

語法:

not(x: BOOLEAN) -> BOOLEAN

說明:

傳回布林值的邏輯 NOT。

Node.js
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("tags").arrayContains("nonfiction").not()
      .as("isFiction")
  )
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        Expression.not(
            field("tags").arrayContains("nonfiction")
        ).alias("isFiction")
    )
    .execute()
Java
Android
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();

CONDITIONAL

語法:

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

說明:

如果 condition 評估為 TRUE,則評估並傳回 true_case

如果條件解析為 FALSENULLABSENT 值,則評估並傳回 false_case

範例:

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")
  )
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("tags").arrayConcat(
            Expression.conditional(
                field("pages").greaterThan(100),
                constant("longRead"),
                constant("shortRead")
            )
        ).alias("extendedTags")
    )
    .execute()
Java
Android
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();

EQUAL_ANY

語法:

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

說明:

如果 value 位於 search_space 陣列中,則傳回 TRUE

範例:

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 [1L, NaN, 3L] TRUE
Node.js
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("genre").equalAny(["Science Fiction", "Psychological Thriller"])
      .as("matchesGenreFilters")
  )
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("genre").equalAny(listOf("Science Fiction", "Psychological Thriller"))
            .alias("matchesGenreFilters")
    )
    .execute()
Java
Android
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();

NOT_EQUAL_ANY

語法:

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

說明:

如果 value 不在 search_space 陣列中,則傳回 TRUE

範例:

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 [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")
  )
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("author").notEqualAny(listOf("George Orwell", "F. Scott Fitzgerald"))
            .alias("byExcludedAuthors")
    )
    .execute()
Java
Android
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();

MAXIMUM

語法:

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

說明:

傳回一系列值 x 中的最大非 NULL、非 ABSENT 值。

如果沒有非 NULL 和非 ABSENT 的值,則會傳回 NULL

如果有多個最大等值,則可以傳回其中任何一個值。值類型排序方式遵循文件排序方式

範例:

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"))
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("rating").logicalMaximum(1).alias("flooredRating")
    )
    .execute()
Java
Android
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();

最低

語法:

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

說明:

傳回一系列值 x 中的最小非 NULL、非 ABSENT 值。

如果沒有非 NULL 和非 ABSENT 的值,則會傳回 NULL

如果有多個最小值,系統可以傳回其中一個值。值類型排序方式遵循文件排序方式

範例:

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"))
);

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("rating").logicalMinimum(5).alias("cappedRating")
    )
    .execute()
Java
Android
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();

地圖函式

名稱 說明
MAP 從一系列鍵/值組合建構對應值
MAP_GET 傳回對應中指定鍵的值
MAP_SET 傳回地圖副本,其中包含一系列更新的金鑰
MAP_REMOVE 傳回地圖副本,並移除一系列鍵
MAP_MERGE 將一系列地圖合併在一起。
CURRENT_CONTEXT 以對映形式傳回目前環境。
MAP_KEYS 傳回對應項目中所有鍵的陣列。
MAP_VALUES 傳回對應中所有值的陣列。
MAP_ENTRIES 傳回對應的鍵/值組合陣列。

地圖

語法:

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

說明:

從一系列鍵/值組合建構對應。

MAP_GET

語法:

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

說明:

傳回對應中指定索引鍵的值。如果對應中沒有 key,或 map 引數不是 MAP,則傳回 ABSENT 值。

Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("awards").mapGet("pulitzer").as("hasPulitzerAward")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("awards").mapGet("pulitzer").alias("hasPulitzerAward")
    )
    .execute()
Java
Android
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();

MAP_SET

語法:

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

說明:

傳回 map 值的副本,並以一系列鍵/值組合更新其內容。

如果指定值解析為缺席值,系統會從對應中移除相關聯的鍵。

如果 map 引數不是 MAP,則傳回缺席值。

MAP_REMOVE

語法:

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

說明:

傳回 map 值的副本,並移除一系列鍵。

MAP_MERGE

語法:

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

合併 2 個以上對應項目的內容。如果多個對應具有衝突的值,系統會使用最後一個值。

CURRENT_CONTEXT

語法:

current_context() -> MAP

傳回的地圖包含目前執行點的所有可用欄位。

MAP_KEYS

語法:

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

說明:

傳回包含 map 值所有鍵的陣列。

MAP_VALUES

語法:

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

說明:

傳回包含 map 值所有值的陣列。

MAP_ENTRIES

語法:

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

說明:

傳回包含 map 值中所有鍵/值組合的陣列。

每個鍵/值組合都會以對應的形式呈現,並包含兩個項目:kv

範例:

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

字串函式

名稱 說明
BYTE_LENGTH 傳回 STRINGBYTES 值中的 BYTES 數量
CHAR_LENGTH 傳回 STRING 值中的 Unicode 字元數
STARTS_WITH 如果 STRING 以指定前置字元開頭,則傳回 TRUE
ENDS_WITH 如果 STRING 以指定後置字串結尾,則傳回 TRUE
LIKE 如果 STRING 符合模式,則傳回 TRUE
REGEX_CONTAINS 如果值與規則運算式部分或完全相符,則傳回 TRUE
REGEX_MATCH 如果值中任何部分與規則運算式相符,則傳回 TRUE
STRING_CONCAT 將多個 STRING 串連成一個 STRING
STRING_CONTAINS 如果值包含 STRING,則傳回 TRUE
TO_UPPER STRINGBYTES 值轉換為大寫。
TO_LOWER STRINGBYTES 值轉換為小寫。
SUBSTRING 取得 STRINGBYTES 值的子字串。
STRING_REVERSE 反轉 STRINGBYTES 值。
TRIM STRINGBYTES 值中移除開頭和結尾字元。
SPLIT STRINGBYTES 值分割為陣列。

BYTE_LENGTH

語法:

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

說明:

傳回 STRINGBYTES 值中的 BYTES 數量。

範例:

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

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("title").byteLength().alias("titleByteLength")
    )
    .execute()
Java
Android
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();

CHAR_LENGTH

語法:

char_length(value: STRING) -> INT64

說明:

傳回 STRING 值中的 Unicode 碼位數。

範例:

char_length(value)
"abc" 3
「你好」。 5
"world" 5
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").charLength().as("titleCharLength")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("title").charLength().alias("titleCharLength")
    )
    .execute()
Java
Android
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();

STARTS_WITH

語法:

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

說明:

如果 valueprefix 開頭,則傳回 TRUE

範例:

前置字串 starts_with(value, prefix)
"abc" 「a」 true
"abc" "b" false
"abc" "" true
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("title").startsWith("The")
            .alias("needsSpecialAlphabeticalSort")
    )
    .execute()
Java
Android
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();

ENDS_WITH

語法:

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

說明:

如果 value 結尾為 postfix,則傳回 TRUE

範例:

postfix ends_with(value, postfix)
"abc" 「c」 true
"abc" "b" false
"abc" "" true
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
Android
val result = db.pipeline()
    .collection("inventory/devices/laptops")
    .select(
        field("name").endsWith("16 inch")
            .alias("16InLaptops")
    )
    .execute()
Java
Android
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();

喜歡

語法:

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

說明:

如果 valuepattern 相符,則傳回 TRUE

範例:

圖案 like(value, pattern)
「Firestore」 「Fire%」 true
「Firestore」 「%store」 true
「Datastore」 「Data_tore」 true
「100%」 「100\%」 true
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("genre").like("%Fiction")
      .as("anyFiction")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("genre").like("%Fiction")
            .alias("anyFiction")
    )
    .execute()
Java
Android
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();

REGEX_CONTAINS

語法:

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

說明:

如果 value 的部分內容與 pattern 相符,就會傳回 TRUE。如果 pattern 不是有效的規則運算式,這個函式會傳回 error

規則運算式遵循 re2 程式庫的語法。

範例:

圖案 regex_contains(value, pattern)
「Firestore」 「Fire」 true
「Firestore」 「store$" true
「Firestore」 "data" false
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("title").regexContains("Firestore (Enterprise|Standard)")
            .alias("isFirestoreRelated")
    )
    .execute()
Java
Android
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();

REGEX_MATCH

語法:

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

說明:

如果 valuepattern 完全相符,則會傳回 TRUE。如果 pattern 不是有效的規則運算式,這個函式會傳回 error

規則運算式遵循 re2 程式庫的語法。

範例:

圖案 regex_match(value, pattern)
「Firestore」 「F.*store」 true
「Firestore」 「Fire」 false
「Firestore」 "^F.*e$" true
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("title").regexMatch("Firestore (Enterprise|Standard)")
      .as("isFirestoreExactly")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("title").regexMatch("Firestore (Enterprise|Standard)")
            .alias("isFirestoreExactly")
    )
    .execute()
Java
Android
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();

STRING_CONCAT

語法:

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

說明:

將兩個以上STRING值串連成單一結果。

範例:

引數 string_concat(values...)
() 錯誤
("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();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("title").concat(" by ", field("author"))
            .alias("fullyQualifiedTitle")
    )
    .execute()
Java
Android
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();

STRING_CONTAINS

語法:

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

說明:

檢查 value 是否包含字串常值 substring

範例:

子字串 string_contains(value, substring)
"abc" "b" true
"abc" 「d」 false
"abc" "" true
"a.c" "." true
「☃☃☃」 「☃」 true
Node.js
const result = await db.pipeline()
  .collection("articles")
  .select(
    field("body").stringContains("Firestore")
      .as("isFirestoreRelated")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("articles")
    .select(
        field("body").stringContains("Firestore")
            .alias("isFirestoreRelated")
    )
    .execute()
Java
Android
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();

TO_UPPER

語法:

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

說明:

STRINGBYTES 值轉換為大寫。

如果位元組或字元不對應至 UTF-8 小寫英文字母,則會以未變更的形式傳遞。

範例:

to_upper(value)
"abc" 「ABC」
「AbC」 「ABC」
b"abc" b"ABC"
b"a1c" b"A1C"
Node.js
const result = await db.pipeline()
  .collection("authors")
  .select(
    field("name").toUpper()
      .as("uppercaseName")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("authors")
    .select(
        field("name").toUpper()
            .alias("uppercaseName")
    )
    .execute()
Java
Android
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();

TO_LOWER

語法:

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

說明:

STRINGBYTES 值轉換為小寫。

如果位元組或字元不對應至 UTF-8 大寫英文字母,則會保持不變。

範例:

to_lower(value)
「ABC」 "abc"
「AbC」 "abc"
「A1C」 「a1c」
b"ABC" b"abc"
Node.js
const result = await db.pipeline()
  .collection("authors")
  .select(
    field("genre").toLower().equal("fantasy")
      .as("isFantasy")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("authors")
    .select(
        field("genre").toLower().equal("fantasy")
            .alias("isFantasy")
    )
    .execute()
Java
Android
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();

SUBSTRING

語法:

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

說明:

傳回 input 的子字串,從 position (從零開始計算的索引) 開始,最多包含 length 個項目。如果未提供 length,則傳回從 positioninput 結尾的子字串。

  • 如果 inputSTRING 值,則 positionlength 會以 Unicode 碼點為單位。如果是 BYTES 值,則以位元組為單位。

  • 如果 position 大於 input 的長度,系統會傳回空白子字串。如果 position 加上 length 大於 input 的長度,子字串會截斷至 input 的結尾。

  • 如果 position 為負數,位置會從輸入內容的結尾開始計算。如果負數 position 大於輸入內容的大小,位置會設為零。length 不得為負數。

範例:

如果未提供 length

輸入 位置 substring(input, position)
"abc" 0 "abc"
"abc" 1 "bc"
"abc" 3 ""
"abc" -1 「c」
b"abc" 1 b"bc"

如果提供 length

輸入 位置 長度 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();

網頁

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

STRING_REVERSE

語法:

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

說明:

以相反順序傳回提供的輸入內容。

如果輸入內容為 STRING,系統會以 Unicode 碼位劃分字元;如果輸入內容為 BYTES 值,系統則會以位元組劃分字元。

範例:

輸入 string_reverse(input)
"abc" "cba"
"a🌹b" "b🌹a"
「你好」。 「olleh」
b"abc" b"cba"
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("name").reverse().as("reversedName")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("name").reverse().alias("reversedName")
    )
    .execute()
Java
Android
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();

TRIM

語法:

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

說明:

從提供的 input 開頭和結尾,修剪一組指定的 BYTESCHARS

  • 如果未提供 values_to_trim,則會修剪空白字元。

範例:

如果未提供 values_to_trim

輸入 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"

如果提供 values_to_trim

輸入 values_to_trim trim(input, values_to_trim)
"abcbfooaacb" "abc" "foo"
"abcdaabadbac" "abc" "daabad"
b"C1C2C3" b"C1" b"C2C3"
b"C1C2" "foo" 錯誤
"foo" b"C1" 錯誤

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("name").trim().alias("whitespaceTrimmedName")
    )
    .execute()
Java
Android
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();

SPLIT

語法:

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

說明:

使用分隔符號拆分 STRINGBYTES 值。

  • 對於 STRING,預設分隔符號是逗號 ,。分隔符號會視為單一字串。

  • 對於 BYTES,您必須指定分隔符號。

  • 以空的分隔符號分割時,STRING 值會產生 Unicode 碼位陣列,BYTES 值則會產生 BYTES 陣列。

  • 分割空的 STRING 會傳回帶有單一空白 STRINGARRAY

範例:

如果未提供 delimiter

輸入 split(input)
「foo,bar,foo」 ["foo", "bar", "foo"]
"foo" ["foo"]
",foo," ["", "foo", ""]
"" [""]
b"C120C2C4" 錯誤

如果提供 delimiter

輸入 delimiter 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"]
b"ABC" b"" [b"A", b"B", b"C"]
"foo" b"C1" 錯誤

時間戳記函式

名稱 說明
CURRENT_TIMESTAMP 產生與要求時間相應的 TIMESTAMP
TIMESTAMP_TRUNC TIMESTAMP 截斷至指定精細程度。
UNIX_MICROS_TO_TIMESTAMP 將自 1970-01-01 00:00:00 UTC 算起的微秒數轉換為 TIMESTAMP
UNIX_MILLIS_TO_TIMESTAMP 將自 1970-01-01 00:00:00 UTC 起算的毫秒數轉換為 TIMESTAMP
UNIX_SECONDS_TO_TIMESTAMP 將自 1970-01-01 00:00:00 UTC 起的秒數轉換為 TIMESTAMP
TIMESTAMP_ADD TIMESTAMP 中加上時間間隔
TIMESTAMP_SUB TIMESTAMP 中減去時間間隔
TIMESTAMP_TO_UNIX_MICROS TIMESTAMP 轉換為自 1970-01-01 00:00:00 UTC 算起的微秒數
TIMESTAMP_TO_UNIX_MILLIS TIMESTAMP 轉換為自 1970-01-01 00:00:00 UTC 算起的毫秒數
TIMESTAMP_TO_UNIX_SECONDS TIMESTAMP 轉換為自 1970-01-01 00:00:00 UTC 以來的秒數

CURRENT_TIMESTAMP

語法:

current_timestamp() -> TIMESTAMP

說明:

取得要求時間 input 開始時的時間戳記 (解讀為自 1970-01-01 00:00:00 UTC 起算的微秒數)。

這在查詢中是穩定的,多次呼叫時一律會解析為相同的值。

TIMESTAMP_TRUNC

語法:

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

說明:

將時間戳記截斷至指定精細程度。

granularity 引數必須是字串,且為下列其中一項:

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

如果提供 timezone 引數,系統會根據指定時區的日曆界線進行截斷 (例如,如果截斷單位是天,系統會截斷至指定時區的午夜)。截斷時間時會考量日光節約時間。

如未提供 timezone,系統會根據 UTC 日曆界線截斷。

timezone 引數應為 tz 資料庫中時區的字串表示法,例如 America/New_York。您也可以指定 GMT 的偏移量,使用自訂時間偏移量。

範例:

timestamp granularity timezone timestamp_trunc(timestamp, granularity, timezone)
2000-01-01 10:20:30:123456 UTC 「second」 未提供 2001-01-01 10:20:30 UTC
1997-05-31 04:30:30 UTC "day" 未提供 1997-05-31 00:00:00 UTC
1997-05-31 04:30:30 UTC "day" 「America/Los_Angeles」 1997-05-30 07:00:00 UTC
2001-03-16 04:00:00 UTC 「week(friday) 未提供 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
2026-01-24 20:00:00 UTC 「month」 「GMT+06:32:43」 2026-01-01T06:32:43 UTC

UNIX_MICROS_TO_TIMESTAMP

語法:

unix_micros_to_timestamp(input: INT64) -> TIMESTAMP

說明:

input (解讀為自 1970-01-01 00:00:00 UTC 算起的微秒數) 轉換為 TIMESTAMP。如果 input 無法轉換為有效的 TIMESTAMP,則會擲回 error

範例:

input unix_micros_to_timestamp(input)
0L 1970-01-01 00:00:00 UTC
400123456L 1970-01-01 00:06:40.123456 UTC
-1000000L 1969-12-31 23:59:59 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtMicros").unixMicrosToTimestamp().alias("createdAtString")
    )
    .execute()
Java
Android
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();

UNIX_MILLIS_TO_TIMESTAMP

語法:

unix_millis_to_timestamp(input: INT64) -> TIMESTAMP

說明:

input (解讀為自 1970-01-01 00:00:00 UTC 算起的毫秒數) 轉換為 TIMESTAMP。如果 input 無法轉換為有效的 TIMESTAMP,則會擲回 error

範例:

input unix_millis_to_timestamp(input)
0L 1970-01-01 00:00:00 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();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtMillis").unixMillisToTimestamp().alias("createdAtString")
    )
    .execute()
Java
Android
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();

UNIX_SECONDS_TO_TIMESTAMP

語法:

unix_seconds_to_timestamp(input: INT64) -> TIMESTAMP

說明:

input (解讀為自 1970-01-01 00:00:00 UTC 算起的秒數) 轉換為 TIMESTAMP。如果 input 無法轉換為有效的 TIMESTAMP,則會擲回 error

範例:

input unix_seconds_to_timestamp(input)
0L 1970-01-01 00:00:00 UTC
60L 世界標準時間 1970-01-01 00:01:00
-300L 1969-12-31 23:55:00 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAtSeconds").unixSecondsToTimestamp().alias("createdAtString")
    )
    .execute()
Java
Android
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();

TIMESTAMP_ADD

語法:

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

說明:

timestamp 新增 unitamountamount 引數可以是負數,在這種情況下,這相當於 TIMESTAMP_SUB

unit 引數必須是字串,且為下列其中一項:

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

如果產生的時間戳記不符合 TIMESTAMP 範圍,就會擲回錯誤。

範例:

timestamp unit amount timestamp_add(timestamp, unit, amount)
2025-02-20 00:00:00 UTC 「minute」 2L 2025-02-20 00:02:00 UTC
2025-02-20 00:00:00 UTC 「hour」 -4L 2025-02-19 20:00:00 UTC
2025-02-20 00:00:00 UTC "day" 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();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("createdAt")
          .timestampAdd("day", 3653)
          .alias("expiresAt")
    )
    .execute()
Java
Android
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();

TIMESTAMP_SUB

語法:

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

說明:

timestamp 減去 unitamountamount 引數可以是負數,在這種情況下,這相當於 TIMESTAMP_ADD

unit 引數必須是字串,且為下列其中一項:

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

如果產生的時間戳記不符合 TIMESTAMP 範圍,就會擲回錯誤。

範例:

timestamp unit amount timestamp_sub(timestamp, unit, amount)
2026-07-04 00:00:00 UTC 「minute」 40L 2026-07-03 23:20:00 UTC
2026-07-04 00:00:00 UTC 「hour」 -24L 2026-07-05 00:00:00 UTC
2026-07-04 00:00:00 UTC "day" 3L 2026-07-01 00:00:00 UTC
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("expiresAt")
          .timestampSubtract("day", 14)
          .alias("sendWarningTimestamp")
    )
    .execute()
Java
Android
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();

TIMESTAMP_TO_UNIX_MICROS

語法:

timestamp_to_unix_micros(input: TIMESTAMP) -> INT64

說明:

input 轉換為自 1970-01-01 00:00:00 UTC 算起的微秒數。會將較高層級的精確度向下捨入至微秒的開頭。

範例:

input timestamp_to_unix_micros(input)
1970-01-01 00:00:00 UTC 0L
1970-01-01 00:06:40.123456 UTC 400123456L
1969-12-31 23:59:59 UTC -1000000L
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMicros().as("unixMicros")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixMicros().alias("unixMicros")
    )
    .execute()
Java
Android
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();

TIMESTAMP_TO_UNIX_MILLIS

語法:

timestamp_to_unix_millis(input: TIMESTAMP) -> INT64

說明:

input 轉換為自 1970-01-01 00:00:00 UTC 算起的毫秒數。會截斷較高層級的精確度,並向下捨入至毫秒的開頭。

範例:

input timestamp_to_unix_millis(input)
1970-01-01 00:00:00 UTC 0L
1970-01-01 01:06:40.123 UTC 4000123L
1969-12-31 23:43:20 -1000000L
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMillis().as("unixMillis")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixMillis().alias("unixMillis")
    )
    .execute()
Java
Android
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();

TIMESTAMP_TO_UNIX_SECONDS

語法:

timestamp_to_unix_seconds(input: TIMESTAMP) -> INT64

說明:

input 轉換為自 1970-01-01 00:00:00 UTC 起的秒數。將較高層級的精確度向下捨入至秒數開頭,藉此截斷較高層級的精確度。

範例:

input timestamp_to_unix_seconds(input)
1970-01-01 00:00:00 UTC 0L
世界標準時間 1970-01-01 00:01:00 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();

網頁

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
Android
val result = db.pipeline()
    .collection("documents")
    .select(
        field("dateString").timestampToUnixSeconds().alias("unixSeconds")
    )
    .execute()
Java
Android
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();
## **類型函式**
名稱 說明
TYPE STRING 形式傳回值的型別。
### TYPE **語法:** ```none type(input: ANY) -> STRING ``` **說明:** 傳回 `input` 型別的字串表示法。 如果提供的值不存在,則會傳回 `NULL`。 **範例:** | `input` | `type(input)` | |---|---| | NULL | "null" | | true | "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" | | ABSENT | NULL | **用戶端範例**
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("title").notEqual("1984").as("not1984"))
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(field("title").notEqual("1984").alias("not1984"))
    .execute()
Java
Android
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();

向量函式

名稱 說明
COSINE_DISTANCE 傳回兩個向量之間的餘弦距離
DOT_PRODUCT 傳回兩個向量之間的點積
EUCLIDEAN_DISTANCE 傳回兩個向量之間的歐幾里得距離
MANHATTAN_DISTANCE 傳回兩個向量之間的曼哈頓距離
VECTOR_LENGTH 傳回向量中的元素數量

COSINE_DISTANCE

語法:

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

說明:

傳回 xy 之間的餘弦距離。

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

網頁

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

DOT_PRODUCT

語法:

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

說明:

傳回 xy 的點積。

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

網頁

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

EUCLIDEAN_DISTANCE

語法:

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

說明:

計算 xy 之間的歐幾里得距離。

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

網頁

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

MANHATTAN_DISTANCE

語法:

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

說明:

計算 xy 之間的曼哈頓距離。

VECTOR_LENGTH

語法:

vector_length(vector: VECTOR) -> INT64

說明:

傳回 VECTOR 中的元素數。

Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("embedding").vectorLength().as("vectorLength")
  )
  .execute();

網頁

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
Android
val result = db.pipeline()
    .collection("books")
    .select(
        field("embedding").vectorLength().alias("vectorLength")
    )
    .execute()
Java
Android
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();

後續步驟