Referencia de todas las funciones
Agregación
Todas las funciones de agregación se pueden usar como expresiones de nivel superior en la etapa aggregate(...).
| Nombre | Descripción |
COUNT
|
Devuelve la cantidad de documentos. |
COUNT_IF
|
Devuelve el recuento de documentos en los que una expresión se evalúa como TRUE.
|
COUNT_DISTINCT
|
Devuelve el recuento de valores únicos que no son NULL.
|
SUM
|
Devuelve la suma de todos los valores NUMERIC.
|
AVERAGE
|
Devuelve el promedio de todos los valores NUMERIC.
|
MINIMUM
|
Devuelve el valor mínimo que no es NULL.
|
MAXIMUM
|
Devuelve el valor máximo que no es NULL.
|
FIRST
|
Devuelve el valor de expression para el primer documento.
|
LAST
|
Devuelve el valor de expression para el último documento.
|
ARRAY_AGG
|
Devuelve un array de todos los valores de entrada. |
ARRAY_AGG_DISTINCT
|
Devuelve un array de todos los valores de entrada distintos. |
COUNT
Sintaxis:
count() -> INT64
count(expression: ANY) -> INT64
Descripción:
Devuelve el recuento de documentos de la etapa anterior en la que expression se evalúa como cualquier valor que no sea NULL. Si no se proporciona ninguna expression, se devuelve el recuento total de documentos de la etapa anterior.
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
Sintaxis:
count_if(expression: BOOLEAN) -> INT64
Descripción:
Devuelve la cantidad de documentos de la etapa anterior en la que expression se evalúa como 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
Sintaxis:
count_distinct(expression: ANY) -> INT64
Descripción:
Devuelve la cantidad de valores únicos que no son NULL ni ABSENT de 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
Sintaxis:
sum(expression: ANY) -> NUMBER
Descripción:
Devuelve la suma de todos los valores numéricos, sin tener en cuenta los valores no numéricos. Devuelve NaN si algún valor es NaN.
El resultado tendrá el mismo tipo que el tipo de entrada, excepto en los siguientes casos:
- Un
INTEGERse convertirá en unDOUBLEsi no se puede representar como unINTEGER.
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();
PROMEDIO
Sintaxis:
average(expression: ANY) -> FLOAT64
Descripción:
Devuelve el promedio de todos los valores numéricos, sin tener en cuenta los valores no numéricos.
Se evalúa como NaN si algún valor es NaN, o como NULL si no se agregan valores numéricos.
El resultado tendrá el mismo tipo que el tipo de entrada, excepto en los siguientes casos:
- Un
INTEGERse convertirá en unDOUBLEsi no se puede representar como unINTEGER.
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
Sintaxis:
minimum(expression: ANY) -> ANY
Descripción:
Devuelve el valor mínimo que no es NULL ni está ausente de expression cuando se evalúa en cada documento.
Si no hay valores que no sean NULL ni ausentes, se devuelve NULL. Esto incluye los casos en los que no se consideran documentos.
Si hay varios valores equivalentes mínimos, se puede devolver cualquiera de ellos. El orden de los tipos de valor sigue el orden documentado.
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();
MAXIMUM
Sintaxis:
maximum(expression: ANY) -> ANY
Descripción:
Devuelve el valor máximo que no es NULL ni está ausente de expression cuando se evalúa en cada documento.
Si no hay valores que no sean NULL ni ausentes, se devuelve NULL. Esto incluye los casos en los que no se consideran documentos.
Si hay varios valores equivalentes máximos, se puede devolver cualquiera de ellos. El orden de los tipos de valor sigue el orden documentado.
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();
FIRST
Sintaxis:
first(expression: ANY) -> ANY
Descripción:
Devuelve el valor de expression para el primer documento devuelto.
LAST
Sintaxis:
last(expression: ANY) -> ANY
Descripción:
Devuelve el valor de expression para el último documento devuelto.
ARRAY_AGG
Sintaxis:
array_agg(expression: ANY) -> ARRAY<ANY>
Descripción:
Devuelve un array que contiene todos los valores de expression cuando se evalúa en cada documento.
Si la expresión se resuelve en un valor ausente, se convierte en NULL.
El orden de los elementos en el array de salida no es estable y no se debe confiar en él.
ARRAY_AGG_DISTINCT
Sintaxis:
array_agg_distinct(expression: ANY) -> ARRAY<ANY>
Descripción:
Devuelve un array que contiene todos los valores distintos de expression cuando se evalúa en cada documento.
Si la expresión se resuelve en un valor ausente, se convierte en NULL.
El orden de los elementos en el array de salida no es estable y no se debe confiar en él.
Funciones aritméticas
Todas las funciones aritméticas en Firestore tienen los siguientes comportamientos:
- Se evalúa como
NULLsi alguno de los parámetros de entrada esNULL. - Se evalúa como
NaNsi alguno de los argumentos esNaN. - Genera un error si se produce un desbordamiento o subdesbordamiento.
Además, cuando una función aritmética toma varios argumentos numéricos de diferentes tipos (por ejemplo, add(5.0, 6)), Firestore convierte implícitamente los argumentos al tipo de entrada más amplio. Si solo se proporcionan entradas INT32, el tipo de datos que se devuelve será INT64.
| Nombre | Descripción |
ABS
|
Devuelve el valor absoluto de un number.
|
ADD
|
Devuelve el valor de x + y.
|
SUBTRACT
|
Devuelve el valor de x - y.
|
MULTIPLY
|
Devuelve el valor de x * y.
|
DIVIDE
|
Devuelve el valor de x / y.
|
MOD
|
Devuelve el resto de la división de x / y.
|
CEIL
|
Devuelve el límite superior de un number
|
FLOOR
|
Devuelve el límite inferior de un number
|
ROUND
|
Redondea un number a places decimales
|
TRUNC
|
Trunca un number a places decimales.
|
POW
|
Devuelve el valor de base^exponent.
|
SQRT
|
Devuelve la raíz cuadrada de un number
|
EXP
|
Devuelve el número de Euler elevado a la potencia de exponent
|
LN
|
Devuelve el logaritmo natural de un number
|
LOG
|
Devuelve el logaritmo de un number
|
LOG10
|
Devuelve el logaritmo de un number en base 10
|
RAND
|
Devuelve un número de punto flotante pseudoaleatorio. |
ABS
Sintaxis:
abs[N <: INT32 | INT64 | FLOAT64](number: N) -> N
Descripción:
Devuelve el valor absoluto de un number.
- Se arroja un error cuando la función desbordaría un valor de
INT32oINT64.
Ejemplos:
| número | abs(number) |
|---|---|
| 10 | 10 |
| -10 | 10 |
| 10L | 10L |
| -0.0 | 0.0 |
| 10.5 | 10.5 |
| -10.5 | 10.5 |
| -231 | [error] |
| -263 | [error] |
AGREGAR
Sintaxis:
add[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Descripción:
Devuelve el valor de x + y.
Ejemplos:
| 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
Sintaxis:
subtract[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Descripción:
Devuelve el valor de x - y.
Ejemplos:
| 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
Sintaxis:
multiply[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Descripción:
Devuelve el valor de x * y.
Ejemplos:
| 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
Sintaxis:
divide[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Descripción:
Devuelve el valor de x / y. La división de números enteros se trunca.
Ejemplos:
| 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
Sintaxis:
mod[N <: INT32 | INT64 | FLOAT64](x: N, y: N) -> N
Descripción:
Devuelve el resto de x / y.
- Muestra un
errorcuandoyes cero para los tipos de números enteros (INT64). - Devuelve
NaNcuandoyes cero para los tipos de números de punto flotante (FLOAT64).
Ejemplos:
| 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
Sintaxis:
ceil[N <: INT32 | INT64 | FLOAT64](number: N) -> N
Descripción:
Devuelve el valor numérico más pequeño que no es menor que number.
Ejemplos:
| número | 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
Sintaxis:
floor[N <: INT32 | INT64 | FLOAT64](number: N) -> N
Descripción:
Devuelve el valor numérico más grande que no es mayor que number.
Ejemplos:
| número | 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
Sintaxis:
round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N) -> N
round[N <: INT32 | INT64 | FLOAT64 | DECIMAL128](number: N, places: INT64) -> N
Descripción:
Redondea places dígitos de un number. Redondea los dígitos a la derecha del punto decimal si places es positivo y a la izquierda del punto decimal si es negativo.
- Si solo se proporciona
number, se redondea al valor entero más cercano. - Redondea en dirección opuesta al cero en los casos de punto medio.
- Se arroja un
errorsi el redondeo con un valor deplacesnegativo genera un desbordamiento.
Ejemplos:
| número | cifras decimales | 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();
TRUNC
Sintaxis:
trunc[N <: Number](number: N) -> N
trunc[N <: Number](number: N, places: INT64) -> N
Descripción:
Trunca un number a una cantidad especificada de places decimales. Trunca los dígitos a la derecha del punto decimal si places es positivo y a la izquierda del punto decimal si es negativo.
- Si solo se proporciona
number, se trunca al valor entero más cercano a cero. - Se arroja un
errorsi el truncamiento genera un desbordamiento.
Ejemplos:
| número | cifras decimales | trunc(number, places) |
|---|---|---|
| 15.5 | 0 | 15.0 |
| -15.5 | 0 | -15.0 |
| 15 | 1 | 15 |
| 15 | 0 | 15 |
| 15 | -1 | 10 |
| 15 | -2 | 0 |
| 15.48924 | 1 | 15.4 |
| -15.48924 | 2 | -15.48 |
POW
Sintaxis:
pow(base: FLOAT64, exponent: FLOAT64) -> FLOAT64
Descripción:
Devuelve el valor de base elevado a la potencia de exponent.
Muestra un error si
base <= 0yexponentson negativos.Para cualquier
exponent,pow(1, exponent)es 1.Para cualquier
base,pow(base, 0)es 1.
Ejemplos:
| base | exponente | 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
Sintaxis:
sqrt[N <: FLOAT64 | DECIMAL128](number: N) -> N
Descripción:
Devuelve la raíz cuadrada de un number.
- Muestra un
errorsinumberes negativo.
Ejemplos:
| número | 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
Sintaxis:
exp(exponent: FLOAT64) -> FLOAT64
Descripción:
Devuelve el valor del número de Euler elevado a la potencia de exponent, también llamado función exponencial natural.
Ejemplos:
| exponente | 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
Sintaxis:
ln(number: FLOAT64) -> FLOAT64
Descripción:
Devuelve el logaritmo natural de number. Esta función es equivalente a log(number).
Ejemplos:
| número | 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
Sintaxis:
log(number: FLOAT64, base: FLOAT64) -> FLOAT64
log(number: FLOAT64) -> FLOAT64
Descripción:
Devuelve el logaritmo de number en base base.
- Si solo se proporciona
number, devuelve el logaritmo denumberenbase(sinónimo deln(number)).
Ejemplos:
| número | 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
Sintaxis:
log10(x: FLOAT64) -> FLOAT64
Descripción:
Devuelve el logaritmo de number en base 10.
Ejemplos:
| número | log10(number) |
|---|---|
| 100 | 2.0 |
-inf |
NaN |
+inf |
+inf |
x <= 0 |
[error] |
RAND
Sintaxis:
rand() -> FLOAT64
Descripción:
Devuelve un número de punto flotante pseudoaleatorio, elegido de forma uniforme entre 0.0 (inclusive) y 1.0 (exclusive).
Funciones de matríz
| Nombre | Descripción |
ARRAY
|
Devuelve un ARRAY que contiene un elemento para cada argumento de entrada.
|
ARRAY_CONCAT
|
Concatena varios arrays en un solo ARRAY.
|
ARRAY_CONTAINS
|
Devuelve TRUE si un ARRAY determinado contiene un valor específico.
|
ARRAY_CONTAINS_ALL
|
Devuelve TRUE si todos los valores están presentes en ARRAY.
|
ARRAY_CONTAINS_ANY
|
Devuelve TRUE si alguno de los valores está presente en ARRAY.
|
ARRAY_FILTER
|
Filtra los elementos de un ARRAY que no satisfacen un predicado.
|
ARRAY_FIRST
|
Devuelve el primer elemento en un ARRAY.
|
ARRAY_FIRST_N
|
Devuelve los primeros elementos n en un ARRAY.
|
ARRAY_GET
|
Devuelve el elemento en un índice determinado en un ARRAY.
|
ARRAY_INDEX_OF
|
Devuelve el índice de la primera ocurrencia de un valor en un ARRAY.
|
ARRAY_INDEX_OF_ALL
|
Devuelve todos los índices de un valor en un ARRAY.
|
ARRAY_LENGTH
|
Devuelve la cantidad de elementos en un ARRAY.
|
ARRAY_LAST
|
Devuelve el último elemento de un ARRAY.
|
ARRAY_LAST_N
|
Devuelve los últimos elementos de n en un ARRAY.
|
ARRAY_REVERSE
|
Invierte el orden de los elementos en un ARRAY.
|
ARRAY_SLICE
|
Devuelve un segmento de un ARRAY
|
ARRAY_TRANSFORM
|
Transforma los elementos de un ARRAY aplicando una expresión a cada elemento.
|
MAXIMUM
|
Devuelve el valor máximo en un ARRAY.
|
MAXIMUM_N
|
Devuelve los valores más grandes de n en un ARRAY.
|
MINIMUM
|
Devuelve el valor mínimo en un ARRAY.
|
MINIMUM_N
|
Devuelve los valores más pequeños de n en un ARRAY.
|
SUM
|
Devuelve la suma de todos los valores de NUMERIC en un ARRAY.
|
JOIN
|
Produce una concatenación de los elementos en un ARRAY como un valor de STRING.
|
ARRAY
Sintaxis:
array(values: ANY...) -> ARRAY
Descripción:
Construye un array a partir de los elementos proporcionados.
- Si no existe un argumento, se reemplaza por
NULLen el array resultante.
Ejemplos:
| valores | 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
Sintaxis:
array_concat(arrays: ARRAY...) -> ARRAY
Descripción:
Concatena dos o más arrays en un solo ARRAY.
Ejemplos:
| arreglos | 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
Sintaxis:
array_contains(array: ARRAY, value: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si se encuentra value en array y FALSE en caso contrario.
Ejemplos:
| array | valor | array_contains(array, value) |
|---|---|---|
| [1, 2, 3] | 2 | verdadero |
| [[1, 2], [3]] | [1, 2] | verdadero |
| [1, null] | nulo | verdadero |
| "abc" | CUALQUIERA | error |
Node.js
const result = await db.pipeline() .collection("books") .select(field("genre").arrayContains(constant("mystery")).as("isMystery")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("genre").arrayContains(constant("mystery")).as("isMystery")) );
Swift
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayContains(Constant("mystery")).as("isMystery")]) .execute()
Kotlin
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
Sintaxis:
array_contains_all(array: ARRAY, search_values: ARRAY) -> BOOLEAN
Descripción:
Devuelve TRUE si todos los search_values se encuentran en el array, y FALSE en caso contrario.
Ejemplos:
| array | search_values | array_contains_all(array, search_values) |
|---|---|---|
| [1, 2, 3] | [1, 2] | verdadero |
| [1, 2, 3] | [1, 4] | falso |
| [1, null] | [null] | verdadero |
| [NaN] | [NaN] | verdadero |
| [] | [] | verdadero |
| [1, 2, 3] | [] | verdadero |
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
Sintaxis:
array_contains_any(array: ARRAY, search_values: ARRAY) -> BOOLEAN
Descripción:
Devuelve TRUE si se encuentra alguno de los search_values en el array, y FALSE en caso contrario.
Ejemplos:
| array | search_values | array_contains_any(array, search_values) |
|---|---|---|
| [1, 2, 3] | [4, 1] | verdadero |
| [1, 2, 3] | [4, 5] | falso |
| [1, 2, null] | [null] | verdadero |
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_FILTER
Sintaxis:
array_filter(array: ARRAY, predicate: (ANY) -> BOOLEAN) -> ARRAY
Descripción:
Filtra array con una expresión predicate y devuelve un array nuevo solo con los elementos que satisfacen el predicado.
- Para cada elemento de
array, se evalúapredicate. Si devuelvetrue, el elemento se incluye en el resultado; de lo contrario (si devuelvefalseonull), se omite. - Si
predicatese evalúa como un valor no booleano o no nulo, la función devuelve un error.
Ejemplos:
| array | predicado | array_filter(array, predicate) |
|---|---|---|
| [1, 2, 3] | x -> x > 1 | [2, 3] |
| [1, nulo, 3] | x -> x > 1 | [3] |
| ["a", "b", "c"] | x -> x != "b" | ["a", "c"] |
| [] | x -> true | [] |
ARRAY_GET
Sintaxis:
array_get(array: ARRAY, index: INT64) -> ANY
Descripción:
Devuelve el elemento en el índice index basado en 0 en array.
- Si
indexes negativo, se accede a los elementos desde el final del array, donde-1es el último elemento. - Si
arrayno es del tipoARRAYninull, se devuelve un error. - Si
indexestá fuera de los límites, la función devuelve un valor ausente. - Si
indexno es del tipoINT64, la función muestra un error.
Ejemplos:
| array | índice | array_get(array, index) |
|---|---|---|
| [1, 2, 3] | 0 | 1 |
| [1, 2, 3] | -1 | 3 |
| [1, 2, 3] | 3 | ausente |
| [1, 2, 3] | -4 | ausente |
| "abc" | 0 | error |
| nulo | 0 | nulo |
Array |
"a" | error |
Array |
2.0 | error |
ARRAY_LENGTH
Sintaxis:
array_length(array: ARRAY) -> INT64
Descripción:
Devuelve la cantidad de elementos en un array.
Ejemplos:
| array | array_length(array) |
|---|---|
| [1, 2, 3] | 3 |
| [] | 0 |
| [1, 1, 1] | 3 |
| [1, null] | 2 |
Node.js
const result = await db.pipeline() .collection("books") .select(field("genre").arrayLength().as("genreCount")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("genre").arrayLength().as("genreCount")) );
Swift
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayLength().as("genreCount")]) .execute()
Kotlin
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
Sintaxis:
array_reverse(array: ARRAY) -> ARRAY
Descripción:
Invierte el array determinado.
Ejemplos:
| array | array_reverse(array) |
|---|---|
| [1, 2, 3] | [3, 2, 1] |
| ["a", "b"] | ["b", "a"] |
| [1, 2, 2, 3] | [3, 2, 2, 1] |
Node.js
const result = await db.pipeline() .collection("books") .select(arrayReverse(field("genre")).as("reversedGenres")) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select(field("genre").arrayReverse().as("reversedGenres")) );
Swift
let result = try await db.pipeline() .collection("books") .select([Field("genre").arrayReverse().as("reversedGenres")]) .execute()
Kotlin
Android
val result = db.pipeline() .collection("books") .select(field("genre").arrayReverse().alias("reversedGenres")) .execute()
Java
Task<Pipeline.Snapshot> result = db.pipeline() .collection("books") .select(field("genre").arrayReverse().alias("reversedGenres")) .execute();
Android
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();
ARRAY_FIRST
Sintaxis:
array_first(array: ARRAY) -> ANY
Descripción:
Devuelve el primer elemento de array. Esto equivale a array_get(array, 0).
- Si
arrayestá vacío, devuelve un valor ausente.
Ejemplos:
| array | array_first(array) |
|---|---|
| [1, 2, 3] | 1 |
| [] | ausente |
ARRAY_FIRST_N
Sintaxis:
array_first_n(array: ARRAY, n: INT64) -> ARRAY
Descripción:
Devuelve los primeros elementos n de array. Esto equivale a array_slice(array, 0, n).
- Si
nes negativo, se muestra un error.
Ejemplos:
| array | n | array_first_n(array, n) |
|---|---|---|
| [1, 2, 3, 4, 5] | 3 | [1, 2, 3] |
| [1, 2] | 3 | [1, 2] |
| [1, 2, 3] | 0 | [] |
ARRAY_INDEX_OF
Sintaxis:
array_index_of(array: ARRAY, value: ANY) -> INT64
Descripción:
Devuelve el índice basado en 0 del primer caso de value en array. Devuelve value si no se encuentra.
Ejemplos:
| array | valor | array_index_of(array, value) |
|---|---|---|
| [1, 2, 3, 2] | 2 | 1 |
| [1, 2, 3] | 4 | -1 |
| [1, nulo, 3] | nulo | 1 |
ARRAY_INDEX_OF_ALL
Sintaxis:
array_index_of_all(array: ARRAY, value: ANY) -> ARRAY<INT64>
Descripción:
Devuelve un array que contiene los índices basados en 0 de todos los casos de value en array. Muestra [] si no se encuentra value.
Ejemplos:
| array | valor | array_index_of_all(array, value) |
|---|---|---|
| [1, 2, 3, 2] | 2 | [1, 3] |
| [1, 2, 3] | 4 | [] |
| [1, nulo, 3, nulo] | nulo | [1, 3] |
ARRAY_LAST
Sintaxis:
array_last(array: ARRAY) -> ANY
Descripción:
Devuelve el último elemento de array. Esto equivale a array_get(array, -1).
- Si
arrayestá vacío, devuelve un valor ausente.
Ejemplos:
| array | array_last(array) |
|---|---|
| [1, 2, 3] | 3 |
| [] | ausente |
ARRAY_LAST_N
Sintaxis:
array_last_n(array: ARRAY, n: INT64) -> ARRAY
Descripción:
Devuelve los últimos elementos de n de array.
- Si
nes negativo, se muestra un error.
Ejemplos:
| array | n | array_last_n(array, n) |
|---|---|---|
| [1, 2, 3, 4, 5] | 3 | [3, 4, 5] |
| [1, 2] | 3 | [1, 2] |
| [1, 2, 3] | 0 | [] |
ARRAY_SLICE
Sintaxis:
array_slice(array: ARRAY, offset: INT64, length: INT64) -> ARRAY
Descripción:
Devuelve un subconjunto de array que comienza en el índice offset basado en 0 y que incluye elementos length.
- Si
offsetes negativo, indica la posición de inicio desde el final del array, en el que-1es el último elemento. - Si
lengthes mayor que la cantidad de elementos restantes en el array después deoffset, el resultado se extiende hasta el final del array. lengthdebe ser no negativo; de lo contrario, se devolverá un error.
Ejemplos:
| array | offset | longitud | array_slice(array, offset, length) |
|---|---|---|---|
| [1, 2, 3, 4, 5] | 1 | 3 | [2, 3, 4] |
| [1, 2, 3, 4, 5] | -2 | 2 | [4, 5] |
| [1, 2, 3] | 1 | 5 | [2, 3] |
| [1, 2, 3] | 3 | 2 | [] |
ARRAY_TRANSFORM
Sintaxis:
array_transform(array: ARRAY, expression: (ANY) -> ANY) -> ARRAY
array_transform(array: ARRAY, expression: (ANY, INT64) -> ANY) -> ARRAY
Descripción:
Transforma array aplicando expression a cada elemento y devuelve un array nuevo con los elementos transformados. El array de salida siempre tendrá el mismo tamaño que el array de entrada.
expressionpuede ser una función unariaelement -> resulto una función binaria(element, index) -> result.- Si
expressiones unario, se llama con cada elemento dearray. - Si
expressiones binaria, se llama con cada elemento dearrayy su índice correspondiente basado en 0.
Ejemplos:
| array | expresión | array_transform(array, expression) |
|---|---|---|
| [1, 2, 3] | x -> x * 2 | [2, 4, 6] |
| [1, 2, 3] | x -> x + 1 | [2, 3, 4] |
| [10, 20] | (x, i) -> x + i | [10, 21] |
| [] | x -> 1 | [] |
MAXIMUM
Sintaxis:
maximum(array: ARRAY) -> ANY
Descripción:
Devuelve el valor máximo en array.
- Los valores de
NULLse ignoran durante la comparación. - Si
arrayestá vacío o solo contiene valoresNULL, se devuelveNULL.
Ejemplos:
| array | maximum(array) |
|---|---|
| [1, 5, 2] | 5 |
| [1, nulo, 5] | 5 |
| ["a", "c", "b"] | "c" |
| [nulo, nulo] | nulo |
| [] | nulo |
MAXIMUM_N
Sintaxis:
maximum_n(array: ARRAY, n: INT64) -> ARRAY
Descripción:
Devuelve un array con los valores más grandes de n en array en orden descendente.
- Los valores
NULLse ignoran. - Si
nes negativo, se muestra un error.
Ejemplos:
| array | n | maximum_n(array, n) |
|---|---|---|
| [1, 5, 2, 4, 3] | 3 | [5, 4, 3] |
| [1, nulo, 5] | 3 | [5, 1] |
MINIMUM
Sintaxis:
minimum(array: ARRAY) -> ANY
Descripción:
Devuelve el valor mínimo en array.
- Los valores de
NULLse ignoran durante la comparación. - Si
arrayestá vacío o solo contiene valoresNULL, se devuelveNULL.
Ejemplos:
| array | minimum(array) |
|---|---|
| [1, 5, 2] | 1 |
| [5, nulo, 1] | 1 |
| ["a", "c", "b"] | "a" |
| [nulo, nulo] | nulo |
| [] | nulo |
MINIMUM_N
Sintaxis:
minimum_n(array: ARRAY, n: INT64) -> ARRAY
Descripción:
Devuelve un array con los valores más pequeños de n en array en orden ascendente.
- Los valores
NULLse ignoran. - Si
nes negativo, se muestra un error.
Ejemplos:
| array | n | minimum_n(array, n) |
|---|---|---|
| [1, 5, 2, 4, 3] | 3 | [1, 2, 3] |
| [5, nulo, 1] | 3 | [1, 5] |
SUM
Sintaxis:
sum(array: ARRAY) -> INT64 | FLOAT64
Descripción:
Devuelve la suma de todos los valores de NUMERIC en un ARRAY.
- Se ignoran los valores no numéricos del array.
- Si algún valor numérico del array es
NaN, la función devuelveNaN. - El tipo de datos que se devuelve se determina según el tipo numérico más amplio del array:
INT64<FLOAT64. - Si se produce un desbordamiento de números enteros de 64 bits antes de que se sume cualquier valor de punto flotante, se devuelve un error. Si se suman valores de punto flotante, el desbordamiento generará +/- infinito.
- Si el array no contiene valores numéricos, la función devuelve
NULL.
Ejemplos:
| array | sum(array) |
|---|---|
| [1, 2, 3] | 6L |
| [1L, 2L, 3L] | 6L |
| [2000000000, 2000000000] | 4000000000L |
| [10, 20.5] | 30.5 |
| [1, "a", 2] | 3L |
| [INT64.MAX_VALUE, 1] | error |
| [INT64.MAX_VALUE, 1, -1.0] | error |
| [INT64.MAX_VALUE, 1.0] | 9.223372036854776e+18 |
UNIRSE
Sintaxis:
join[T <: STRING | BYTES](array: ARRAY<T>, delimiter: T) -> STRING
join[T <: STRING | BYTES](array: ARRAY<T>, delimiter: T, null_text: T) -> STRING
Descripción:
Muestra una concatenación de los elementos en la array como una STRING. El array puede ser de tipos de datos STRING o BYTES.
- Todos los elementos de
array,delimiterynull_textdeben ser del mismo tipo: todos deben serSTRINGo todos deben serBYTES. - Si se proporciona
null_text, cualquier valorNULLenarrayse reemplaza pornull_text. - Si no se proporciona
null_text, los valores deNULLenarrayse omiten del resultado.
Ejemplos:
Cuando no se proporciona null_text:
| array | delimitador | join(array, delimiter) |
|---|---|---|
| ["a", "b", "c"] | "," | "a,b,c" |
| ["a", null, "c"] | "," | "a,c" |
| [b'a', b'b', b'c'] | b',' | b'a,b,c' |
| ["a", b'c'] | "," | error |
| ["a", "c"] | b',' | error |
| [b'a', b'c'] | "," | error |
Cuando se proporciona null_text, ocurre lo siguiente:
| array | delimitador | null_text | join(array, delimiter, null_text) |
|---|---|---|---|
| ["a", null, "c"] | "," | "MISSING" | "a,MISSING,c" |
| [b'a', null, b'c'] | b',' | b'NULL' | b'a,NULL,c' |
| [null, "b", null] | "," | "MISSING" | "MISSING,b,MISSING" |
| [b'a', null, null] | b',' | b'NULL' | b'a,NULL,NULL' |
| ["a", null] | "," | b'N' | error |
| [b'a', null] | b',' | "N" | error |
Funciones de comparación
| Nombre | Descripción |
EQUAL
|
Comparación de igualdad |
GREATER_THAN
|
Comparación de mayor que |
GREATER_THAN_OR_EQUAL
|
Comparación de mayor o igual que |
LESS_THAN
|
Comparación de menor que |
LESS_THAN_OR_EQUAL
|
Comparación de menor o igual que |
NOT_EQUAL
|
Comparación de no es igual que |
CMP
|
Comparación general |
EQUAL
Sintaxis:
equal(x: ANY, y: ANY) -> BOOLEAN
Ejemplos:
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 |
Descripción:
Devuelve TRUE si x y y son iguales, y FALSE en caso contrario.
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();
GREATER_THAN
Sintaxis:
greater_than(x: ANY, y: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si x es mayor que y, y FALSE en caso contrario.
Si x y y no son comparables, devuelve FALSE.
Ejemplos:
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();
GREATER_THAN_OR_EQUAL
Sintaxis:
greater_than_or_equal(x: ANY, y: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si x es mayor o igual que y, y FALSE en los demás casos.
Si x y y no son comparables, devuelve FALSE.
Ejemplos:
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
Sintaxis:
less_than(x: ANY, y: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si x es menor que y, y FALSE en caso contrario.
Si x y y no son comparables, devuelve FALSE.
Ejemplos:
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
Sintaxis:
less_than_or_equal(x: ANY, y: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si x es menor o igual que y, y FALSE en los demás casos.
Si x y y no son comparables, devuelve FALSE.
Ejemplos:
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
Sintaxis:
not_equal(x: ANY, y: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si x no es igual a y, y FALSE en caso contrario.
Ejemplos:
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();
CMP
Sintaxis:
cmp(x: ANY, y: ANY) -> Int64
Descripción:
Compara x y y, y devuelve lo siguiente:
1Lsixes mayor quey-1Lsixes menor quey0Len caso contrario
A diferencia de otras funciones de comparación, la función cmp(...) opera en todos los tipos y sigue el mismo orden que se usa en la etapa sort(...). Consulta Orden de los tipos de valor para obtener información sobre cómo se ordenan los valores en todos los tipos.
Ejemplos:
x |
y |
cmp(x, y) |
|---|---|---|
| 1L | 1L | 0L |
| 1.0 | 1L | 0L |
| -1.0 | 1L | -1L |
| 42.5D | "foo" | -1L |
NULL |
NULL |
0L |
NULL |
ABSENT |
0L |
Funciones de depuración
| Nombre | Descripción |
EXISTS
|
Devuelve TRUE si el valor no es un valor ausente.
|
IS_ABSENT
|
Devuelve TRUE si el valor es un valor ausente.
|
IF_ABSENT
|
Reemplaza el valor por una expresión si no está presente. |
IS_ERROR
|
Captura y verifica si la expresión subyacente arrojó un error. |
IF_ERROR
|
Reemplaza el valor por una expresión si generó un error. |
ERROR
|
Finaliza la evaluación y devuelve un error con el mensaje especificado. |
EXISTS
Sintaxis:
exists(value: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si value no es el valor ausente.
Ejemplos:
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
Ejemplo:
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
Ejemplo:
val result = db.pipeline() .collection("books") .select(field("rating").exists().alias("hasRating")) .execute()
Java
Android
Ejemplo:
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
Sintaxis:
is_absent(value: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si value es el valor ausente; de lo contrario, devuelve FALSE. Los valores ausentes son los que faltan en la entrada, como un campo de documento faltante.
Ejemplos:
value |
is_absent(value) |
|---|---|
| 0L | FALSE |
| "foo" | FALSE |
NULL |
FALSE |
ABSENT |
TRUE |
IF_ABSENT
Sintaxis:
if_absent(value: ANY, replacement: ANY) -> ANY
Descripción:
Si value es un valor ausente, evalúa y devuelve replacement. De lo contrario, muestra value.
Ejemplos:
value |
replacement |
if_absent(value, replacement) |
|---|---|---|
| 5L | 0L | 5L |
NULL |
0L | NULL |
ABSENT |
0L | 0L |
IS_ERROR
Sintaxis:
is_error(try: ANY) -> BOOLEAN
Descripción:
Devuelve TRUE si se produce un error durante la evaluación de try. De lo contrario, devuelve FALSE.
IF_ERROR
Sintaxis:
if_error(try: ANY, catch: ANY) -> ANY
Descripción:
Si se produce un error durante la evaluación de try, evalúa y devuelve replacement. De lo contrario, devuelve el valor resuelto de try.
ERROR
Sintaxis:
error(message: STRING) -> ANY
Descripción:
La evaluación de la función error hace que la evaluación de la canalización finalice con un error. El message proporcionado se incluye en el error.
Ejemplos:
cond |
res |
switch_on(cond, res, error("no condition matched")) |
|---|---|---|
TRUE |
1L | 1L |
FALSE |
1L | ERROR ("no condition matched") |
Funciones de referencia
El tipo REFERENCE actúa como un "puntero" a otros documentos de la base de datos (o incluso a otras bases de datos). Las siguientes funciones permiten manipular este tipo durante la ejecución de la consulta.
| Nombre | Descripción |
COLLECTION_ID
|
Devuelve el ID de la colección de hojas en la referencia dada. |
DOCUMENT_ID
|
Devuelve el ID del documento en la referencia determinada. |
PARENT
|
Devuelve la referencia principal. |
REFERENCE_SLICE
|
Devuelve un subconjunto de segmentos de la referencia proporcionada. |
COLLECTION_ID
Sintaxis:
collection_id(ref: REFERENCE) -> STRING
Descripción:
Devuelve el ID de la colección de hojas del REFERENCE determinado.
Ejemplos:
ref |
collection_id(ref) |
|---|---|
users/user1 |
"users" |
users/user1/posts/post1 |
"posts" |
DOCUMENT_ID
Sintaxis:
document_id(ref: REFERENCE) -> ANY
Descripción:
Devuelve el ID del documento del REFERENCE determinado.
Ejemplos:
ref |
document_id(ref) |
|---|---|
users/user1 |
"user1" |
users/user1/posts/post1 |
"post1" |
PARENT
Sintaxis:
parent(ref: REFERENCE) -> REFERENCE
Descripción:
Devuelve el REFERENCE principal de la referencia determinada o NULL si la referencia ya es una raíz.
Ejemplos:
ref |
parent(ref) |
|---|---|
/ |
NULL |
users/user1 |
/ |
users/user1/posts/post1 |
users/user1 |
REFERENCE_SLICE
Sintaxis:
reference_slice(ref: REFERENCE, offset: INT, length: INT) -> REFERENCE
Descripción:
Un REFERENCE es una lista de tuplas (collection_id, document_id), lo que permite obtener una vista de esa lista, al igual que array_slice(...).
Devuelve un nuevo REFERENCE que es un subconjunto de los segmentos del ref determinado.
offset: Es el índice inicial (basado en 0) de la división. Si es negativo, es una compensación desde el final de la referencia.length: Es la cantidad de segmentos que se incluirán en la segmentación.
Ejemplos:
ref |
offset |
length |
reference_slice(ref, offset, length) |
|---|---|---|---|
a/1/b/2/c/3 |
1L | 2L | b/2/c/3 |
a/1/b/2/c/3 |
0L | 2L | a/1/b/2 |
a/1/b/2/c/3 |
-2L | 2L | c/3 |
Funciones lógicas
| Nombre | Descripción |
AND
|
Realiza un AND lógico |
OR
|
Realiza una operación OR lógica |
XOR
|
Realiza un XOR lógico |
NOT
|
Realiza una operación NOT lógica |
NOR
|
Realiza una operación NOR lógica |
CONDITIONAL
|
Ramifica la evaluación según una expresión condicional. |
IF_NULL
|
Devuelve el primer valor no nulo. |
SWITCH_ON
|
Ramifica la evaluación según una serie de condiciones |
EQUAL_ANY
|
Comprueba si un valor es igual a algún elemento de un array. |
NOT_EQUAL_ANY
|
Comprueba si un valor no es igual a ningún elemento de un array. |
MAXIMUM
|
Devuelve el valor máximo de un conjunto de valores. |
MINIMUM
|
Devuelve el valor mínimo de un conjunto de valores. |
Y
Sintaxis:
and(x: BOOLEAN...) -> BOOLEAN
Descripción:
Devuelve el AND lógico de dos o más valores booleanos.
Devuelve NULL si no se puede derivar el resultado debido a que alguno de los valores proporcionados es ABSENT o NULL.
Ejemplos:
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();
OR
Sintaxis:
or(x: BOOLEAN...) -> BOOLEAN
Descripción:
Devuelve el valor OR lógico de dos o más valores booleanos.
Devuelve NULL si no se puede derivar el resultado debido a que alguno de los valores proporcionados es ABSENT o NULL.
Ejemplos:
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
Sintaxis:
xor(x: BOOLEAN...) -> BOOLEAN
Descripción:
Devuelve el XOR lógico de dos o más valores booleanos.
Devuelve NULL si alguno de los valores proporcionados es ABSENT o NULL.
Ejemplos:
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();
NOR
Sintaxis:
nor(x: BOOLEAN...) -> BOOLEAN
Descripción:
Devuelve el valor NOR lógico de dos o más valores booleanos.
Devuelve NULL si no se puede derivar el resultado debido a que alguno de los valores proporcionados es ABSENT o NULL.
Ejemplos:
x |
y |
nor(x, y) |
|---|---|---|
TRUE |
TRUE |
FALSE |
FALSE |
TRUE |
FALSE |
FALSE |
FALSE |
TRUE |
NULL |
TRUE |
FALSE |
ABSENT |
TRUE |
FALSE |
NULL |
FALSE |
NULL |
FALSE |
ABSENT |
NULL |
NOT
Sintaxis:
not(x: BOOLEAN) -> BOOLEAN
Descripción:
Devuelve el NOT lógico de un valor 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();
CONDITIONAL
Sintaxis:
conditional(condition: BOOLEAN, true_case: ANY, false_case: ANY) -> ANY
Descripción:
Evalúa y devuelve true_case si condition se evalúa como TRUE.
Evalúa y devuelve false_case si la condición se resuelve como FALSE, NULL o un valor ABSENT.
Ejemplos:
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();
IF_NULL
Sintaxis:
if_null(expr: ANY, replacement: ANY) -> ANY
Descripción:
Devuelve expr si no es NULL; de lo contrario, evalúa y devuelve replacement. La expresión replacement no se evalúa si se usa expr.
Ejemplos:
expr |
replacement |
if_null(expr, replacement) |
|---|---|---|
| 1L | 2L | 1L |
NULL |
2L | 2L |
ABSENT |
2L | ABSENT |
SWITCH_ON
Sintaxis:
switch_on(cond1: BOOLEAN, res1: ANY, cond2: BOOLEAN, res2: ANY, ..., [default: ANY]) -> ANY
Descripción:
Evalúa una serie de condiciones y devuelve el resultado asociado a la primera condición TRUE. Si ninguna condición se evalúa como TRUE, se devuelve el valor default si se proporciona. Si no se proporciona ningún valor default, se arroja un error si ninguna otra condición se evalúa como TRUE.
Para proporcionar un valor default, pásalo como el argumento final de modo que haya una cantidad impar de argumentos.
Ejemplos:
x |
switch_on(eq(x, 1L), "one", eq(x, 2L), "two", "other") |
|---|---|
| 1L | “uno” |
| 2L | "two" |
| 3L | "other" |
EQUAL_ANY
Sintaxis:
equal_any(value: ANY, search_space: ARRAY) -> BOOLEAN
Descripción:
Devuelve TRUE si value está en el array search_space.
Ejemplos:
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
Sintaxis:
not_equal_any(value: ANY, search_space: ARRAY) -> BOOLEAN
Descripción:
Devuelve TRUE si value no está en el array search_space.
Ejemplos:
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();
MAXIMUM
Sintaxis:
maximum(x: ANY...) -> ANY
maximum(x: ARRAY) -> ANY
Descripción:
Devuelve el valor máximo que no es NULL ni ABSENT en una serie de valores x.
Si no hay valores que no sean NULL ni ABSENT, se devuelve NULL.
Si hay varios valores equivalentes máximos, se puede devolver cualquiera de ellos. El orden de los tipos de valor sigue el orden documentado.
Ejemplos:
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
Sintaxis:
minimum(x: ANY...) -> ANY
minimum(x: ARRAY) -> ANY
Descripción:
Devuelve el valor mínimo que no es NULL ni ABSENT en una serie de valores x.
Si no hay valores que no sean NULL ni ABSENT, se devuelve NULL.
Si hay varios valores equivalentes mínimos, se puede devolver cualquiera de ellos. El orden de los tipos de valor sigue el orden documentado.
Ejemplos:
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();
Funciones de mapa
| Nombre | Descripción |
MAP
|
Construye un valor de mapa a partir de una serie de pares clave-valor. |
MAP_GET
|
Devuelve el valor de un mapa para una clave especificada. |
MAP_SET
|
Devuelve una copia de un mapa con una serie de claves actualizadas. |
MAP_REMOVE
|
Devuelve una copia de un mapa con una serie de claves quitadas. |
MAP_MERGE
|
Combina una serie de mapas. |
CURRENT_CONTEXT
|
Devuelve el contexto actual como un mapa. |
MAP_KEYS
|
Devuelve un array de todas las claves de un mapa. |
MAP_VALUES
|
Devuelve un array de todos los valores de un mapa. |
MAP_ENTRIES
|
Devuelve un array de pares clave-valor de un mapa. |
MAPA
Sintaxis:
map(key: STRING, value: ANY, ...) -> MAP
Descripción:
Construye un mapa a partir de una serie de pares clave-valor.
MAP_GET
Sintaxis:
map_get(map: ANY, key: STRING) -> ANY
Descripción:
Devuelve el valor de un mapa para una clave especificada. Devuelve un valor ABSENT si el key no existe en el mapa o si el argumento map no es 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
Sintaxis:
map_set(map: MAP, key: STRING, value: ANY, ...) -> MAP
Descripción:
Devuelve una copia del valor de map con su contenido actualizado por una serie de pares clave-valor.
Si el valor proporcionado se resuelve en un valor ausente, se quita la clave asociada del mapa.
Si el argumento map no es un MAP, devuelve un valor ausente.
MAP_REMOVE
Sintaxis:
map_remove(map: MAP, key: STRING...) -> MAP
Descripción:
Devuelve una copia del valor de map con una serie de claves quitadas.
MAP_MERGE
Sintaxis:
map_merge(maps: MAP...) -> MAP
Combina el contenido de 2 o más mapas. Si varios mapas tienen valores en conflicto, se usa el último valor.
CURRENT_CONTEXT
Sintaxis:
current_context() -> MAP
Devuelve un mapa que contiene todos los campos disponibles en el punto de ejecución actual.
MAP_KEYS
Sintaxis:
map_keys(map: MAP) -> ARRAY<STRING>
Descripción:
Devuelve un array que contiene todas las claves del valor map.
MAP_VALUES
Sintaxis:
map_values(map: MAP) -> ARRAY<ANY>
Descripción:
Devuelve un array que contiene todos los valores del valor map.
MAP_ENTRIES
Sintaxis:
map_entries(map: MAP) -> ARRAY<MAP>
Descripción:
Devuelve un array que contiene todos los pares clave-valor en el valor de map.
Cada par clave-valor tendrá la forma de un mapa con dos entradas, k y v.
Ejemplos:
map |
map_entries(map) |
|---|---|
| {} | [] |
| {"foo" : 2L} | [{"k": "foo", "v" : 2L}] |
| {"foo" : "bar", "bar" : "foo"} | [{"k": "foo", "v" : "bar" }, {"k" : "bar", "v": "foo"}] |
Funciones de string
| Nombre | Descripción |
BYTE_LENGTH
|
Devuelve la cantidad de BYTES en un valor de STRING o BYTES.
|
CHAR_LENGTH
|
Devuelve la cantidad de caracteres Unicode en un valor STRING.
|
STARTS_WITH
|
Devuelve TRUE si una STRING comienza con un prefijo determinado.
|
ENDS_WITH
|
Devuelve TRUE si una STRING termina con un sufijo determinado.
|
LIKE
|
Devuelve TRUE si una STRING coincide con un patrón.
|
REGEX_CONTAINS
|
Devuelve TRUE si un valor coincide parcial o completamente con una expresión regular
|
REGEX_MATCH
|
Devuelve TRUE si alguna parte de un valor coincide con una expresión regular
|
STRING_CONCAT
|
Concatena varias STRING en una sola STRING.
|
STRING_CONTAINS
|
Devuelve TRUE si un valor contiene una STRING.
|
STRING_INDEX_OF
|
Devuelve el índice basado en 0 de la primera ocurrencia de un valor de STRING o BYTES.
|
TO_UPPER
|
Convierte un valor STRING o BYTES en mayúsculas.
|
TO_LOWER
|
Convierte un valor STRING o BYTES en minúsculas.
|
SUBSTRING
|
Obtiene una subcadena de un valor STRING o BYTES.
|
STRING_REVERSE
|
Invierte un valor STRING o BYTES.
|
STRING_REPEAT
|
Repite un valor STRING o BYTES una cantidad especificada de veces.
|
STRING_REPLACE_ALL
|
Reemplaza todos los casos de un valor STRING o BYTES.
|
STRING_REPLACE_ONE
|
Reemplaza la primera ocurrencia de un valor STRING o BYTES.
|
TRIM
|
Recorta los caracteres iniciales y finales de un valor STRING o BYTES.
|
LTRIM
|
Recorta los caracteres iniciales de un valor STRING o BYTES.
|
RTRIM
|
Recorta los caracteres finales de un valor STRING o BYTES.
|
SPLIT
|
Divide un valor STRING o BYTES en un array.
|
BYTE_LENGTH
Sintaxis:
byte_length[T <: STRING | BYTES](value: T) -> INT64
Descripción:
Devuelve la cantidad de BYTES en un valor STRING o BYTES.
Ejemplos:
| valor | 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
Sintaxis:
char_length(value: STRING) -> INT64
Descripción:
Devuelve la cantidad de puntos de código Unicode en el valor de STRING.
Ejemplos:
| valor | char_length(value) |
|---|---|
| "abc" | 3 |
| "hello" | 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
Sintaxis:
starts_with(value: STRING, prefix: STRING) -> BOOLEAN
Descripción:
Devuelve TRUE si value comienza con prefix.
Ejemplos:
| valor | prefijo | starts_with(value, prefix) |
|---|---|---|
| "abc" | "a" | verdadero |
| "abc" | "b" | falso |
| "abc" | "" | verdadero |
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
Sintaxis:
ends_with(value: STRING, postfix: STRING) -> BOOLEAN
Descripción:
Devuelve TRUE si value termina con postfix.
Ejemplos:
| valor | postfix | ends_with(value, postfix) |
|---|---|---|
| "abc" | "c" | verdadero |
| "abc" | "b" | falso |
| "abc" | "" | verdadero |
Node.js
const result = await db.pipeline() .collection("inventory/devices/laptops") .select( field("name").endsWith("16 inch") .as("16InLaptops") ) .execute();
Swift
let result = try await db.pipeline() .collection("inventory/devices/laptops") .select([ Field("name").endsWith("16 inch") .as("16InLaptops") ]) .execute()
Kotlin
Android
val result = db.pipeline() .collection("inventory/devices/laptops") .select( field("name").endsWith("16 inch") .alias("16InLaptops") ) .execute()
Java
Android
Task<Pipeline.Snapshot> result = db.pipeline() .collection("inventory/devices/laptops") .select( field("name").endsWith("16 inch") .alias("16InLaptops") ) .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field result = ( client.pipeline() .collection("inventory/devices/laptops") .select(Field.of("name").ends_with("16 inch").as_("16InLaptops")) .execute() )
Java
Pipeline.Snapshot result = firestore .pipeline() .collection("inventory/devices/laptops") .select(endsWith(field("name"), "16 inch").as("16InLaptops")) .execute() .get();
LIKE
Sintaxis:
like(value: STRING, pattern: STRING) -> BOOLEAN
Descripción:
Devuelve TRUE si value coincide con pattern.
Ejemplos:
| valor | patrón | like(value, pattern) |
|---|---|---|
| "Firestore" | "Fire%" | verdadero |
| "Firestore" | "%store" | verdadero |
| "Datastore" | "Data_tore" | verdadero |
| "100%" | "100\%" | verdadero |
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
Sintaxis:
regex_contains(value: STRING, pattern: STRING) -> BOOLEAN
Descripción:
Devuelve TRUE si alguna parte de value coincide con pattern. Si pattern no es una expresión regular válida, esta función devuelve un error.
Las expresiones regulares siguen la sintaxis de la biblioteca re2.
Ejemplos:
| valor | patrón | regex_contains(value, pattern) |
|---|---|---|
| "Firestore" | "Fire" | verdadero |
| "Firestore" | "store$" | verdadero |
| "Firestore" | "data" | 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
Sintaxis:
regex_match(value: STRING, pattern: STRING) -> BOOLEAN
Descripción:
Devuelve TRUE si value coincide por completo con pattern. Si pattern no es una expresión regular válida, esta función devuelve un error.
Las expresiones regulares siguen la sintaxis de la biblioteca re2.
Ejemplos:
| valor | patrón | regex_match(value, pattern) |
|---|---|---|
| "Firestore" | "F.*store" | verdadero |
| "Firestore" | "Fire" | falso |
| "Firestore" | "^F.*e$" | verdadero |
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
Sintaxis:
string_concat(values: STRING...) -> STRING
Descripción:
Concatena uno o más valores STRING en un solo resultado.
Ejemplos:
| argumentos | string_concat(values...) |
|---|---|
() |
error |
("a") |
"a" |
("abc", "def") |
"abcdef" |
("a", "", "c") |
"ac" |
Node.js
const result = await db.pipeline() .collection("books") .select( field("title").stringConcat(" by ", field("author")) .as("fullyQualifiedTitle") ) .execute();
Web
const result = await execute(db.pipeline() .collection("books") .select( field("title").stringConcat(" by ", field("author")) .as("fullyQualifiedTitle") ) );
Swift
let result = try await db.pipeline() .collection("books") .select([ Field("title").concat([" by ", Field("author")]) .as("fullyQualifiedTitle") ]) .execute()
Kotlin
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
Sintaxis:
string_contains(value: STRING, substring: STRING) -> BOOLEAN
Descripción:
Comprueba si value contiene la cadena literal substring.
Ejemplos:
| valor | subcadena | string_contains(value, substring) |
|---|---|---|
| "abc" | "b" | verdadero |
| "abc" | "d" | falso |
| "abc" | "" | verdadero |
| "a.c" | "." | verdadero |
| "☃☃☃" | "☃" | verdadero |
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();
STRING_INDEX_OF
Sintaxis:
string_index_of[T <: STRING | BYTES](value: T, search: T) -> INT64
Descripción:
Devuelve el índice basado en 0 del primer caso de search en value.
- Muestra
-1si no se encuentrasearch. - Si
valuees un valor deSTRING, el resultado se mide en puntos de código Unicode. Si es un valorBYTES, se mide en bytes. - Si
searches un valor deSTRINGoBYTESvacío, el resultado es0.
Ejemplos:
| valor | search | string_index_of(value, search) |
|---|---|---|
| "hello world" | "o" | 4 |
| "hello world" | "l" | 2 |
| "hello world" | "z" | -1 |
| "banana" | "na" | 2 |
| "abc" | "" | 0 |
| b"abc" | b"b" | 1 |
| "é" | "é" | 0 |
| b"é" | b"é" | 0 |
TO_UPPER
Sintaxis:
to_upper[T <: STRING | BYTES](value: T) -> T
Descripción:
Convierte un valor STRING o BYTES en mayúsculas.
Si un byte o un char no corresponde a un carácter alfabético en minúscula UTF-8, se pasa sin cambios.
Ejemplos:
| valor | 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
Sintaxis:
to_lower[T <: STRING | BYTES](value: T) -> T
Descripción:
Convierte un valor STRING o BYTES en minúsculas.
Si un byte o un char no corresponde a un carácter alfabético en mayúsculas UTF-8, se pasa sin cambios.
Ejemplos:
| valor | 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
Sintaxis:
substring[T <: STRING | BYTES](input: T, position: INT64) -> T
substring[T <: STRING | BYTES](input: T, position: INT64, length: INT64) -> T
Descripción:
Devuelve una subcadena de input que comienza en position (índice basado en cero) y que incluye hasta entradas length. Si no se proporciona ningún length, devuelve la subcadena desde position hasta el final de input.
Si
inputes un valor deSTRING,positionylengthse miden en puntos de código Unicode. Si es un valorBYTES, se miden en bytes.Si
positiones mayor que la longitud deinput, se devuelve una subcadena vacía. Sipositionmáslengthes mayor que la longitud deinput, la subcadena se trunca hasta el final deinput.Si
positiones negativo, la posición se toma desde el final de la entrada. Si lapositionnegativa es mayor que el tamaño de la entrada, la posición se establece en cero.lengthno debe ser un valor negativo.
Ejemplos:
Cuando no se proporciona length:
| entrada | posición | substring(input, position) |
|---|---|---|
| "abc" | 0 | "abc" |
| "abc" | 1 | "bc" |
| "abc" | 3 | "" |
| "abc" | -1 | "c" |
| b"abc" | 1 | b"bc" |
Cuando se proporciona length, ocurre lo siguiente:
| entrada | posición | longitud | 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
Sintaxis:
string_reverse[T <: STRING | BYTES](input: T) -> T
Descripción:
Devuelve la entrada proporcionada en orden inverso.
Los caracteres se delimitan por puntos de código Unicode cuando la entrada es un STRING y por bytes cuando la entrada es un valor de BYTES.
Ejemplos:
| entrada | string_reverse(input) |
|---|---|
| "abc" | "cba" |
| "a🌹b" | "b🌹a" |
| "hello" | "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();
STRING_REPEAT
Sintaxis:
string_repeat[T <: STRING | BYTES](input: T, repetitions: INT64) -> T
Descripción:
Devuelve el valor de input repetido repetitions veces.
repetitionsdebe ser un número entero no negativo- Si
repetitionses0, devuelve un valor vacío del mismo tipo queinput. - Si el resultado supera el tamaño máximo permitido (1 MB), se muestra un error.
Ejemplos:
| entrada | repeticiones | string_repeat(input, repetitions) |
|---|---|---|
| "foo" | 3 | "foofoofoo" |
| "foo" | 0 | "" |
| "a " | 3 | "a a a " |
| b"ab" | 2 | b"abab" |
| "é🦆" | 2 | "é🦆é🦆" |
STRING_REPLACE_ALL
Sintaxis:
string_replace_all[T <: STRING | BYTES](input: T, find: T, replacement: T) -> T
Descripción:
Reemplaza todos los casos no superpuestos de find en input por replacement.
- Las coincidencias distinguen mayúsculas de minúsculas.
- Si
findestá vacío, no se realizan reemplazos.
Ejemplos:
| entrada | buscar | reemplazo | string_replace_all(input, find, replacement) |
|---|---|---|---|
| "foobarfoo" | "foo" | "baz" | "bazbarbaz" |
| "ababab" | "aba" | "c" | "cbab" |
| "foobar" | "o" | "" | "fbar" |
| "é🦆🌎🦆" | "🦆" | "a" | "éa🌎a" |
| b"abc" | b"b" | b"d" | b"adc" |
STRING_REPLACE_ONE
Sintaxis:
string_replace_one[T <: STRING | BYTES](input: T, find: T, replacement: T) -> T
Descripción:
Reemplaza el primer caso de find en input por replacement.
- Las coincidencias distinguen mayúsculas de minúsculas.
- Si
findestá vacío, no se realizan reemplazos.
Ejemplos:
| entrada | buscar | reemplazo | string_replace_one(input, find, replacement) |
|---|---|---|---|
| "foobarfoo" | "foo" | "baz" | "bazbarfoo" |
| "é" | "é" | "a" | "a" |
| b"foobar" | b"o" | b"z" | b"fzoobar" |
TRIM
Sintaxis:
trim[T <: STRING | BYTES](input: T, values_to_trim: T) -> T
trim[T <: STRING | BYTES](input: T) -> T
Descripción:
Corta un conjunto especificado de BYTES o CHARS del principio y el final de la input proporcionada.
- Si no se proporciona ningún
values_to_trim, se quitan los caracteres de espacio en blanco.
Ejemplos:
Cuando no se proporciona values_to_trim:
| entrada | 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" |
Cuando se proporciona values_to_trim, ocurre lo siguiente:
| entrada | values_to_trim | trim(input, values_to_trim) |
|---|---|---|
| "abcbfooaacb" | "abc" | "foo" |
| "abcdaabadbac" | "abc" | "daabad" |
| b"C1C2C3" | b"C1" | b"C2C3" |
| b"C1C2" | "foo" | error |
| "foo" | b"C1" | error |
Web
const result = await execute(db.pipeline() .collection("books") .select( field("name").trim().as("whitespaceTrimmedName") ) );
Swift
let result = try await db.pipeline() .collection("books") .select([ Field("name").trim(" \n\t").as("whitespaceTrimmedName") ]) .execute()
Kotlin
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();
LTRIM
Sintaxis:
ltrim[T <: STRING | BYTES](value: T, to_trim: T) -> T
ltrim[T <: STRING | BYTES](value: T) -> T
Descripción:
Corta un conjunto especificado de BYTES o CHARS del principio de la value proporcionada.
- Si no se proporciona
to_trim, se quitan los caracteres de espacio en blanco iniciales.
Ejemplos:
Cuando no se proporciona to_trim:
| valor | ltrim(value) |
|---|---|
| " foo " | "foo " |
| "foo" | "foo" |
Cuando se proporciona to_trim, ocurre lo siguiente:
| valor | to_trim | ltrim(value, to_trim) |
|---|---|---|
| "aaabc" | "a" | "bc" |
| "abacaba" | “ba” | "caba" |
| "é" | "é" | "" |
RTRIM
Sintaxis:
rtrim[T <: STRING | BYTES](value: T, to_trim: T) -> T
rtrim[T <: STRING | BYTES](value: T) -> T
Descripción:
Corta un conjunto especificado de BYTES o CHARS del final del value proporcionado.
- Si no se proporciona
to_trim, se quitan los caracteres de espacio en blanco finales.
Ejemplos:
Cuando no se proporciona to_trim:
| valor | rtrim(value) |
|---|---|
| " foo " | " foo" |
| "foo" | "foo" |
Cuando se proporciona to_trim, ocurre lo siguiente:
| valor | to_trim | rtrim(value, to_trim) |
|---|---|---|
| "abccc" | "c" | "ab" |
| "abacaba" | “ba” | "abac" |
| "é" | "é" | "" |
SPLIT
Sintaxis:
split(input: STRING) -> ARRAY<STRING>
split[T <: STRING | BYTES](input: T, delimiter: T) -> ARRAY<T>
Descripción:
Divide un valor STRING o BYTES con un delimitador.
Para
STRING, el delimitador predeterminado es la coma,. El delimitador se trata como una sola cadena.Para
BYTES, debes especificar un delimitador.La división en un delimitador vacío produce un array de puntos de código Unicode para los valores de
STRINGy un array deBYTESpara los valores deBYTES.Dividir una
STRINGvacía devuelve unARRAYcon una únicaSTRINGvacía.
Ejemplos:
Cuando no se proporciona delimiter:
| entrada | split(input) |
|---|---|
| "foo,bar,foo" | ["foo", "bar", "foo"] |
| "foo" | ["foo"] |
| ",foo," | ["", "foo", ""] |
| "" | [""] |
| b"C120C2C4" | error |
Cuando se proporciona delimiter, ocurre lo siguiente:
| entrada | delimitador | 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" | error |
Funciones de marca de tiempo
| Nombre | Descripción |
CURRENT_TIMESTAMP
|
Genera un TIMESTAMP que corresponde a la hora de la solicitud.
|
TIMESTAMP_TRUNC
|
Trunca un objeto TIMESTAMP a un nivel de detalle determinado.
|
UNIX_MICROS_TO_TIMESTAMP
|
Convierte la cantidad de microsegundos desde 1970-01-01 00:00:00 UTC en un objeto TIMESTAMP.
|
UNIX_MILLIS_TO_TIMESTAMP
|
Convierte la cantidad de milisegundos desde 1970-01-01 00:00:00 UTC en un objeto TIMESTAMP.
|
UNIX_SECONDS_TO_TIMESTAMP
|
Convierte la cantidad de segundos desde 1970-01-01 00:00:00 UTC en un objeto TIMESTAMP.
|
TIMESTAMP_ADD
|
Agrega un intervalo de tiempo a un objeto TIMESTAMP
|
TIMESTAMP_SUB
|
Resta un intervalo de tiempo a un objeto TIMESTAMP
|
TIMESTAMP_TO_UNIX_MICROS
|
Convierte un objeto TIMESTAMP en la cantidad de microsegundos desde 1970-01-01 00:00:00 UTC.
|
TIMESTAMP_TO_UNIX_MILLIS
|
Convierte un objeto TIMESTAMP en la cantidad de milisegundos desde 1970-01-01 00:00:00 UTC.
|
TIMESTAMP_TO_UNIX_SECONDS
|
Convierte un objeto TIMESTAMP en la cantidad de segundos transcurridos desde 1970-01-01 00:00:00 UTC.
|
TIMESTAMP_DIFF
|
Devuelve el número entero de intervalos unit especificados entre dos TIMESTAMP.
|
TIMESTAMP_EXTRACT
|
Extrae un part específico (p. ej., año, mes, día) de un TIMESTAMP.
|
CURRENT_TIMESTAMP
Sintaxis:
current_timestamp() -> TIMESTAMP
Descripción:
Obtiene la marca de tiempo al comienzo de la hora de solicitud input (interpretada como la cantidad de microsegundos desde 1970-01-01 00:00:00 UTC).
Este valor es estable dentro de una consulta y siempre se resolverá en el mismo valor si se llama varias veces.
TIMESTAMP_TRUNC
Sintaxis:
timestamp_trunc(timestamp: TIMESTAMP, granularity: STRING[, timezone: STRING]) -> TIMESTAMP
Descripción:
Trunca una marca de tiempo a un nivel de detalle determinado.
El argumento granularity debe ser una cadena y uno de los siguientes:
microsecondmillisecondsecondminutehourdayweekweek([weekday])monthquarteryearisoyear
Si se proporciona el argumento timezone, el truncamiento se basará en los límites del calendario de la zona horaria proporcionada (p. ej., el truncamiento del día se truncará a la medianoche en la zona horaria proporcionada). El truncamiento respetará el horario de verano.
Si no se proporciona timezone, el truncamiento se basará en los límites del calendario UTC.
El argumento timezone debe ser una representación de cadena de una zona horaria de la base de datos tz, por ejemplo, America/New_York. También se puede usar una compensación de tiempo personalizada especificando una compensación desde GMT.
Ejemplos:
timestamp |
granularity |
timezone |
timestamp_trunc(timestamp, granularity, timezone) |
|---|---|---|---|
| 2000-01-01 10:20:30:123456 UTC | "second" | No proporcionado | 2001-01-01 10:20:30 UTC |
| 1997-05-31 04:30:30 UTC | "day" | No proporcionado | 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) | No proporcionado | 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
Sintaxis:
unix_micros_to_timestamp(input: INT64) -> TIMESTAMP
Descripción:
Convierte el objeto input (interpretado como la cantidad de microsegundos desde 1970-01-01 00:00:00 UTC) en un objeto TIMESTAMP. Muestra un error si input no se puede convertir en un objeto TIMESTAMP válido.
Ejemplos:
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
Sintaxis:
unix_millis_to_timestamp(input: INT64) -> TIMESTAMP
Descripción:
Convierte un objeto input (interpretado como la cantidad de milisegundos desde 1970-01-01 00:00:00 UTC) en un objeto TIMESTAMP. Muestra un error si input no se puede convertir en un objeto TIMESTAMP válido.
Ejemplos:
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
Sintaxis:
unix_seconds_to_timestamp(input: INT64) -> TIMESTAMP
Descripción:
Convierte un objeto input (interpretado como la cantidad de segundos desde 1970-01-01 00:00:00 UTC) en un objeto TIMESTAMP. Muestra un error si input no se puede convertir en un objeto TIMESTAMP válido.
Ejemplos:
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
Sintaxis:
timestamp_add(timestamp: TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP
Descripción:
Agrega un amount de unit desde timestamp. El argumento amount puede ser negativo, en cuyo caso equivale a TIMESTAMP_SUB.
El argumento unit debe ser una cadena y uno de los siguientes:
microsecondmillisecondsecondminutehourday
Se genera un error si la marca de tiempo resultante no se ajusta al rango de TIMESTAMP.
Ejemplos:
timestamp |
unit |
amount |
timestamp_add(timestamp, unit, amount) |
|---|---|---|---|
| 2025-02-20 00:00:00 UTC | "minute" | 2L | 2025-02-20 00:02:00 UTC |
| 2025-02-20 00:00:00 UTC | "hour" | -4L | 2025-02-19 20:00:00 UTC |
| 2025-02-20 00:00:00 UTC | "day" | 5L | 2025-02-25 00:00:00 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("createdAt").timestampAdd("day", 3653).as("expiresAt") ) .execute();
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
Sintaxis:
timestamp_sub(timestamp: TIMESTAMP, unit: STRING, amount: INT64) -> TIMESTAMP
Descripción:
Resta una amount de unit a timestamp. El argumento amount puede ser negativo, en cuyo caso equivale a TIMESTAMP_ADD.
El argumento unit debe ser una cadena y uno de los siguientes:
microsecondmillisecondsecondminutehourday
Se genera un error si la marca de tiempo resultante no se ajusta al rango de TIMESTAMP.
Ejemplos:
timestamp |
unit |
amount |
timestamp_sub(timestamp, unit, amount) |
|---|---|---|---|
| 2026-07-04 00:00:00 UTC | "minute" | 40L | 2026-07-03 23:20:00 UTC |
| 2026-07-04 00:00:00 UTC | "hour" | -24L | 2026-07-05 00:00:00 UTC |
| 2026-07-04 00:00:00 UTC | "day" | 3L | 2026-07-01 00:00:00 UTC |
Node.js
const result = await db.pipeline() .collection("documents") .select( field("expiresAt").timestampSubtract("day", 14).as("sendWarningTimestamp") ) .execute();
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
Sintaxis:
timestamp_to_unix_micros(input: TIMESTAMP) -> INT64
Descripción:
Convierte el objeto input en la cantidad de microsegundos desde 1970-01-01 00:00:00 UTC. Trunca los niveles más altos de precisión mediante el redondeo por defecto al principio del microsegundo.
Ejemplos:
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
Sintaxis:
timestamp_to_unix_millis(input: TIMESTAMP) -> INT64
Descripción:
Convierte el objeto input en la cantidad de milisegundos desde 1970-01-01 00:00:00 UTC. Trunca los niveles más altos de precisión mediante el redondeo por defecto al principio del milisegundo.
Ejemplos:
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
Sintaxis:
timestamp_to_unix_seconds(input: TIMESTAMP) -> INT64
Descripción:
Convierte el objeto input en la cantidad de segundos desde 1970-01-01 00:00:00 UTC. Trunca los niveles más altos de precisión mediante el redondeo por defecto al principio del segundo.
Ejemplos:
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();
TIMESTAMP_DIFF
Sintaxis:
timestamp_diff(end: TIMESTAMP, start: TIMESTAMP, unit: STRING) -> INT64
Descripción:
Devuelve el número entero de intervalos unit especificados entre dos TIMESTAMP.
- Devuelve un valor negativo si
endes anterior astart. - Trunca cualquier unidad fraccionaria. Por ejemplo,
timestamp_diff("2021-01-01 00:00:01", "2021-01-01 00:00:00", "minute")devuelve0.
El argumento unit debe ser una cadena y uno de los siguientes:
microsecondmillisecondsecondminutehourday
Ejemplos:
end |
start |
unit |
timestamp_diff(end, start, unit) |
|---|---|---|---|
| 2026-07-04 00:01:00 UTC | 2026-07-04 00:00:00 UTC | "second" | 60L |
| 2026-07-04 00:00:00 UTC | 2026-07-05 00:00:00 UTC | "day" | -1L |
| 2026-07-04 00:00:59 UTC | 2026-07-04 00:00:00 UTC | "minute" | 0L |
TIMESTAMP_EXTRACT
Sintaxis:
timestamp_extract(timestamp: TIMESTAMP, part: STRING[, timezone: STRING]) -> INT64
Descripción:
Extrae un part específico (p. ej., año, mes, día) de timestamp.
El argumento part debe ser una cadena y uno de los siguientes:
microsecondmillisecondsecondminutehourdaydayofweek: Muestra un valor entre 1 (domingo) y 7 (sábado).dayofyearweek: Devuelve el número de semana del año, comenzando en 1 para el primer domingo del año.week([weekday]): Muestra el número de la semana del año, a partir delweekdayespecificado.monthquarteryearisoweek: Muestra el número de semana según ISO 8601.isoyear: Muestra el año de numeración de semana según ISO 8601.
Si se proporciona el argumento timezone, la extracción se basará en el calendario de la zona horaria proporcionada. La extracción respetará el horario de verano.
Si no se proporciona timezone, la extracción se basará en UTC.
El argumento timezone debe ser una representación de cadena de una zona horaria de la base de datos de zona horaria, por ejemplo, America/New_York. También se puede usar una compensación de tiempo personalizada especificando una compensación desde GMT.
Ejemplos:
timestamp |
part |
timezone |
timestamp_extract(timestamp, part, timezone) |
|---|---|---|---|
| 2025-02-20 10:20:30 UTC | "year" | No proporcionado | 2025 |
| 2025-02-20 10:20:30 UTC | "day" | No proporcionado | 20 |
| 2025-12-31 23:59:59 UTC | "year" | "Asia/Tokio" | 2026 |
Funciones de tipo
| Nombre | Descripción |
TYPE
|
Devuelve el tipo del valor como una STRING.
|
IS_TYPE
|
Devuelve true si el valor coincide con el tipo especificado.
|
TYPE
Sintaxis:
type(input: ANY) -> STRING
Descripción:
Devuelve una representación de cadena del tipo input.
Si se proporciona un valor ausente, se devuelve NULL.
Ejemplos:
input |
type(input) |
|---|---|
| NULL | "null" |
| verdadero | "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 |
Ejemplos de clientes
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();
IS_TYPE
Sintaxis:
is_type(input: ANY, type: STRING) -> BOOLEAN
Descripción:
Devuelve true si input coincide con el type especificado; de lo contrario, devuelve false.
Si se proporciona un valor ausente para input, se devuelve NULL.
Las cadenas de type admitidas son las siguientes:
"null""boolean""int32""int64""float64""decimal128""number""timestamp""string""bytes""array""map""reference""vector""geo_point""max_key""min_key""object_id""regex""bson_timestamp"
Ejemplos:
input |
type |
is_type(input, type) |
|---|---|---|
| NULL | "null" | verdadero |
| verdadero | "boolean" | verdadero |
| 3.14 | "float64" | verdadero |
| "foo" | "string" | verdadero |
| b"foo" | "string" | falso |
| [1, 2] | "array" | verdadero |
| {"a": 1} | "map" | verdadero |
vector([1.0, 2.0]) |
"vector" | verdadero |
| ABSENT | "string" | NULL |
| "bar" | "other" | ERROR |
Funciones vectoriales
| Nombre | Descripción |
COSINE_DISTANCE
|
Devuelve la distancia de coseno entre dos vectores. |
DOT_PRODUCT
|
Devuelve el producto escalar entre dos vectores. |
EUCLIDEAN_DISTANCE
|
Devuelve la distancia euclidiana entre dos vectores. |
MANHATTAN_DISTANCE
|
Devuelve la distancia euclidiana entre dos vectores |
VECTOR_LENGTH
|
Devuelve la cantidad de elementos en un vector. |
COSINE_DISTANCE
Sintaxis:
cosine_distance(x: VECTOR, y: VECTOR) -> FLOAT64
Descripción:
Devuelve la distancia de coseno entre x y 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
Sintaxis:
dot_product(x: VECTOR, y: VECTOR) -> FLOAT64
Descripción:
Devuelve el producto escalar de x y 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
Sintaxis:
euclidean_distance(x: VECTOR, y: VECTOR) -> FLOAT64
Descripción:
Calcula la distancia euclidiana entre x y 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
Sintaxis:
manhattan_distance(x: VECTOR, y: VECTOR) -> FLOAT64
Descripción:
Calcula la distancia Manhattan entre x y y.
VECTOR_LENGTH
Sintaxis:
vector_length(vector: VECTOR) -> INT64
Descripción:
Devuelve la cantidad de elementos en 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();
¿Qué sigue?
- Consulta la descripción general de las consultas de canalización.