Строковые функции
| Имя | Описание |
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 |
TO_UPPER | Преобразует значение STRING или BYTES в верхний регистр. |
TO_LOWER | Преобразует значение STRING или BYTES в нижний регистр. |
SUBSTRING | Получает подстроку из значения типа STRING или BYTES . |
STRING_REVERSE | Переворачивает значение STRING или BYTES . |
TRIM | Удаляет начальные и конечные символы из STRING или BYTES значения. |
SPLIT | Разделяет STRING или BYTES значение на массив. |
ДЛИНА_БАЙТА
Синтаксис:
byte_length[T <: STRING | BYTES](value: T) -> INT64
Описание:
Возвращает количество BYTES в STRING или в BYTES .
Примеры:
| ценить | byte_length(value) |
|---|---|
| "abc" | 3 |
| "xyzabc" | 6 |
| б"абк" | 3 |
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() )
ДЛИНА_СИМВОЛА
Синтаксис:
char_length(value: STRING) -> INT64
Описание:
Возвращает количество кодовых точек Юникода в STRING значении.
Примеры:
| ценить | char_length(value) |
|---|---|
| "abc" | 3 |
| "привет" | 5 |
| "мир" | 5 |
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() )
STARTS_WITH
Синтаксис:
starts_with(value: STRING, prefix: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value начинается с prefix .
Примеры:
| ценить | префикс | starts_with(value, prefix) |
|---|---|---|
| "abc" | "а" | истинный |
| "abc" | "б" | ЛОЖЬ |
| "abc" | "" | истинный |
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() )
ЗАВЕРШАЕТСЯ
Синтаксис:
ends_with(value: STRING, postfix: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value заканчивается postfix .
Примеры:
| ценить | постфикс | ends_with(value, postfix) |
|---|---|---|
| "abc" | "с" | истинный |
| "abc" | "б" | ЛОЖЬ |
| "abc" | "" | истинный |
Быстрый
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(value: STRING, pattern: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value соответствует pattern .
Примеры:
| ценить | шаблон | like(value, pattern) |
|---|---|---|
| "Магазин пожарных" | "Огонь%" | истинный |
| "Магазин пожарных" | "%магазин" | истинный |
| "Хранилище данных" | "Data_store" | истинный |
| «100%» | "100%" | истинный |
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() )
REGEX_CONTAINS
Синтаксис:
regex_contains(value: STRING, pattern: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если какая-либо часть value соответствует pattern . Если pattern не является допустимым регулярным выражением, функция возвращает error .
Регулярные выражения следуют синтаксису библиотеки re2 .
Примеры:
| ценить | шаблон | regex_contains(value, pattern) |
|---|---|---|
| "Магазин пожарных" | "Огонь" | истинный |
| "Магазин пожарных" | "магазин$" | истинный |
| "Магазин пожарных" | "данные" | ЛОЖЬ |
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() )
REGEX_MATCH
Синтаксис:
regex_match(value: STRING, pattern: STRING) -> BOOLEAN
Описание:
Возвращает TRUE если value полностью соответствует pattern . Если pattern не является допустимым регулярным выражением, функция возвращает error .
Регулярные выражения следуют синтаксису библиотеки re2 .
Примеры:
| ценить | шаблон | regex_match(value, pattern) |
|---|---|---|
| "Магазин пожарных" | "F.*store" | истинный |
| "Магазин пожарных" | "Огонь" | ЛОЖЬ |
| "Магазин пожарных" | "^F.*e$" | истинный |
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() )
STRING_CONCAT
Синтаксис:
string_concat(values: STRING...) -> STRING
Описание:
Объединяет два или более STRING значения в один результат.
Примеры:
| аргументы | string_concat(values...) |
|---|---|
() | ошибка |
("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") ) );
Быстрый
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
Синтаксис:
string_contains(value: STRING, substring: STRING) -> BOOLEAN
Описание:
Проверяет, содержит ли value строковый литерал substring String.
Примеры:
| ценить | подстрока | string_contains(value, substring) |
|---|---|---|
| "abc" | "б" | истинный |
| "abc" | "д" | ЛОЖЬ |
| "abc" | "" | истинный |
| "ac" | "." | истинный |
| "☃☃☃" | "☃" | истинный |
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() )
TO_UPPER
Синтаксис:
to_upper[T <: STRING | BYTES](value: T) -> T
Описание:
Преобразует значение STRING или BYTES в верхний регистр.
Если байт или символ не соответствует строчному буквенному символу UTF-8, он передается без изменений.
Примеры:
| ценить | to_upper(value) |
|---|---|
| "abc" | "ABC" |
| "АбС" | "ABC" |
| б"абк" | б"ABC" |
| б"а1с" | б"А1С" |
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() )
TO_LOWER
Синтаксис:
to_lower[T <: STRING | BYTES](value: T) -> T
Описание:
Преобразует значение STRING или BYTES в нижний регистр.
Если байт или символ не соответствует заглавной букве алфавита UTF-8, он передается без изменений.
Примеры:
| ценить | to_lower(value) |
|---|---|
| "ABC" | "abc" |
| "АбС" | "abc" |
| "A1C" | "a1c" |
| б"ABC" | б"абк" |
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() )
ПОДСТРОКА
Синтаксис:
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 | б"а" |
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() )
STRING_REVERSE
Синтаксис:
string_reverse[T <: STRING | BYTES](input: T) -> T
Описание:
Возвращает введенные данные в обратном порядке.
Символы разграничиваются кодовыми точками Unicode, когда входные данные представляют собой STRING , и байтами, когда входные данные представляют собой значение BYTES .
Примеры:
| вход | string_reverse(input) |
|---|---|
| "abc" | "cba" |
| "a🌹b" | "б🌹а" |
| "привет" | "оллех" |
| б"абк" | б"кба" |
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() )
ПОДРЕЗАТЬ
Синтаксис:
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() )
РАСКОЛОТЬ
Синтаксис:
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" | ошибка |