Riferimento per tutte le funzioni

Aggregate

Tutte le funzioni di aggregazione possono essere utilizzate come espressioni di primo livello nella fase aggregate(...).

Nome Descrizione
COUNT Restituisce il numero di documenti.
COUNT_IF Restituisce il conteggio dei documenti in cui un'espressione restituisce TRUE
COUNT_DISTINCT Restituisce il conteggio dei valori univoci e non NULL
SUM Restituisce la somma di tutti i valori di NUMERIC
AVERAGE Restituisce la media di tutti i valori di NUMERIC
MINIMUM Restituisce il valore minimo diverso da NULL
MAXIMUM Restituisce il valore massimo non NULL
FIRST Restituisce il valore expression per il primo documento.
LAST Restituisce il valore expression per l'ultimo documento.
ARRAY_AGG Restituisce un array di tutti i valori di input.
ARRAY_AGG_DISTINCT Restituisce un array di tutti i valori di input distinti.

COUNT

Sintassi:

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

Descrizione:

Restituisce il conteggio dei documenti della fase precedente in cui expression restituisce un valore diverso da NULL. Se non viene fornito alcun expression, restituisce il conteggio totale dei documenti della fase precedente.

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

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

Web

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

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

// Number of books with nonnull `ratings` field
let countField = try await db.pipeline()
  .collection("books")
  .aggregate([Field("ratings").count().as("count")])
  .execute()
Kotlin
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

Sintassi:

count_if(expression: BOOLEAN) -> INT64

Descrizione:

Restituisce il numero di documenti della fase precedente in cui expression restituisce TRUE.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(
    field("rating").greaterThan(4).countIf().as("filteredCount")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([
    AggregateFunction("count_if", [Field("rating").greaterThan(4)]).as("filteredCount")
  ])
  .execute()
Kotlin
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

Sintassi:

count_distinct(expression: ANY) -> INT64

Descrizione:

Restituisce il numero di valori univoci non NULL e non ABSENT di expression.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("author").countDistinct().as("unique_authors"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([AggregateFunction("count_distinct", [Field("author")]).as("unique_authors")])
  .execute()
Kotlin
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

Sintassi:

sum(expression: ANY) -> NUMBER

Descrizione:

Restituisce la somma di tutti i valori numerici, ignorando i valori non numerici. Restituisce NaN se uno dei valori è NaN.

L'output avrà lo stesso tipo del tipo di input più ampio, tranne nei seguenti casi:

  • Un INTEGER verrà convertito in un DOUBLE se non può essere rappresentato come INTEGER.
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").sum().as("totalPopulation"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("cities")
  .aggregate(field("population").sum().as("totalPopulation"))
);
Swift
let result = try await db.pipeline()
  .collection("cities")
  .aggregate([Field("population").sum().as("totalPopulation")])
  .execute()
Kotlin
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();

MEDIA

Sintassi:

average(expression: ANY) -> FLOAT64

Descrizione:

Restituisce la media di tutti i valori numerici, ignorando i valori non numerici. Restituisce NaN se uno dei valori è NaN o NULL se non vengono aggregati valori numerici.

L'output avrà lo stesso tipo dell'input, tranne nei seguenti casi:

  • Un INTEGER verrà convertito in un DOUBLE se non può essere rappresentato come INTEGER.
Node.js
const result = await db.pipeline()
  .collection("cities")
  .aggregate(field("population").average().as("averagePopulation"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("cities")
  .aggregate(field("population").average().as("averagePopulation"))
);
Swift
let result = try await db.pipeline()
  .collection("cities")
  .aggregate([Field("population").average().as("averagePopulation")])
  .execute()
Kotlin
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

Sintassi:

minimum(expression: ANY) -> ANY

Descrizione:

Restituisce il valore minimo non NULL e non assente di expression quando viene valutato su ogni documento.

Se non sono presenti valori non NULL e non assenti, viene restituito NULL. Ciò include i casi in cui non vengono presi in considerazione documenti.

Se sono presenti più valori minimi equivalenti, può essere restituito uno qualsiasi di questi valori. L'ordinamento dei tipi di valore segue l'ordinamento documentato.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").minimum().as("minimumPrice"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([Field("price").minimum().as("minimumPrice")])
  .execute()
Kotlin
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();

MASSIMO

Sintassi:

maximum(expression: ANY) -> ANY

Descrizione:

Restituisce il valore massimo non NULL e non assente di expression quando viene valutato su ogni documento.

Se non sono presenti valori non NULL e non assenti, viene restituito NULL. Ciò include i casi in cui non vengono presi in considerazione documenti.

Se esistono più valori equivalenti massimi, può essere restituito uno qualsiasi di questi valori. L'ordinamento dei tipi di valore segue l'ordinamento documentato.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").maximum().as("maximumPrice"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .aggregate([Field("price").maximum().as("maximumPrice")])
  .execute()
Kotlin
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();

PRIMO

Sintassi:

first(expression: ANY) -> ANY

Descrizione:

Restituisce il valore di expression per il primo documento restituito.

ULTIMO

Sintassi:

last(expression: ANY) -> ANY

Descrizione:

Restituisce il valore di expression per l'ultimo documento restituito.

ARRAY_AGG

Sintassi:

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

Descrizione:

Restituisce un array contenente tutti i valori di expression quando viene valutato su ogni documento.

Se l'espressione viene risolta in un valore assente, viene convertita in NULL.

L'ordine degli elementi nell'array di output non è stabile e non deve essere considerato affidabile.

ARRAY_AGG_DISTINCT

Sintassi:

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

Descrizione:

Restituisce un array contenente tutti i valori distinti di expression quando viene valutato su ogni documento.

Se l'espressione viene risolta in un valore assente, viene convertita in NULL.

L'ordine degli elementi nell'array di output non è stabile e non deve essere considerato affidabile.

Funzioni aritmetiche

Tutte le funzioni aritmetiche in Firestore hanno i seguenti comportamenti:

  • Restituisce NULL se uno dei parametri di input è NULL.
  • Restituisce NaN se uno degli argomenti è NaN.
  • Genera un errore se si verifica un overflow o un underflow.

Inoltre, quando una funzione aritmetica accetta più argomenti numerici di tipi diversi (ad esempio: add(5.0, 6)), Firestore converte implicitamente gli argomenti nel tipo di input più ampio. Se vengono forniti solo input INT32, il tipo di reso sarà INT64.

Nome Descrizione
ABS Restituisce il valore assoluto di un number
ADD Restituisce il valore di x + y
SUBTRACT Restituisce il valore di x - y
MULTIPLY Restituisce il valore di x * y
DIVIDE Restituisce il valore di x / y
MOD Restituisce il resto della divisione di x / y
CEIL Restituisce il numero intero più piccolo maggiore o uguale a number.
FLOOR Restituisce la parte intera di un number
ROUND Arrotonda un number a places cifre decimali
POW Restituisce il valore di base^exponent
SQRT Restituisce la radice quadrata di un number
EXP Restituisce il numero di Eulero elevato alla potenza di exponent
LN Restituisce il logaritmo naturale di un number
LOG Restituisce il logaritmo di un number
LOG10 Restituisce il logaritmo di un number in base 10
RAND Restituisce un numero pseudo-casuale con rappresentazione in virgola mobile

ABS

Sintassi:

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

Descrizione:

Restituisce il valore assoluto di un number.

  • Genera un errore quando la funzione causerebbe l'overflow di un valore INT32 o INT64.

Esempi:

numero abs(number)
10 10
-10 10
10L 10L
-0.0 0.0
10.5 10.5
-10,5 10.5
-231 [error]
-263 [error]

AGGIUNGI

Sintassi:

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

Descrizione:

Restituisce il valore di x + y.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("soldBooks").add(field("unsoldBooks")).as("totalBooks"))
);
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

Sintassi:

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

Descrizione:

Restituisce il valore di x - y.

Esempi:

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

Web

const storeCredit = 7;
const result = await execute(db.pipeline()
  .collection("books")
  .select(field("price").subtract(constant(storeCredit)).as("totalCost"))
);
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

Sintassi:

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

Descrizione:

Restituisce il valore di x * y.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("price").multiply(field("soldBooks")).as("revenue"))
);
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

Sintassi:

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

Descrizione:

Restituisce il valore di x / y. La divisione intera viene troncata.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("ratings").divide(field("soldBooks")).as("reviewRate"))
);
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

Sintassi:

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

Descrizione:

Restituisce il resto di x / y.

  • Genera un errore error quando y è zero per i tipi interi (INT64).
  • Restituisce NaN quando y è zero per i tipi float (FLOAT64).

Esempi:

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

Web

const displayCapacity = 1000;
const result = await execute(db.pipeline()
  .collection("books")
  .select(field("unsoldBooks").mod(constant(displayCapacity)).as("warehousedBooks"))
);
Swift
let displayCapacity = 1000
let result = try await db.pipeline()
  .collection("books")
  .select([Field("unsoldBooks").mod(Constant(displayCapacity)).as("warehousedBooks")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce il valore intero più piccolo che non sia inferiore a number.

Esempi:

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

Web

const booksPerShelf = 100;
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("unsoldBooks").divide(constant(booksPerShelf)).ceil().as("requiredShelves")
  )
);
Swift
let booksPerShelf = 100
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("unsoldBooks").divide(Constant(booksPerShelf)).ceil().as("requiredShelves")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce il valore intero più grande non superiore a number.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .addFields(
    field("wordCount").divide(field("pages")).floor().as("wordsPerPage")
  )
);
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

Sintassi:

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

Descrizione:

Arrotonda places cifre di un number. Arrotonda le cifre a destra del separatore decimale se places è positivo e a sinistra del separatore decimale se è negativo.

  • Se viene fornito solo number, il valore viene arrotondato al numero intero più vicino.
  • Arrotonda lontano da zero nei casi a metà.
  • Viene generato un error se l'arrotondamento con un valore places negativo comporta un overflow.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("soldBooks").multiply(field("price")).round().as("partialRevenue"))
  .aggregate(field("partialRevenue").sum().as("totalRevenue"))
  );
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("soldBooks").multiply(Field("price")).round().as("partialRevenue")])
  .aggregate([Field("partialRevenue").sum().as("totalRevenue")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce il valore base elevato alla potenza di exponent.

  • Genera un errore se base <= 0 e exponent sono negativi.

  • Per qualsiasi exponent, pow(1, exponent) è 1.

  • Per qualsiasi base, pow(base, 0) è 1.

Esempi:

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

Web

const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await execute(db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
);
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

Sintassi:

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

Descrizione:

Restituisce la radice quadrata di un number.

  • Genera un error se number è negativo.

Esempi:

numero sqrt(number)
25 5,0
12.002 3,464…
0.0 0.0
NaN NaN
+inf +inf
-inf [error]
x < 0 [error]
Node.js
const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
  .execute();

Web

const googleplex = { latitude: 37.4221, longitude: 122.0853 };
const result = await execute(db.pipeline()
  .collection("cities")
  .addFields(
    field("lat").subtract(constant(googleplex.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    field("lng").subtract(constant(googleplex.longitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  )
  .select(
    field("latitudeDifference").add(field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  )
);
Swift
let googleplex = CLLocation(latitude: 37.4221, longitude: 122.0853)
let result = try await db.pipeline()
  .collection("cities")
  .addFields([
    Field("lat").subtract(Constant(googleplex.coordinate.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("latitudeDifference"),
    Field("lng").subtract(Constant(googleplex.coordinate.latitude))
      .multiply(111 /* km per degree */)
      .pow(2)
      .as("longitudeDifference")
  ])
  .select([
    Field("latitudeDifference").add(Field("longitudeDifference")).sqrt()
      // Inaccurate for large distances or close to poles
      .as("approximateDistanceToGoogle")
  ])
  .execute()
Kotlin
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

Sintassi:

exp(exponent: FLOAT64) -> FLOAT64

Descrizione:

Restituisce il valore del numero di Eulero elevato alla potenza di exponent, chiamato anche funzione esponenziale naturale.

Esempi:

base del logaritmo naturale exp(exponent)
0.0 1,0
10 e^10 (FLOAT64)
+inf +inf
-inf 0
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("rating").exp().as("expRating"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").exp().as("expRating"))
);
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

Sintassi:

ln(number: FLOAT64) -> FLOAT64

Descrizione:

Restituisce il logaritmo naturale di number. Questa funzione è equivalente a log(number).

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").ln().as("lnRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").ln().as("lnRating")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce il logaritmo di un number in base base.

  • Se viene fornito solo number, restituisce il logaritmo di number in base base (sinonimo di ln(number)).

Esempi:

numero 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

Sintassi:

log10(x: FLOAT64) -> FLOAT64

Descrizione:

Restituisce il logaritmo di un number in base 10.

Esempi:

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

RAND

Sintassi:

rand() -> FLOAT64

Descrizione:

Restituisce un numero in virgola mobile pseudocasuale, scelto in modo uniforme tra 0.0 (incluso) e 1.0 (escluso).

Funzioni di array

Nome Descrizione
ARRAY Restituisce un ARRAY contenente un elemento per ogni argomento di input
ARRAY_CONCAT Concatena più array in un unico ARRAY
ARRAY_CONTAINS Restituisce TRUE se un determinato ARRAY contiene un valore specifico
ARRAY_CONTAINS_ALL Restituisce TRUE se tutti i valori sono presenti in ARRAY
ARRAY_CONTAINS_ANY Restituisce TRUE se uno dei valori è presente in ARRAY
ARRAY_GET Restituisce l'elemento in un determinato indice di un ARRAY
ARRAY_LENGTH Restituisce il numero di elementi in un ARRAY
ARRAY_REVERSE Inverte l'ordine degli elementi in un ARRAY
SUM Restituisce la somma di tutti i valori NUMERIC in un ARRAY.
JOIN Produce una concatenazione degli elementi in un ARRAY come valore STRING.

ARRAY

Sintassi:

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

Descrizione:

Costruisce un array dagli elementi specificati.

  • Se un argomento non esiste, viene sostituito con NULL nell'array risultante.

Esempi:

valori 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

Sintassi:

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

Descrizione:

Concatena due o più array in un unico ARRAY.

Esempi:

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

Sintassi:

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

Descrizione:

Restituisce TRUE se value viene trovato in array, altrimenti restituisce FALSE.

Esempi:

matrice valore array_contains(array, value)
[1, 2, 3] 2 true
[[1, 2], [3]] [1, 2] true
[1, null] null true
"abc" QUALSIASI errore
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("genre").arrayContains(constant("mystery")).as("isMystery"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("genre").arrayContains(constant("mystery")).as("isMystery"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("genre").arrayContains(Constant("mystery")).as("isMystery")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se tutti i search_values si trovano in array, altrimenti restituisce FALSE.

Esempi:

matrice search_values array_contains_all(array, search_values)
[1, 2, 3] [1, 2] true
[1, 2, 3] [1, 4] falso
[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();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("genre")
      .arrayContainsAll([constant("fantasy"), constant("adventure")])
      .as("isFantasyAdventure")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("genre")
      .arrayContainsAll([Constant("fantasy"), Constant("adventure")])
      .as("isFantasyAdventure")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se uno qualsiasi dei search_values viene trovato in array, altrimenti restituisce FALSE.

Esempi:

matrice search_values array_contains_any(array, search_values)
[1, 2, 3] [4, 1] true
[1, 2, 3] [4, 5] falso
[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();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("genre")
      .arrayContainsAny([constant("fantasy"), constant("nonfiction")])
      .as("isMysteryOrFantasy")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("genre")
      .arrayContainsAny([Constant("fantasy"), Constant("nonfiction")])
      .as("isMysteryOrFantasy")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce l'elemento in corrispondenza dell'indice index basato su zero in array.

  • Se index è negativo, gli elementi vengono accessibili dalla fine dell'array, dove -1 è l'ultimo elemento.
  • Se array non è di tipo ARRAY, la funzione restituisce un valore assente.
  • Se index non rientra nei limiti, la funzione restituisce un valore assente.
  • Se index non è di tipo INT64, la funzione restituisce un errore.

Esempi:

matrice indice array_get(array, index)
[1, 2, 3] 0 1
[1, 2, 3] -1 3
[1, 2, 3] 3 assente
[1, 2, 3] -4 assente
"abc" 0 assente
null 0 assente
Array "a" errore
Array 2.0 errore

ARRAY_LENGTH

Sintassi:

array_length(array: ARRAY) -> INT64

Descrizione:

Restituisce il numero di elementi in array.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("genre").arrayLength().as("genreCount"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("genre").arrayLength().as("genreCount")])
  .execute()
Kotlin
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

Sintassi:

array_reverse(array: ARRAY) -> ARRAY

Descrizione:

Inverte il array specificato.

Esempi:

matrice array_reverse(array)
[1, 2, 3] [3, 2, 1]
["a", "b"] ["b", "a"]
[1, 2, 2, 3] [3, 2, 2, 1]
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(arrayReverse(field("genre")).as("reversedGenres"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("genre").arrayReverse().as("reversedGenres"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("genre").arrayReverse().as("reversedGenres")])
  .execute()
Kotlin
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

Sintassi:

sum(array: ARRAY) -> INT64 | FLOAT64

Descrizione:

Restituisce la somma di tutti i valori NUMERIC in un ARRAY.

  • I valori non numerici nell'array vengono ignorati.
  • Se un valore numerico nell'array è NaN, la funzione restituisce NaN.
  • Il tipo restituito è determinato dal tipo numerico più ampio nell'array: INT64 < FLOAT64.
  • Se si verifica un overflow di numeri interi a 64 bit prima che venga sommato un valore in virgola mobile, viene restituito un errore. Se vengono sommati valori in virgola mobile, l'overflow restituirà +/- infinito.
  • Se l'array non contiene valori numerici, la funzione restituisce NULL.

Esempi:

matrice 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] errore
[INT64.MAX_VALUE, 1, -1.0] errore
[INT64.MAX_VALUE, 1.0] 9.223372036854776e+18

PARTECIPA

Sintassi:

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

Descrizione:

Restituisce una concatenazione degli elementi in array come STRING. array può essere di tipo STRING o BYTES.

  • Tutti gli elementi in array, delimiter e null_text devono essere dello stesso tipo: devono essere tutti STRING o tutti BYTES.
  • Se viene fornito null_text, tutti i valori NULL in array vengono sostituiti con null_text.
  • Se null_text non viene fornito, i valori NULL in array vengono omessi dal risultato.

Esempi:

Quando null_text non viene fornito:

matrice delimitatore 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'] "," errore
["a", "c"] b',' errore
[b'a', b'c'] "," errore

Quando viene fornito null_text:

matrice delimitatore 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' errore
[b'a', null] b',' "N" errore

Funzioni di confronto

Nome Descrizione
EQUAL Confronto di uguaglianza
GREATER_THAN Confronto maggiore di
GREATER_THAN_OR_EQUAL Confronto maggiore o uguale a
LESS_THAN Confronto con il segno "minore di"
LESS_THAN_OR_EQUAL Confronto minore o uguale
NOT_EQUAL Confronto diverso da

EQUAL

Sintassi:

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

Esempi:

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

Descrizione:

Restituisce TRUE se x e y sono uguali, altrimenti restituisce FALSE.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").equal(5).as("hasPerfectRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").equal(5).as("hasPerfectRating")])
  .execute()
Kotlin
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();

MAGGIORE_DI

Sintassi:

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

Descrizione:

Restituisce TRUE se x è maggiore di y, altrimenti restituisce FALSE.

Se x e y non sono comparabili, restituisce FALSE.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").greaterThan(4).as("hasHighRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").greaterThan(4).as("hasHighRating")])
  .execute()
Kotlin
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();

MAGGIORE_UGUALE

Sintassi:

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

Descrizione:

Restituisce TRUE se x è maggiore o uguale a y, altrimenti restituisce FALSE.

Se x e y non sono comparabili, restituisce FALSE.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("published").greaterThanOrEqual(1900).as("publishedIn20thCentury"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("published").greaterThanOrEqual(1900).as("publishedIn20thCentury")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se x è minore di y, altrimenti restituisce FALSE.

Se x e y non sono comparabili, restituisce FALSE.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("published").lessThan(1923).as("isPublicDomainProbably"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("published").lessThan(1923).as("isPublicDomainProbably")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se x è minore o uguale a y, altrimenti restituisce FALSE.

Se x e y non sono comparabili, restituisce FALSE.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("rating").lessThanOrEqual(2).as("hasBadRating"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("rating").lessThanOrEqual(2).as("hasBadRating")])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se x non è uguale a y, altrimenti restituisce FALSE.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("title").notEqual("1984").as("not1984"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("title").notEqual("1984").as("not1984")])
  .execute()
Kotlin
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();

Funzioni di debug

Nome Descrizione
EXISTS Restituisce TRUE se il valore non è un valore assente
IS_ABSENT Restituisce TRUE se il valore è un valore assente
IF_ABSENT Sostituisce il valore con un'espressione se è assente
IS_ERROR Rileva e verifica se l'espressione sottostante ha generato un errore
IF_ERROR Sostituisce il valore con un'espressione se ha generato un errore

ESISTE

Sintassi:

exists(value: ANY) -> BOOLEAN

Descrizione:

Restituisce TRUE se value non è il valore assente.

Esempi:

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

Web

Esempio:

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

Esempio:

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

Esempio:

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

Sintassi:

is_absent(value: ANY) -> BOOLEAN

Descrizione:

Restituisce TRUE se value è il valore assente, altrimenti restituisce FALSE. I valori assenti sono valori mancanti nell'input, ad esempio un campo del documento mancante.

Esempi:

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

IF_ABSENT

Sintassi:

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

Descrizione:

Se value è un valore assente, valuta e restituisce replacement. In caso contrario, restituisce value.

Esempi:

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

IS_ERROR

Sintassi:

is_error(try: ANY) -> BOOLEAN

Descrizione:

Restituisce TRUE se viene generato un errore durante la valutazione di try. In caso contrario, restituisce FALSE.

IF_ERROR

Sintassi:

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

Descrizione:

Se viene generato un errore durante la valutazione di try, valuta e restituisce replacement. In caso contrario, restituisce il valore risolto di try.

Funzioni logiche

Nome Descrizione
AND Esegue un AND logico
OR Esegue un OR logico
XOR Esegue un'operazione XOR logica.
NOT Esegue un NOT logico
CONDITIONAL Valutazione dei rami in base a un'espressione condizionale.
EQUAL_ANY Verifica se un valore è uguale a uno qualsiasi degli elementi di un array
NOT_EQUAL_ANY Verifica se un valore non è uguale a nessun elemento di un array
MAXIMUM Restituisce il valore massimo in un insieme di valori.
MINIMUM Restituisce il valore minimo in un insieme di valori.

E

Sintassi:

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

Descrizione:

Restituisce l'operatore logico AND di due o più valori booleani.

Restituisce NULL se il risultato non può essere derivato perché uno dei valori forniti è ABSENT o NULL.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    and(field("rating").greaterThan(4), field("price").lessThan(10))
      .as("under10Recommendation")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    (Field("rating").greaterThan(4) && Field("price").lessThan(10))
      .as("under10Recommendation")
  ])
  .execute()
Kotlin
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();

OPPURE

Sintassi:

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

Descrizione:

Restituisce l'OR logico di due o più valori booleani.

Restituisce NULL se il risultato non può essere derivato perché uno dei valori forniti è ABSENT o NULL.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    or(field("genre").equal("Fantasy"), field("tags").arrayContains("adventure"))
      .as("matchesSearchFilters")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    (Field("genre").equal("Fantasy") || Field("tags").arrayContains("adventure"))
      .as("matchesSearchFilters")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce l'operazione XOR logica di due o più valori booleani.

Restituisce NULL se uno dei valori forniti è ABSENT o NULL.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    xor(field("tags").arrayContains("magic"), field("tags").arrayContains("nonfiction"))
      .as("matchesSearchFilters")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    (Field("tags").arrayContains("magic") ^ Field("tags").arrayContains("nonfiction"))
      .as("matchesSearchFilters")
  ])
  .execute()
Kotlin
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

Sintassi:

not(x: BOOLEAN) -> BOOLEAN

Descrizione:

Restituisce la negazione logica di un valore booleano.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("tags").arrayContains("nonfiction").not()
      .as("isFiction")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    (!Field("tags").arrayContains("nonfiction"))
      .as("isFiction")
  ])
  .execute()
Kotlin
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();

CONDIZIONALE

Sintassi:

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

Descrizione:

Valuta e restituisce true_case se condition restituisce TRUE.

Valuta e restituisce false_case se la condizione restituisce FALSE, NULL o un valore ABSENT.

Esempi:

condition true_case false_case conditional(condition, true_case, false_case)
TRUE 1L 0L 1L
FALSE 1L 0L 0L
NULL 1L 0L 0L
ABSENT 1L 0L 0L
Node.js
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("tags").arrayConcat([
      field("pages").greaterThan(100)
        .conditional(constant("longRead"), constant("shortRead"))
    ]).as("extendedTags")
  )
);

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("tags").arrayConcat([
      field("pages").greaterThan(100)
        .conditional(constant("longRead"), constant("shortRead"))
    ]).as("extendedTags")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("tags").arrayConcat([
      ConditionalExpression(
        Field("pages").greaterThan(100),
        then: Constant("longRead"),
        else: Constant("shortRead")
      )
    ]).as("extendedTags")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se value è presente nell'array search_space.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("genre").equalAny(["Science Fiction", "Psychological Thriller"])
      .as("matchesGenreFilters")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("genre").equalAny(["Science Fiction", "Psychological Thriller"])
      .as("matchesGenreFilters")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se value non è presente nell'array search_space.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("author").notEqualAny(["George Orwell", "F. Scott Fitzgerald"])
      .as("byExcludedAuthors")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("author").notEqualAny(["George Orwell", "F. Scott Fitzgerald"])
      .as("byExcludedAuthors")
  ])
  .execute()
Kotlin
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();

MASSIMO

Sintassi:

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

Descrizione:

Restituisce il valore massimo non NULL e non ABSENT in una serie di valori x.

Se non sono presenti valori non NULL e non ABSENT, viene restituito NULL.

Se esistono più valori equivalenti massimi, può essere restituito uno qualsiasi di questi valori. L'ordinamento dei tipi di valore segue l'ordinamento documentato.

Esempi:

x y maximum(x, y)
FALSE TRUE TRUE
FALSE -10L -10L
0.0 -5L 0.0
"foo" "bar" "foo"
"foo" ["foo"] ["foo"]
ABSENT ABSENT NULL
NULL NULL NULL
Node.js
const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").maximum().as("maximumPrice"))
);

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").maximum().as("maximumPrice"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("rating").logicalMaximum([1]).as("flooredRating")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce il valore minimo non NULL e non ABSENT in una serie di valori x.

Se non sono presenti valori non NULL e non ABSENT, viene restituito NULL.

Se sono presenti più valori minimi equivalenti, può essere restituito uno qualsiasi di questi valori. L'ordinamento dei tipi di valore segue l'ordinamento documentato.

Esempi:

x y minimum(x, y)
FALSE TRUE FALSE
FALSE -10L FALSE
0.0 -5L -5L
"foo" "bar" "bar"
"foo" ["foo"] "foo"
ABSENT ABSENT NULL
NULL NULL NULL
Node.js
const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").minimum().as("minimumPrice"))
);

Web

const result = await execute(db.pipeline()
  .collection("books")
  .aggregate(field("price").minimum().as("minimumPrice"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("rating").logicalMinimum([5]).as("cappedRating")
  ])
  .execute()
Kotlin
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();

Funzioni della mappa

Nome Descrizione
MAP Crea un valore della mappa da una serie di coppie chiave-valore
MAP_GET Restituisce il valore in una mappa data una chiave specificata
MAP_SET Restituisce una copia di una mappa con una serie di chiavi aggiornate
MAP_REMOVE Restituisce una copia di una mappa con una serie di chiavi rimosse
MAP_MERGE Unisce una serie di mappe.
CURRENT_CONTEXT Restituisce il contesto corrente come mappa.
MAP_KEYS Restituisce un array di tutte le chiavi in una mappa.
MAP_VALUES Restituisce un array di tutti i valori in una mappa.
MAP_ENTRIES Restituisce un array di coppie chiave-valore di una mappa.

MAPPA

Sintassi:

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

Descrizione:

Crea una mappa da una serie di coppie chiave-valore.

MAP_GET

Sintassi:

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

Descrizione:

Restituisce il valore in una mappa data una chiave specificata. Restituisce un valore ABSENT se key non esiste nella mappa o se l'argomento map non è un MAP.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("awards").mapGet("pulitzer").as("hasPulitzerAward")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("awards").mapGet("pulitzer").as("hasPulitzerAward")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce una copia del valore map con i contenuti aggiornati da una serie di coppie chiave-valore.

Se il valore fornito viene risolto in un valore assente, la chiave associata viene rimossa dalla mappa.

Se l'argomento map non è un MAP, restituisce un valore assente.

MAP_REMOVE

Sintassi:

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

Descrizione:

Restituisce una copia del valore map con una serie di chiavi rimosse.

MAP_MERGE

Sintassi:

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

Unisce i contenuti di due o più mappe. Se più mappe hanno valori in conflitto, viene utilizzato l'ultimo valore.

CURRENT_CONTEXT

Sintassi:

current_context() -> MAP

Restituisce una mappa costituita da tutti i campi disponibili nel punto di esecuzione corrente.

MAP_KEYS

Sintassi:

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

Descrizione:

Restituisce un array contenente tutte le chiavi del valore map.

MAP_VALUES

Sintassi:

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

Descrizione:

Restituisce un array contenente tutti i valori del valore map.

MAP_ENTRIES

Sintassi:

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

Descrizione:

Restituisce un array contenente tutte le coppie chiave-valore nel valore map.

Ogni coppia chiave-valore avrà la forma di una mappa con due voci, k e v.

Esempi:

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

Funzioni stringa

Nome Descrizione
BYTE_LENGTH Restituisce il numero di BYTES in un valore STRING o BYTES
CHAR_LENGTH Restituisce il numero di caratteri Unicode in un valore STRING
STARTS_WITH Restituisce TRUE se un STRING inizia con un determinato prefisso
ENDS_WITH Restituisce TRUE se un STRING termina con un determinato suffisso
LIKE Restituisce TRUE se un STRING corrisponde a un pattern
REGEX_CONTAINS Restituisce TRUE se un valore corrisponde parzialmente o completamente a un'espressione regolare.
REGEX_MATCH Restituisce TRUE se una parte di un valore corrisponde a un'espressione regolare
STRING_CONCAT Concatena più STRING in un STRING
STRING_CONTAINS Restituisce TRUE se un valore contiene STRING
TO_UPPER Converte un valore STRING o BYTES in maiuscolo.
TO_LOWER Converte un valore STRING o BYTES in minuscolo.
SUBSTRING Ottiene una sottostringa di un valore STRING o BYTES.
STRING_REVERSE Inverte un valore STRING o BYTES.
TRIM Rimuove i caratteri iniziali e finali da un valore STRING o BYTES.
SPLIT Divide un valore STRING o BYTES in una matrice.

BYTE_LENGTH

Sintassi:

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

Descrizione:

Restituisce il numero di BYTES in un valore STRING o BYTES.

Esempi:

valore byte_length(value)
"abc" 3
"xyzabc" 6
b"abc" 3
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").byteLength().as("titleByteLength")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").byteLength().as("titleByteLength")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").byteLength().as("titleByteLength")
  ])
  .execute()
Kotlin
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

Sintassi:

char_length(value: STRING) -> INT64

Descrizione:

Restituisce il numero di punti di codice Unicode nel valore di STRING.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").charLength().as("titleCharLength")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").charLength().as("titleCharLength")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se value inizia con prefix.

Esempi:

valore prefisso starts_with(value, prefix)
"abc" "a" true
"abc" "b" falso
"abc" "" true
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se value termina con postfix.

Esempi:

valore postfix ends_with(value, postfix)
"abc" "c" true
"abc" "b" falso
"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();

MI PIACE

Sintassi:

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

Descrizione:

Restituisce TRUE se value corrisponde a pattern.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("genre").like("%Fiction")
      .as("anyFiction")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("genre").like("%Fiction")
      .as("anyFiction")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se una parte di value corrisponde a pattern. Se pattern non è un'espressione regolare valida, questa funzione restituisce error.

Le espressioni regolari seguono la sintassi della libreria re2.

Esempi:

valore pattern regex_contains(value, pattern)
"Firestore" "Fuoco" true
"Firestore" "store$" true
"Firestore" "dati" falso
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce TRUE se value corrisponde esattamente a pattern. Se pattern non è un'espressione regolare valida, questa funzione restituisce error.

Le espressioni regolari seguono la sintassi della libreria re2.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("title").regexMatch("Firestore (Enterprise|Standard)")
      .as("isFirestoreExactly")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("title").regexMatch("Firestore (Enterprise|Standard)")
      .as("isFirestoreExactly")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Concatena due o più valori STRING in un unico risultato.

Esempi:

argomenti string_concat(values...)
() errore
("a") "a"
("abc", "def") "abcdef"
("a", "", "c") "ac"
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").stringConcat(" by ", field("author"))
      .as("fullyQualifiedTitle")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").stringConcat(" by ", field("author"))
      .as("fullyQualifiedTitle")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").concat([" by ", Field("author")])
      .as("fullyQualifiedTitle")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Controlla se value contiene la stringa letterale substring.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("articles")
  .select(
    field("body").stringContains("Firestore")
      .as("isFirestoreRelated")
  )
);
Swift
let result = try await db.pipeline()
  .collection("articles")
  .select([
    Field("body").stringContains("Firestore")
      .as("isFirestoreRelated")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Converte un valore STRING o BYTES in maiuscolo.

Se un byte o un carattere non corrisponde a un carattere alfabetico minuscolo UTF-8, viene passato invariato.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("authors")
  .select(
    field("name").toUpper()
      .as("uppercaseName")
  )
);
Swift
let result = try await db.pipeline()
  .collection("authors")
  .select([
    Field("name").toUpper()
      .as("uppercaseName")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Converte un valore STRING o BYTES in minuscolo.

Se un byte o un carattere non corrisponde a un carattere alfabetico maiuscolo UTF-8, viene passato invariato.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("authors")
  .select(
    field("genre").toLower().equal("fantasy")
      .as("isFantasy")
  )
);
Swift
let result = try await db.pipeline()
  .collection("authors")
  .select([
    Field("genre").toLower().equal("fantasy")
      .as("isFantasy")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce una sottostringa di input a partire da position (indice in base zero) e includendo fino a length voci. Se non viene fornito alcun length, restituisce la sottostringa da position alla fine di input.

  • Se input è un valore STRING, position e length vengono misurati in punti di codice Unicode. Se si tratta di un valore BYTES, vengono misurati in byte.

  • Se position è maggiore della lunghezza di input, viene restituita una sottostringa vuota. Se position più length è maggiore della lunghezza di input, la sottostringa viene troncata alla fine di input.

  • Se position è negativo, la posizione viene presa dalla fine dell'input. Se il valore negativo di position è maggiore della dimensione dell'input, la posizione viene impostata su zero. length non deve essere un valore negativo.

Esempi:

Quando length non viene fornito:

immissione position substring(input, position)
"abc" 0 "abc"
"abc" 1 "bc"
"abc" 3 ""
"abc" -1 "c"
b"abc" 1 b"bc"

Quando viene fornito length:

immissione position lunghezza substring(input, position, length)
"abc" 0 1 "a"
"abc" 1 2 "bc"
"abc" -1 1 "c"
b"abc" 0 1 b"a"
Node.js
const result = await db.pipeline()
  .collection("books")
  .where(field("title").startsWith("The "))
  .select(
    field("title").substring(4)
      .as("titleWithoutLeadingThe")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .where(field("title").startsWith("The "))
  .select(
    field("title").substring(4)
      .as("titleWithoutLeadingThe")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .where(Field("title").startsWith("The "))
  .select([
    Field("title").substring(position: 4)
      .as("titleWithoutLeadingThe")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce l'input fornito in ordine inverso.

I caratteri sono delimitati dai punti di codice Unicode quando l'input è un STRING e dai byte quando l'input è un valore BYTES.

Esempi:

immissione string_reverse(input)
"abc" "cba"
"a🌹b" "b🌹a"
"ciao" "olleh"
b"abc" b"cba"
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("name").reverse().as("reversedName")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("name").reverse().as("reversedName")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("name").reverse().as("reversedName")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Taglia un insieme specificato di BYTES o CHARS dall'inizio e dalla fine del input fornito.

  • Se non vengono forniti values_to_trim, vengono eliminati gli spazi vuoti.

Esempi:

Quando values_to_trim non viene fornito:

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

Quando viene fornito values_to_trim:

immissione values_to_trim trim(input, values_to_trim)
"abcbfooaacb" "abc" "foo"
"abcdaabadbac" "abc" "daabad"
b"C1C2C3" b"C1" b"C2C3"
b"C1C2" "foo" errore
"foo" b"C1" errore

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("name").trim().as("whitespaceTrimmedName")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("name").trim(" \n\t").as("whitespaceTrimmedName")
  ])
  .execute()
Kotlin
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();

DIVIDI

Sintassi:

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

Descrizione:

Divide un valore STRING o BYTES utilizzando un delimitatore.

  • Per STRING, il delimitatore predefinito è la virgola ,. Il delimitatore viene trattato come una singola stringa.

  • Per BYTES, devi specificare un delimitatore.

  • La suddivisione in base a un delimitatore vuoto produce una matrice di punti di codice Unicode per i valori STRING e una matrice di BYTES per i valori BYTES.

  • La suddivisione di un STRING vuoto restituisce un ARRAY con un singolo STRING vuoto.

Esempi:

Quando delimiter non viene fornito:

immissione split(input)
"foo,bar,foo" ["foo", "bar", "foo"]
"foo" ["foo"]
",foo," ["", "foo", ""]
"" [""]
b"C120C2C4" errore

Quando viene fornito delimiter:

immissione delimitatore 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" errore

Funzioni di timestamp

Nome Descrizione
CURRENT_TIMESTAMP Genera un TIMESTAMP corrispondente all'ora della richiesta.
TIMESTAMP_TRUNC Tronca un TIMESTAMP in base a una granularità specificata.
UNIX_MICROS_TO_TIMESTAMP Converte il numero di microsecondi a partire dal 1970-01-01 00:00:00 UTC in un TIMESTAMP
UNIX_MILLIS_TO_TIMESTAMP Converte il numero di millisecondi trascorsi dal 1970-01-01 00:00:00 UTC in un TIMESTAMP
UNIX_SECONDS_TO_TIMESTAMP Converte il numero di secondi trascorsi dal 1970-01-01 00:00:00 UTC in un TIMESTAMP
TIMESTAMP_ADD Aggiunge un intervallo di tempo a un TIMESTAMP
TIMESTAMP_SUB Sottrae un intervallo di tempo a TIMESTAMP
TIMESTAMP_TO_UNIX_MICROS Converte un valore TIMESTAMP nel numero di microsecondi trascorsi dal 1970-01-01 00:00:00 UTC
TIMESTAMP_TO_UNIX_MILLIS Converte un valore TIMESTAMP nel numero di millisecondi trascorsi dal giorno 1970-01-01 00:00:00 UTC
TIMESTAMP_TO_UNIX_SECONDS Converte un valore TIMESTAMP nel numero di secondi trascorsi dal giorno 1970-01-01 00:00:00 UTC

CURRENT_TIMESTAMP

Sintassi:

current_timestamp() -> TIMESTAMP

Descrizione:

Recupera il timestamp all'inizio dell'ora della richiesta input (interpretato come il numero di microsecondi trascorsi dal 1970-01-01 00:00:00 UTC).

Questo valore è stabile all'interno di una query e verrà sempre risolto nello stesso valore se chiamato più volte.

TIMESTAMP_TRUNC

Sintassi:

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

Descrizione:

Tronca un timestamp in base a una granularità specificata.

L'argomento granularity deve essere una stringa e uno dei seguenti:

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

Se viene fornito l'argomento timezone, il troncamento si baserà sui limiti del calendario del fuso orario specificato (ad esempio, il troncamento giornaliero troncherà fino a mezzanotte nel fuso orario specificato). Il troncamento rispetterà l'ora legale.

Se timezone non viene fornito, il troncamento si baserà sui limiti del calendario UTC.

L'argomento timezone deve essere una rappresentazione stringa di un fuso orario del database tz, ad esempio America/New_York. È possibile utilizzare anche un offset temporale personalizzato specificando un offset da GMT.

Esempi:

timestamp granularity timezone timestamp_trunc(timestamp, granularity, timezone)
2000-01-01 10:20:30:123456 UTC "secondo" Non fornito 2001-01-01 10:20:30 UTC
1997-05-31 04:30:30 UTC "day" Non fornito 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) Non fornito 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

Sintassi:

unix_micros_to_timestamp(input: INT64) -> TIMESTAMP

Descrizione:

Converte input (interpretato come il numero di microsecondi a partire dal 1970-01-01 00:00:00 UTC) in un TIMESTAMP. Genera un error se input non può essere convertito in un TIMESTAMP valido.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAtMicros").unixMicrosToTimestamp().as("createdAtString")
  ])
  .execute()
Kotlin
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

Sintassi:

unix_millis_to_timestamp(input: INT64) -> TIMESTAMP

Descrizione:

Converte input (interpretato come il numero di millisecondi a partire dal 1970-01-01 00:00:00 UTC) in un TIMESTAMP. Genera un error se input non può essere convertito in un TIMESTAMP valido.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAtMillis").unixMillisToTimestamp().as("createdAtString")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAtMillis").unixMillisToTimestamp().as("createdAtString")
  ])
  .execute()
Kotlin
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

Sintassi:

unix_seconds_to_timestamp(input: INT64) -> TIMESTAMP

Descrizione:

Converte input (interpretato come il numero di secondi trascorsi dal 1970-01-01 00:00:00 UTC) in un TIMESTAMP. Genera un error se input non può essere convertito in un TIMESTAMP valido.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAtSeconds").unixSecondsToTimestamp().as("createdAtString")
  )
);
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

Sintassi:

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

Descrizione:

Aggiunge un amount di unit da timestamp. L'argomento amount può essere negativo, nel qual caso è equivalente a TIMESTAMP_SUB.

L'argomento unit deve essere una stringa e uno dei seguenti:

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

Genera un errore se il timestamp risultante non rientra nell'intervallo TIMESTAMP.

Esempi:

timestamp unit amount timestamp_add(timestamp, unit, amount)
2025-02-20 00:00:00 UTC "minuto" 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();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("createdAt").timestampAdd("day", 3653).as("expiresAt")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("createdAt").timestampAdd(3653, .day).as("expiresAt")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Sottrae un amount di unit da timestamp. L'argomento amount può essere negativo, nel qual caso è equivalente a TIMESTAMP_ADD.

L'argomento unit deve essere una stringa e uno dei seguenti:

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

Genera un errore se il timestamp risultante non rientra nell'intervallo TIMESTAMP.

Esempi:

timestamp unit amount timestamp_sub(timestamp, unit, amount)
2026-07-04 00:00:00 UTC "minuto" 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();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("expiresAt").timestampSubtract(14, .day).as("sendWarningTimestamp")
  ])
  .execute()
Kotlin
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

Sintassi:

timestamp_to_unix_micros(input: TIMESTAMP) -> INT64

Descrizione:

Converte input nel numero di microsecondi trascorsi dal 1970-01-01 00:00:00 UTC. Tronca i livelli di precisione più elevati arrotondando per difetto all'inizio del microsecondo.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMicros().as("unixMicros")
  )
);
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

Sintassi:

timestamp_to_unix_millis(input: TIMESTAMP) -> INT64

Descrizione:

Converte input nel numero di millisecondi trascorsi dal 1970-01-01 00:00:00 UTC. Tronca i livelli di precisione più elevati arrotondando per difetto all'inizio del millisecondo.

Esempi:

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixMillis().as("unixMillis")
  )
);
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

Sintassi:

timestamp_to_unix_seconds(input: TIMESTAMP) -> INT64

Descrizione:

Converte input nel numero di secondi trascorsi dal giorno 1970-01-01 00:00:00 UTC. Tronca i livelli di precisione più elevati arrotondando per difetto all'inizio del secondo.

Esempi:

input timestamp_to_unix_seconds(input)
1970-01-01 00:00:00 UTC 0L
1970-01-01 00:01:00 UTC 60L
1969-12-31 23:55:00 UTC -300L
Node.js
const result = await db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixSeconds().as("unixSeconds")
  )
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("dateString").timestampToUnixSeconds().as("unixSeconds")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("dateString").timestampToUnixSeconds().as("unixSeconds")
  ])
  .execute()
Kotlin
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();
## **Funzioni di tipo**
Nome Descrizione
TYPE Restituisce il tipo di valore come STRING.
### TYPE **Sintassi:** ```none type(input: ANY) -> STRING ``` **Descrizione:** Restituisce una rappresentazione in formato stringa del tipo di `input`. Se viene fornito un valore assente, restituisce `NULL`. **Esempi:** | `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 | **Esempi di client**
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(field("title").notEqual("1984").as("not1984"))
  .execute();

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(field("title").notEqual("1984").as("not1984"))
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([Field("title").notEqual("1984").as("not1984")])
  .execute()
Kotlin
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();

Funzioni vettoriali

Nome Descrizione
COSINE_DISTANCE Restituisce la distanza del coseno tra due vettori
DOT_PRODUCT Restituisce il prodotto scalare tra due vettori
EUCLIDEAN_DISTANCE Restituisce la distanza euclidea tra due vettori
MANHATTAN_DISTANCE Restituisce la distanza di Manhattan tra due vettori
VECTOR_LENGTH Restituisce il numero di elementi in un vettore

COSINE_DISTANCE

Sintassi:

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

Descrizione:

Restituisce la distanza del coseno tra x e y.

Node.js
const sampleVector = [0.0, 1, 2, 3, 4, 5];
const result = await db.pipeline()
  .collection("books")
  .select(
    field("embedding").cosineDistance(sampleVector).as("cosineDistance")
  )
  .execute();

Web

const sampleVector = [0.0, 1, 2, 3, 4, 5];
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("embedding").cosineDistance(sampleVector).as("cosineDistance")));
Swift
let sampleVector = [0.0, 1, 2, 3, 4, 5]
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("embedding").cosineDistance(sampleVector).as("cosineDistance")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Restituisce il prodotto scalare di x e y.

Node.js
const sampleVector = [0.0, 1, 2, 3, 4, 5];
const result = await db.pipeline()
  .collection("books")
  .select(
    field("embedding").dotProduct(sampleVector).as("dotProduct")
  )
  .execute();

Web

const sampleVector = [0.0, 1, 2, 3, 4, 5];
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("embedding").dotProduct(sampleVector).as("dotProduct")
  )
);
Swift
let sampleVector = [0.0, 1, 2, 3, 4, 5]
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("embedding").dotProduct(sampleVector).as("dotProduct")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Calcola la distanza euclidea tra x e y.

Node.js
const sampleVector = [0.0, 1, 2, 3, 4, 5];
const result = await db.pipeline()
  .collection("books")
  .select(
    field("embedding").euclideanDistance(sampleVector).as("euclideanDistance")
  )
  .execute();

Web

const sampleVector = [0.0, 1, 2, 3, 4, 5];
const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("embedding").euclideanDistance(sampleVector).as("euclideanDistance")
  )
);
Swift
let sampleVector = [0.0, 1, 2, 3, 4, 5]
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("embedding").euclideanDistance(sampleVector).as("euclideanDistance")
  ])
  .execute()
Kotlin
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

Sintassi:

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

Descrizione:

Calcola la distanza di Manhattan tra x e y.

VECTOR_LENGTH

Sintassi:

vector_length(vector: VECTOR) -> INT64

Descrizione:

Restituisce il numero di elementi in un VECTOR.

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("embedding").vectorLength().as("vectorLength")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("embedding").vectorLength().as("vectorLength")
  ])
  .execute()
Kotlin
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();

Passaggi successivi