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

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

Имя Описание
BYTE_LENGTH Возвращает количество BYTES в значении STRING или BYTES.
CHAR_LENGTH Возвращает количество символов Юникода в значении STRING.
STARTS_WITH Возвращает TRUE, если STRING начинается с заданного префикса.
ENDS_WITH Возвращает TRUE, если STRING заканчивается заданным постфиксом.
LIKE Возвращает TRUE, если STRING соответствует шаблону.
REGEX_CONTAINS Возвращает TRUE, если значение частично или полностью соответствует регулярному выражению.
REGEX_FIND Возвращает первую подстроку, которая соответствует регулярному выражению, или NULL, если совпадений нет.
REGEX_FIND_ALL Возвращает массив всех подстрок, соответствующих регулярному выражению, или пустой массив, если совпадений нет.
REGEX_MATCH Возвращает TRUE, если какая-либо часть значения соответствует регулярному выражению.
STRING_CONCAT Объединяет несколько значений STRING в одно значение STRING.
STRING_CONTAINS Возвращает TRUE, если значение содержит STRING.
STRING_INDEX_OF Возвращает индекс первого вхождения значения STRING или BYTES (с точкой отсчета в нуле).
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

Синтаксис:

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

Описание.

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

Примеры

value 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

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.ByteLength(firestore.FieldOf("title")).As("titleByteLength"),
	)).
	Execute(ctx)

CHAR_LENGTH

Синтаксис:

char_length(value: STRING) -> INT64

Описание.

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

Примеры

value 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")
  )
);
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()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(charLength(field("title")).as("titleCharLength"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.CharLength(firestore.FieldOf("title")).As("titleCharLength"),
	)).
	Execute(ctx)

STARTS_WITH

Синтаксис:

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

Описание.

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

Примеры

value префикс starts_with(value, prefix)
"abc" "a" true
"abc" "b" false
"abc" "" true
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").startsWith("The")
      .as("needsSpecialAlphabeticalSort")
  )
  .execute();

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()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(startsWith(field("title"), "The").as("needsSpecialAlphabeticalSort"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.StartsWith(firestore.FieldOf("title"), "The").As("needsSpecialAlphabeticalSort"),
	)).
	Execute(ctx)

ENDS_WITH

Синтаксис:

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

Описание.

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

Примеры

value постфикс ends_with(value, postfix)
"abc" "c" true
"abc" "b" false
"abc" "" true
Node.js
const result = await db.pipeline()
  .collection("inventory/devices/laptops")
  .select(
    field("name").endsWith("16 inch")
      .as("16InLaptops")
  )
  .execute();
Swift
let result = try await db.pipeline()
  .collection("inventory/devices/laptops")
  .select([
    Field("name").endsWith("16 inch")
      .as("16InLaptops")
  ])
  .execute()

Kotlin

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("inventory/devices/laptops").
	Select(firestore.Fields(
		firestore.EndsWith(firestore.FieldOf("name"), "16 inch").As("`Laptops16in`"),
	)).
	Execute(ctx)

НРАВИТСЯ

Синтаксис:

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

Описание.

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

Примеры

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

Web

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

Kotlin

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Like(firestore.FieldOf("genre"), "%Fiction").As("anyFiction"),
	)).
	Execute(ctx)

REGEX_CONTAINS

Синтаксис:

regex_contains(value: STRING, regexp: STRING | REGEX) -> BOOLEAN

Описание.

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

Аргумент regexp также может быть значением REGEX, созданным с помощью regex("pattern", "options"). Этот формат позволяет задавать параметры регулярного выражения вместе с шаблоном. Поддерживаются следующие варианты:

  • i – сопоставление без учета регистра.
  • m – многострочный режим (^ и $ соответствуют началу или концу строк).
  • s – режим Dotall (. соответствует символам новой строки).

Если regexp – это STRING, то применяются только те параметры, которые встроены в сам шаблон (например, (?i)).

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

Примеры

value регулярное выражение regex_contains(value, regexp)
"Firestore" "Огонь" true
"Firestore" "store$" true
"Firestore" "data" false
"Firestore" regex("fire", "i") true
"Firestore" regex("FIRE", "") false
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

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.RegexContains(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreRelated"),
	)).
	Execute(ctx)

REGEX_FIND

Синтаксис:

regex_find(value: STRING, regexp: STRING | REGEX) -> STRING

Описание.

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

Аргумент regexp также может быть значением REGEX, созданным с помощью regex("pattern", "options"). Этот формат позволяет задавать параметры регулярного выражения вместе с шаблоном. Поддерживаются следующие варианты:

  • i – сопоставление без учета регистра.
  • m – многострочный режим (^ и $ соответствуют началу или концу строк).
  • s – режим Dotall (. соответствует символам новой строки).

Если regexp – это STRING, то применяются только те параметры, которые встроены в сам шаблон (например, (?i)).

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

Примеры

value регулярное выражение regex_find(value, regexp)
"Sometext MATCH" "SomeText" "Sometext"
"Sometext MATCH" regex("match", "i") "MATCH"
"Sometext MATCH" regex("(match)", "i") "MATCH"
"Sometext match" regex("MATCH", "") null

REGEX_FIND_ALL

Синтаксис:

regex_find_all(value: STRING, regexp: STRING | REGEX) -> ARRAY<STRING>

Описание.

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

Аргумент regexp также может быть значением REGEX, созданным с помощью regex("pattern", "options"). Этот формат позволяет задавать параметры регулярного выражения вместе с шаблоном. Поддерживаются следующие варианты:

  • i – сопоставление без учета регистра.
  • m – многострочный режим (^ и $ соответствуют началу или концу строк).
  • s – режим Dotall (. соответствует символам новой строки).

Если regexp – это STRING, то применяются только те параметры, которые встроены в сам шаблон (например, (?i)).

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

Примеры

value регулярное выражение regex_find_all(value, regexp)
"один два три два" "one" ["one"]
"один ДВА три Два" regex("two", "i") ["TWO", "Two"]
"один два три два" regex("TWO", "") []

REGEX_MATCH

Синтаксис:

regex_match(value: STRING, regexp: STRING | REGEX) -> BOOLEAN

Описание.

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

Аргумент regexp также может быть значением REGEX, созданным с помощью regex("pattern", "options"). Этот формат позволяет задавать параметры регулярного выражения вместе с шаблоном. Поддерживаются следующие варианты:

  • i – сопоставление без учета регистра.
  • m – многострочный режим (^ и $ соответствуют началу или концу строк).
  • s – режим Dotall (. соответствует символам новой строки).

Если regexp – это STRING, то применяются только те параметры, которые встроены в сам шаблон (например, (?i)).

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

Примеры

value регулярное выражение regex_match(value, regexp)
"Firestore" "F.*store" true
"Firestore" "Огонь" false
"Firestore" "^F.*e$" true
"FiReStOrE" regex("firestore", "i") true
"Firestore" regex("firestore", "") false
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

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("documents").
	Select(firestore.Fields(
		firestore.RegexMatch(firestore.FieldOf("title"), "Firestore (Enterprise|Standard)").As("isFirestoreExactly"),
	)).
	Execute(ctx)

STRING_CONCAT

Синтаксис:

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

Описание.

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

Примеры

аргументы string_concat(values...)
() ошибка
("a") "a"
("abc", "def") "abcdef"
("a", "", "c") "ac"
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("title").stringConcat(" by ", field("author"))
      .as("fullyQualifiedTitle")
  )
  .execute();

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()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(stringConcat(field("title"), " by ", field("author")).as("fullyQualifiedTitle"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.StringConcat(firestore.FieldOf("title"), " by ", firestore.FieldOf("author")).As("fullyQualifiedTitle"),
	)).
	Execute(ctx)

STRING_CONTAINS

Синтаксис:

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

Описание.

Проверяет, содержит ли value строку substring.

Примеры

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

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()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("articles")
        .select(stringContains(field("body"), "Firestore").as("isFirestoreRelated"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("articles").
	Select(firestore.Fields(
		firestore.StringContains(firestore.FieldOf("body"), "Firestore").As("isFirestoreRelated"),
	)).
	Execute(ctx)

STRING_INDEX_OF

Синтаксис:

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

Описание.

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

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

Примеры

value search string_index_of(value, search)
"hello world" "o" 4
"hello world" "l" 2
"hello world" "z" -1
"банан" "ana" 1
"abc" "" 0
b"abc" b"b" 1
"é" "é" 0
b"é" b"é" 0

TO_UPPER

Синтаксис:

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

Описание.

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

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

Примеры

value 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

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("authors").
	Select(firestore.Fields(
		firestore.ToUpper(firestore.FieldOf("name")).As("uppercaseName"),
	)).
	Execute(ctx)

TO_LOWER

Синтаксис:

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

Описание.

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

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

Примеры

value 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

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("authors").
	Select(firestore.Fields(
		firestore.Equal(firestore.ToLower(firestore.FieldOf("genre")), "fantasy").As("isFantasy"),
	)).
	Execute(ctx)

SUBSTRING

Синтаксис:

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

Описание.

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

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

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

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

Примеры

Если параметр length не указан:

ввод position substring(input, position)
"abc" 0 "abc"
"abc" 1 "bc"
"abc" 3 ""
"abc" -1 "c"
b"abc" 1 b"bc"

Если указан параметр length:

ввод position длина 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

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();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Where(firestore.StartsWith(firestore.FieldOf("title"), "The ")).
	Select(firestore.Fields(
		firestore.Substring(firestore.FieldOf("title"), firestore.ConstantOf(4), firestore.FieldOf("title").CharLength()).As("titleWithoutLeadingThe"),
	)).
	Execute(ctx)

STRING_REVERSE

Синтаксис:

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

Описание.

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

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

Примеры

ввод string_reverse(input)
"abc" "cba"
"a🌹b" "b🌹a"
"Привет" "olleh"
b"abc" b"cba"
Node.js
const result = await db.pipeline()
  .collection("books")
  .select(
    field("name").reverse().as("reversedName")
  )
  .execute();

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()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(reverse(field("name")).as("reversedName"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Reverse(firestore.FieldOf("name")).As("reversedName"),
	)).
	Execute(ctx)

STRING_REPEAT

Синтаксис:

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

Описание.

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

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

Примеры

ввод повторения string_repeat(input, repetitions)
"foo" 3 "foofoofoo"
"foo" 0 ""
"a " 3 "a a a "
b"ab" 2 b"abab"
"é🦆" 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)
"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

Синтаксис:

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

Описание.

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

  • Регистр учитывается.
  • Если параметр find пустой, замены не выполняются.

Примеры

ввод найти замена string_replace_one(input, find, replacement)
"foobarfoo" "foo" "baz" "bazbarfoo"
"é" "é" "a" "a"
b"foobar" b"o" b"z" 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)
" foo " "foo"
b" foo " b"foo"
"foo" "foo"
"" ""
" " ""
"\t foo \n" "foo"
b"\t foo \n" b"foo"
"\r\f\v foo \r\f\v" "foo"
b"\r\f\v foo \r\f\v" b"foo"

Если указан параметр values_to_trim:

ввод values_to_trim trim(input, values_to_trim)
"abcbfooaacb" "abc" "foo"
"abcdaabadbac" "abc" "daabad"
b"C1C2C3" b"C1" b"C2C3"
b"C1C2" "foo" ошибка
"foo" b"C1" ошибка

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()
)
Java
Pipeline.Snapshot result =
    firestore
        .pipeline()
        .collection("books")
        .select(trim(field("name")).as("whitespaceTrimmedName"))
        .execute()
        .get();
Проложить маршрут
snapshot := client.Pipeline().
	Collection("books").
	Select(firestore.Fields(
		firestore.Trim(firestore.FieldOf("name")).As("whitespaceTrimmedName"),
	)).
	Execute(ctx)

LTRIM

Синтаксис:

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

Описание.

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

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

Примеры

Если параметр to_trim не указан:

value ltrim(value)
" foo " "foo "
"foo" "foo"

Если указан параметр to_trim:

value to_trim ltrim(value, to_trim)
"aaabc" "a" "bc"
"abacaba" "ba" "caba"
"é" "é" ""

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 не указан:

value rtrim(value)
" foo " " foo"
"foo" "foo"

Если указан параметр to_trim:

value to_trim rtrim(value, to_trim)
"abccc" "c" "ab"
"abacaba" "ba" "abac"
"é" "é" ""

SPLIT

Синтаксис:

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" ["foo", "bar", "foo"]
"foo" ["foo"]
",foo," ["", "foo", ""]
"" [""]
b"C120C2C4" ошибка

Если указан параметр delimiter:

ввод разделитель split(input, delimiter)
"foo bar foo" " " ["foo", "bar", "foo"]
"foo bar foo" "z" ["foo bar foo"]
"abc" "" ["a", "b", "c"]
b"C1,C2,C4" b"," [b"C1", b"C2", b"C4"]
b"ABC" b"" [b"A", b"B", b"C"]
"foo" b"C1" ошибка