Funciones de string

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.
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.
TRIM Recorta los caracteres iniciales y 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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").byteLength().as("titleByteLength")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").byteLength().as("titleByteLength")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(
        field("title").byteLength().alias("titleByteLength")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("title").byteLength().alias("titleByteLength")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("title").byte_length().as_("titleByteLength"))
    .execute()
)

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").charLength().as("titleCharLength")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").charLength().as("titleCharLength")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(
        field("title").charLength().alias("titleCharLength")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("title").charLength().alias("titleCharLength")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("title").char_length().as_("titleCharLength"))
    .execute()
)

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(
        field("title").startsWith("The")
            .alias("needsSpecialAlphabeticalSort")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("title").startsWith("The")
            .alias("needsSpecialAlphabeticalSort")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(
        Field.of("title").starts_with("The").as_("needsSpecialAlphabeticalSort")
    )
    .execute()
)

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
Swift
let result = try await db.pipeline()
  .collection("inventory/devices/laptops")
  .select([
    Field("name").endsWith("16 inch")
      .as("16InLaptops")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("inventory/devices/laptops")
    .select(
        field("name").endsWith("16 inch")
            .alias("16InLaptops")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("inventory/devices/laptops")
    .select(
        field("name").endsWith("16 inch")
            .alias("16InLaptops")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("inventory/devices/laptops")
    .select(Field.of("name").ends_with("16 inch").as_("16InLaptops"))
    .execute()
)

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

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("genre").like("%Fiction")
      .as("anyFiction")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("genre").like("%Fiction")
      .as("anyFiction")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(
        field("genre").like("%Fiction")
            .alias("anyFiction")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("genre").like("%Fiction")
            .alias("anyFiction")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("genre").like("%Fiction").as_("anyFiction"))
    .execute()
)

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("title").regexContains("Firestore (Enterprise|Standard)")
            .alias("isFirestoreRelated")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("title").regexContains("Firestore (Enterprise|Standard)")
            .alias("isFirestoreRelated")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("title")
        .regex_contains("Firestore (Enterprise|Standard)")
        .as_("isFirestoreRelated")
    )
    .execute()
)

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

Web

const result = await execute(db.pipeline()
  .collection("documents")
  .select(
    field("title").regexMatch("Firestore (Enterprise|Standard)")
      .as("isFirestoreExactly")
  )
);
Swift
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("title").regexMatch("Firestore (Enterprise|Standard)")
      .as("isFirestoreExactly")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("documents")
    .select(
        field("title").regexMatch("Firestore (Enterprise|Standard)")
            .alias("isFirestoreExactly")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("documents")
    .select(
        field("title").regexMatch("Firestore (Enterprise|Standard)")
            .alias("isFirestoreExactly")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("title")
        .regex_match("Firestore (Enterprise|Standard)")
        .as_("isFirestoreExactly")
    )
    .execute()
)

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"

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("title").stringConcat(" by ", field("author"))
      .as("fullyQualifiedTitle")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").concat([" by ", Field("author")])
      .as("fullyQualifiedTitle")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(
        field("title").concat(" by ", field("author"))
            .alias("fullyQualifiedTitle")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("title").concat(" by ", field("author"))
            .alias("fullyQualifiedTitle")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(
        Field.of("title")
        .concat(" by ", Field.of("author"))
        .as_("fullyQualifiedTitle")
    )
    .execute()
)

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

Web

const result = await execute(db.pipeline()
  .collection("articles")
  .select(
    field("body").stringContains("Firestore")
      .as("isFirestoreRelated")
  )
);
Swift
let result = try await db.pipeline()
  .collection("articles")
  .select([
    Field("body").stringContains("Firestore")
      .as("isFirestoreRelated")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("articles")
    .select(
        field("body").stringContains("Firestore")
            .alias("isFirestoreRelated")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("articles")
    .select(
        field("body").stringContains("Firestore")
            .alias("isFirestoreRelated")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("articles")
    .select(Field.of("body").string_contains("Firestore").as_("isFirestoreRelated"))
    .execute()
)

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"

Web

const result = await execute(db.pipeline()
  .collection("authors")
  .select(
    field("name").toUpper()
      .as("uppercaseName")
  )
);
Swift
let result = try await db.pipeline()
  .collection("authors")
  .select([
    Field("name").toUpper()
      .as("uppercaseName")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("authors")
    .select(
        field("name").toUpper()
            .alias("uppercaseName")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("authors")
    .select(
        field("name").toUpper()
            .alias("uppercaseName")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("authors")
    .select(Field.of("name").to_upper().as_("uppercaseName"))
    .execute()
)

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"

Web

const result = await execute(db.pipeline()
  .collection("authors")
  .select(
    field("genre").toLower().equal("fantasy")
      .as("isFantasy")
  )
);
Swift
let result = try await db.pipeline()
  .collection("authors")
  .select([
    Field("genre").toLower().equal("fantasy")
      .as("isFantasy")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("authors")
    .select(
        field("genre").toLower().equal("fantasy")
            .alias("isFantasy")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("authors")
    .select(
        field("genre").toLower().equal("fantasy")
            .alias("isFantasy")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("authors")
    .select(Field.of("genre").to_lower().equal("fantasy").as_("isFantasy"))
    .execute()
)

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 input es un valor de STRING, position y length se miden en puntos de código Unicode. Si es un valor BYTES, se miden en bytes.

  • Si position es mayor que la longitud de input, se devuelve una subcadena vacía. Si position más length es mayor que la longitud de input, la subcadena se trunca hasta el final de input.

  • Si position es negativo, la posición se toma desde el final de la entrada. Si la position negativa es mayor que el tamaño de la entrada, la posición se establece en cero. length no 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"

Web

const result = await execute(db.pipeline()
  .collection("books")
  .where(field("title").startsWith("The "))
  .select(
    field("title").substring(4)
      .as("titleWithoutLeadingThe")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .where(Field("title").startsWith("The "))
  .select([
    Field("title").substring(position: 4)
      .as("titleWithoutLeadingThe")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .where(field("title").startsWith("The "))
    .select(
        field("title")
          .substring(constant(4),
            field("title").charLength().subtract(4))
            .alias("titleWithoutLeadingThe")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .where(field("title").startsWith("The "))
    .select(
        field("title").substring(
          constant(4),
            field("title").charLength().subtract(4))
            .alias("titleWithoutLeadingThe")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .where(Field.of("title").starts_with("The "))
    .select(Field.of("title").substring(4).as_("titleWithoutLeadingThe"))
    .execute()
)

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"

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("name").reverse().as("reversedName")
  )
);
Swift
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("name").reverse().as("reversedName")
  ])
  .execute()

Kotlin

val result = db.pipeline()
    .collection("books")
    .select(
        field("name").reverse().alias("reversedName")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("name").reverse().alias("reversedName")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("name").string_reverse().as_("reversedName"))
    .execute()
)

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

val result = db.pipeline()
    .collection("books")
    .select(
        field("name").trim().alias("whitespaceTrimmedName")
    )
    .execute()

Java

Task<Pipeline.Snapshot> result = db.pipeline()
    .collection("books")
    .select(
        field("name").trim().alias("whitespaceTrimmedName")
    )
    .execute();
Python
from google.cloud.firestore_v1.pipeline_expressions import Field

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("name").trim().as_("whitespaceTrimmedName"))
    .execute()
)

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 STRING y un array de BYTES para los valores de BYTES.

  • Dividir una STRING vacía devuelve un ARRAY con una única STRING vací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