Строковые функции

Строковые функции

Имя Описание
BYTE_LENGTH Возвращает количество BYTES в STRING или в BYTES значении.
CHAR_LENGTH Возвращает количество символов Юникода в STRING значении.
STARTS_WITH Возвращает TRUE если STRING начинается с заданного префикса.
ENDS_WITH Возвращает TRUE если STRING заканчивается заданным постфиксом.
LIKE Возвращает TRUE если STRING соответствует шаблону.
REGEX_CONTAINS Возвращает TRUE если значение частично или полностью соответствует регулярному выражению.
REGEX_MATCH Возвращает TRUE если хотя бы одна часть значения соответствует регулярному выражению.
STRING_CONCAT Объединяет несколько STRING в одну STRING
STRING_CONTAINS Возвращает TRUE если значение содержит STRING
STRING_INDEX_OF Возвращает индекс первого вхождения STRING или BYTES значения (начиная с 0).
TO_UPPER Преобразует значение STRING или BYTES в верхний регистр.
TO_LOWER Преобразует значение STRING или BYTES в нижний регистр.
SUBSTRING Получает подстроку из значения типа STRING или BYTES .
STRING_REVERSE Переворачивает значение STRING или BYTES .
STRING_REPEAT Повторяет значение STRING или BYTES указанное количество раз.
STRING_REPLACE_ALL Заменяет все вхождения STRING или BYTES значения.
STRING_REPLACE_ONE Заменяет первое вхождение STRING или BYTES значения.
TRIM Удаляет начальные и конечные символы из STRING или BYTES значения.
LTRIM Удаляет начальные символы из STRING или BYTES значения.
RTRIM Удаляет лишние символы из STRING или BYTES значения.
SPLIT Разделяет STRING или BYTES значение на массив.

ДЛИНА_БАЙТА

Синтаксис:

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

Описание:

Возвращает количество BYTES в STRING или в BYTES .

Примеры:

ценить byte_length(value)
"abc" 3
"xyzabc" 6
б"абк" 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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").byteLength().as("titleByteLength")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("title").byte_length().as_("titleByteLength"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(byteLength(field("title")).as("titleByteLength"))
        .execute()
        .get();

ДЛИНА_СИМВОЛА

Синтаксис:

char_length(value: STRING) -> INT64

Описание:

Возвращает количество кодовых точек Юникода в STRING значении.

Примеры:

ценить char_length(value)
"abc" 3
"привет" 5
"мир" 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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").charLength().as("titleCharLength")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("title").char_length().as_("titleCharLength"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(charLength(field("title")).as("titleCharLength"))
        .execute()
        .get();

STARTS_WITH

Синтаксис:

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

Описание:

Возвращает TRUE если value начинается с prefix .

Примеры:

ценить префикс starts_with(value, prefix)
"abc" "а" истинный
"abc" "б" ЛОЖЬ
"abc" "" истинный
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(
        Field.of("title").starts_with("The").as_("needsSpecialAlphabeticalSort")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(startsWith(field("title"), "The").as("needsSpecialAlphabeticalSort"))
        .execute()
        .get();

ЗАВЕРШАЕТСЯ

Синтаксис:

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

Описание:

Возвращает TRUE если value заканчивается postfix .

Примеры:

ценить постфикс ends_with(value, postfix)
"abc" "с" истинный
"abc" "б" ЛОЖЬ
"abc" "" истинный
Node.js
const result = await db.pipeline()
  .collection("inventory/devices/laptops")
  .select(
    field("name").endsWith("16 inch")
      .as("16InLaptops")
  )
  .execute();
Быстрый
let result = try await db.pipeline()
  .collection("inventory/devices/laptops")
  .select([
    Field("name").endsWith("16 inch")
      .as("16InLaptops")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("inventory/devices/laptops")
    .select(Field.of("name").ends_with("16 inch").as_("16InLaptops"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("inventory/devices/laptops")
        .select(endsWith(field("name"), "16 inch").as("16InLaptops"))
        .execute()
        .get();

НРАВИТЬСЯ

Синтаксис:

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

Описание:

Возвращает TRUE если value соответствует pattern .

Примеры:

ценить шаблон like(value, pattern)
"Магазин пожарных" "Огонь%" истинный
"Магазин пожарных" "%магазин" истинный
"Хранилище данных" "Data_store" истинный
«100%» "100%" истинный
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("genre").like("%Fiction")
      .as("anyFiction")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("genre").like("%Fiction").as_("anyFiction"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(like(field("genre"), "%Fiction").as("anyFiction"))
        .execute()
        .get();

REGEX_CONTAINS

Синтаксис:

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

Описание:

Возвращает TRUE если какая-либо часть value соответствует pattern . Если pattern не является допустимым регулярным выражением, функция возвращает error .

Регулярные выражения следуют синтаксису библиотеки re2 .

Примеры:

ценить шаблон regex_contains(value, pattern)
"Магазин пожарных" "Огонь" истинный
"Магазин пожарных" "магазин$" истинный
"Магазин пожарных" "данные" ЛОЖЬ
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("title").regexContains("Firestore (Enterprise|Standard)")
      .as("isFirestoreRelated")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("title")
        .regex_contains("Firestore (Enterprise|Standard)")
        .as_("isFirestoreRelated")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(
            regexContains(field("title"), "Firestore (Enterprise|Standard)")
                .as("isFirestoreRelated"))
        .execute()
        .get();

REGEX_MATCH

Синтаксис:

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

Описание:

Возвращает TRUE если value полностью соответствует pattern . Если pattern не является допустимым регулярным выражением, функция возвращает error .

Регулярные выражения следуют синтаксису библиотеки re2 .

Примеры:

ценить шаблон regex_match(value, pattern)
"Магазин пожарных" "F.*store" истинный
"Магазин пожарных" "Огонь" ЛОЖЬ
"Магазин пожарных" "^F.*e$" истинный
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("documents")
  .select([
    Field("title").regexMatch("Firestore (Enterprise|Standard)")
      .as("isFirestoreExactly")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("documents")
    .select(
        Field.of("title")
        .regex_match("Firestore (Enterprise|Standard)")
        .as_("isFirestoreExactly")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("documents")
        .select(
            regexMatch(field("title"), "Firestore (Enterprise|Standard)")
                .as("isFirestoreExactly"))
        .execute()
        .get();

STRING_CONCAT

Синтаксис:

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

Описание:

Объединяет два или более STRING значения в один результат.

Примеры:

аргументы string_concat(values...)
() ошибка
("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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("title").concat([" by ", Field("author")])
      .as("fullyQualifiedTitle")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(
        Field.of("title")
        .concat(" by ", Field.of("author"))
        .as_("fullyQualifiedTitle")
    )
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(stringConcat(field("title"), " by ", field("author")).as("fullyQualifiedTitle"))
        .execute()
        .get();

STRING_CONTAINS

Синтаксис:

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

Описание:

Проверяет, содержит ли value строковый литерал substring String.

Примеры:

ценить подстрока string_contains(value, substring)
"abc" "б" истинный
"abc" "д" ЛОЖЬ
"abc" "" истинный
"ac" "." истинный
"☃☃☃" "☃" истинный
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("articles")
  .select([
    Field("body").stringContains("Firestore")
      .as("isFirestoreRelated")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("articles")
    .select(Field.of("body").string_contains("Firestore").as_("isFirestoreRelated"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("articles")
        .select(stringContains(field("body"), "Firestore").as("isFirestoreRelated"))
        .execute()
        .get();

STRING_INDEX_OF

Синтаксис:

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

Описание:

Возвращает индекс первого вхождения search value , начинающийся с 0.

  • Возвращает -1 если search не найден.
  • Если value является STRING , результат измеряется в кодовых точках Юникода. Если это значение BYTES , результат измеряется в байтах.
  • Если search значение представляет собой пустую STRING или BYTES , результат равен 0 .

Примеры:

ценить поиск string_index_of(value, search)
"Привет, мир" "о" 4
"Привет, мир" "л" 2
"Привет, мир" "з" -1
"банан" "на" 2
"abc" "" 0
б"абк" б"б" 1
"é" "é" 0
быть" быть" 0

TO_UPPER

Синтаксис:

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

Описание:

Преобразует значение STRING или BYTES в верхний регистр.

Если байт или символ не соответствует строчному буквенному символу UTF-8, он передается без изменений.

Примеры:

ценить to_upper(value)
"abc" "ABC"
"АбС" "ABC"
б"абк" б"ABC"
б"а1с" б"А1С"
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("authors")
  .select([
    Field("name").toUpper()
      .as("uppercaseName")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("authors")
    .select(Field.of("name").to_upper().as_("uppercaseName"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("authors")
        .select(toUpper(field("name")).as("uppercaseName"))
        .execute()
        .get();

TO_LOWER

Синтаксис:

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

Описание:

Преобразует значение STRING или BYTES в нижний регистр.

Если байт или символ не соответствует заглавной букве алфавита UTF-8, он передается без изменений.

Примеры:

ценить to_lower(value)
"ABC" "abc"
"АбС" "abc"
"A1C" "a1c"
б"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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("authors")
  .select([
    Field("genre").toLower().equal("fantasy")
      .as("isFantasy")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("authors")
    .select(Field.of("genre").to_lower().equal("fantasy").as_("isFantasy"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("authors")
        .select(equal(toLower(field("genre")), "fantasy").as("isFantasy"))
        .execute()
        .get();

ПОДСТРОКА

Синтаксис:

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

Описание:

Возвращает подстроку из input , начиная с position (индекс от нуля) и включая до length . Если length не указана, возвращает подстроку от position до конца input .

  • Если input представляют собой STRING , position и length измеряются в кодовых точках Юникода. Если это значение BYTES , они измеряются в байтах.

  • Если position превышает длину input , возвращается пустая подстрока. Если сумма position и length превышает длину input , подстрока обрезается до конца input .

  • Если position отрицательное, позиция берется с конца входного потока. Если отрицательное значение position превышает размер входного потока, position устанавливается равным нулю. length должно быть неотрицательным.

Примеры:

Если length не указана:

вход позиция substring(input, position)
"abc" 0 "abc"
"abc" 1 "до н.э."
"abc" 3 ""
"abc" -1 "с"
б"абк" 1 б"бк"

Если указана length :

вход позиция длина substring(input, position, length)
"abc" 0 1 "а"
"abc" 1 2 "до н.э."
"abc" -1 1 "с"
б"абк" 0 1 б"а"
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .where(Field("title").startsWith("The "))
  .select([
    Field("title").substring(position: 4)
      .as("titleWithoutLeadingThe")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .where(Field.of("title").starts_with("The "))
    .select(Field.of("title").substring(4).as_("titleWithoutLeadingThe"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .where(startsWith(field("title"), "The "))
        .select(
            substring(field("title"), constant(4), field("title").charLength())
                .as("titleWithoutLeadingThe"))
        .execute()
        .get();

STRING_REVERSE

Синтаксис:

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

Описание:

Возвращает введенные данные в обратном порядке.

Символы разграничиваются кодовыми точками Unicode, когда входные данные представляют собой STRING , и байтами, когда входные данные представляют собой значение BYTES .

Примеры:

вход string_reverse(input)
"abc" "cba"
"a🌹b" "б🌹а"
"привет" "оллех"
б"абк" б"кба"
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")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("name").reverse().as("reversedName")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("name").string_reverse().as_("reversedName"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(reverse(field("name")).as("reversedName"))
        .execute()
        .get();

STRING_REPEAT

Синтаксис:

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

Описание:

Возвращает input , repetitions раз.

  • repetitions должно быть неотрицательным целым числом.
  • Если repetitions равно 0 , возвращает пустое значение того же типа, что и input .
  • Если размер полученного результата превышает максимально допустимый (1 МБ), возвращается ошибка.

Примеры:

вход повторения string_repeat(input, repetitions)
"фу" 3 "фуфуфу"
"фу" 0 ""
"а " 3 "ааа"
б"аб" 2 б"абаб"
"é🦆" 2 "é🦆é🦆"

STRING_REPLACE_ALL

Синтаксис:

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

Описание:

Заменяет все непересекающиеся вхождения find во input на replacement .

  • В результатах поиска регистр имеет значение.
  • Если find пустое, замены не производятся.

Примеры:

вход находить замена string_replace_all(input, find, replacement)
"фубарфу" "фу" "баз" "базбарбаз"
"абабаб" "аба" "с" "cbab"
"фубар" "о" "" "fbar"
"é🦆🌎🦆" "🦆" "а" "éa🌎a"
б"абк" б"б" б"д" б"адк"

STRING_REPLACE_ONE

Синтаксис:

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

Описание:

Заменяет первое вхождение слова find во input на replacement .

  • В результатах поиска регистр имеет значение.
  • Если find пустое, замены не производятся.

Примеры:

вход находить замена string_replace_one(input, find, replacement)
"фубарфу" "фу" "баз" "базбарфу"
"é" "é" "а" "а"
b"фубар" б"о" б"з" b"fzoobar"

ПОДРЕЗАТЬ

Синтаксис:

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

Описание:

Удаляет указанный набор BYTES или CHARS из начала и конца предоставленного input .

  • Если values_to_trim не указано, удаляются пробелы.

Примеры:

Если values_to_trim не указан:

вход trim(input)
"фу" "фу"
б" фу " б"фу"
"фу" "фу"
"" ""
" " ""
"\t foo \n" "фу"
б"\t фу \n" б"фу"
"\r\f\v foo \r\f\v" "фу"
b"\r\f\v foo \r\f\v" б"фу"

Если указан values_to_trim :

вход values_to_trim trim(input, values_to_trim)
"abcbfooaacb" "abc" "фу"
"abcdaabadbac" "abc" "даабад"
б"C1C2C3" б"С1" б"C2C3"
б"C1C2" "фу" ошибка
"фу" б"С1" ошибка

Web

const result = await execute(db.pipeline()
  .collection("books")
  .select(
    field("name").trim().as("whitespaceTrimmedName")
  )
);
Быстрый
let result = try await db.pipeline()
  .collection("books")
  .select([
    Field("name").trim(" \n\t").as("whitespaceTrimmedName")
  ])
  .execute()

Kotlin

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

Java

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

result = (
    client.pipeline()
    .collection("books")
    .select(Field.of("name").trim().as_("whitespaceTrimmedName"))
    .execute()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(trim(field("name")).as("whitespaceTrimmedName"))
        .execute()
        .get();

ЛТРИМ

Синтаксис:

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

Описание:

Удаляет указанный набор BYTES или CHARS из начала заданного value .

  • Если to_trim не указан, удаляются начальные пробельные символы.

Примеры:

Если to_trim не указан:

ценить ltrim(value)
"фу" "фу"
"фу" "фу"

Если указан to_trim :

ценить to_trim ltrim(value, to_trim)
"aaabc" "а" "до н.э."
"абакаба" "ба" "каба"
"é" "é" ""

RTRIM

Синтаксис:

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

Описание:

Удаляет указанный набор BYTES или CHARS с конца заданного value .

  • Если to_trim не указан, удаляются пробелы в конце символа.

Примеры:

Если to_trim не указан:

ценить rtrim(value)
"фу" "фу"
"фу" "фу"

Если указан to_trim :

ценить to_trim rtrim(value, to_trim)
"abccc" "с" "аб"
"абакаба" "ба" "абак"
"é" "é" ""

РАСКОЛОТЬ

Синтаксис:

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

Описание:

Разделяет STRING или BYTES значение с помощью разделителя.

  • Для STRING разделителем по умолчанию является запятая , . Разделитель рассматривается как единая строка.

  • Для BYTES необходимо указать разделитель.

  • Разделение по пустому разделителю приводит к созданию массива кодовых точек Unicode для STRING значений и массива BYTES для BYTES значений.

  • Разделение пустой STRING возвращает ARRAY , содержащий одну пустую STRING .

Примеры:

Если delimiter не указан:

вход split(input)
"фу,бар,фу" ["foo", "bar", "foo"]
"фу" ["фу"]
",фу," ["", "фу", ""]
"" [""]
б"C120C2C4" ошибка

Если указан delimiter :

вход разделитель split(input, delimiter)
"фу бар фу" " " ["foo", "bar", "foo"]
"фу бар фу" "з" ["фу бар фу"]
"abc" "" ["a", "b", "c"]
б"C1,C2,C4" б"," [b"C1", b"C2", b"C4"]
б"ABC" б"" [б"А", б"Б", б"С"]
"фу" б"С1" ошибка