提交 e3f8647a 编写于 作者: A Andrey Dudin 提交者: alexey-milovidov

Functions

上级 24ab9fcd
Арифметические функции
Arithmetic functions
======================
Для всех арифметических функций, тип результата вычисляется, как минимальный числовой тип, который может вместить результат, если такой тип есть. Минимум берётся одновременно по числу бит, знаковости и "плавучести". Если бит не хватает, то берётся тип максимальной битности.
For all arithmetic functions, the result type is calculated as the smallest number type that the result fits in, if there is such a type. The minimum is taken simultaneously based on the number of bits, whether it is signed, and whether it floats. If there are not enough bits, the highest bit type is taken.
Пример:
Example
.. code-block:: sql
......@@ -13,53 +13,52 @@
│ UInt8 │ UInt16 │ UInt32 │ UInt64 │
└───────────────┴────────────────────────┴─────────────────────────────────┴──────────────────────────────────────────┘
Арифметические функции работают для любой пары типов из UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64.
Arithmetic functions work for any pair of types from UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, or Float64.
Переполнение производится также, как в C++.
Overflow is produced the same way as in C++.
plus(a, b), оператор a + b
plus(a, b), a + b operator
--------------------------
Вычисляет сумму чисел.
Также можно складывать целые числа с датой и датой-с-временем. В случае даты, прибавление целого числа означает прибавление соответствующего количества дней. В случае даты-с-временем - прибавление соответствующего количества секунд.
Calculates the sum of the numbers.
You can also add whole numbers with a date or date and time. In the case of a date, adding a whole number means adding the corresponding number of days. For a date with time, it means adding the corresponding number of seconds.
minus(a, b), оператор a - b
minus(a, b), a - b operator
---------------------------
Вычисляет разность чисел. Результат всегда имеет знаковый тип.
Calculates the difference. The result is always signed.
Также можно вычитать целые числа из даты и даты-с-временем. Смысл аналогичен - смотрите выше для plus.
You can also calculate whole numbers from a date or date with time. The idea is the same - see above for 'plus'.
multiply(a, b), оператор a * b
multiply(a, b), a * b operator
------------------------------
Вычисляет произведение чисел.
Calculates the product of the numbers.
divide(a, b), оператор a / b
divide(a, b), a / b operator
-----------------------------
Вычисляет частное чисел. Тип результата всегда является типом с плавающей запятой.
То есть, деление не целочисленное. Для целочисленного деления, используйте функцию intDiv.
При делении на ноль получится inf, -inf или nan.
Calculates the quotient of the numbers. The result type is always a floating-point type.
It is not integer division. For integer division, use the 'intDiv' function.
When dividing by zero you get 'inf', '-inf', or 'nan'.
intDiv(a, b)
------------
Вычисляет частное чисел. Деление целочисленное, с округлением вниз (по абсолютному значению).
При делении на ноль или при делении минимального отрицательного числа на минус единицу, кидается исключение.
Calculates the quotient of the numbers. Divides into integers, rounding down (by the absolute value).
When dividing by zero or when dividing a minimal negative number by minus one, an exception is thrown.
intDivOrZero(a, b)
------------------
Отличается от intDiv тем, что при делении на ноль или при делении минимального отрицательного числа на минус единицу, возвращается ноль.
Differs from 'intDiv' in that it returns zero when dividing by zero or when dividing a minimal negative number by minus one.
modulo(a, b), оператор a % b
modulo(a, b), a % b operator
----------------------------
Вычисляет остаток от деления.
Если аргументы - числа с плавающей запятой, то они предварительно преобразуются в целые числа, путём отбрасывания дробной части.
Берётся остаток в том же смысле, как это делается в C++. По факту, для отрицательных чисел, используется truncated division.
При делении на ноль или при делении минимального отрицательного числа на минус единицу, кидается исключение.
Calculates the remainder after division.
If arguments are floating-point numbers, they are pre-converted to integers by dropping the decimal portion. The remainder is taken in the same sense as in C++. Truncated division is used for negative numbers.
An exception is thrown when dividing by zero or when dividing a minimal negative number by minus one.
negate(a), оператор -a
negate(a), -a operator
----------------------
Вычисляет число, обратное по знаку. Результат всегда имеет знаковый тип.
Calculates a number with the reverse sign. The result is always signed.
abs(a)
------
Вычисляет абсолютное значение для числа a. То есть, если a < 0, то возвращает -a.
Для беззнаковых типов ничего не делает. Для чисел типа целых со знаком, возвращает число беззнакового типа.
Calculates the absolute value of the number 'a'. That is, if a< 0, it returns -a.
For unsigned types, it doesn't do anything. For signed integer types, it returns an unsigned number.
Функции по работе с массивами
Functions for working with arrays
-----------------------------
empty
~~~~~
Возвращает 1 для пустого массива, и 0 для непустого массива.
Тип результата - UInt8.
Функция также работает для строк.
Returns 1 for an empty array, or 0 for a non-empty array.
The result type is UInt8.
The function also works for strings.
notEmpty
~~~~~~~~
Возвращает 0 для пустого массива, и 1 для непустого массива.
Тип результата - UInt8.
Функция также работает для строк.
Returns 0 for an empty array, or 1 for a non-empty array.
The result type is UInt8.
The function also works for strings.
length
~~~~~~
Возвращает количество элементов в массиве.
Тип результата - UInt64.
Функция также работает для строк.
Returns the number of items in the array.
The result type is UInt64.
The function also works for strings.
emptyArrayUInt8, emptyArrayUInt16, emptyArrayUInt32, emptyArrayUInt64
~~~~~~~~~~~~~~
......@@ -33,53 +33,53 @@ emptyArrayDate, emptyArrayDateTime
emptyArrayString
~~~~~~~~~~~~
Принимает ноль аргументов и возвращает пустой массив соответствующего типа.
Accepts zero arguments and returns an empty array of the appropriate type.
emptyArrayToSingle
~~~~~~~~~~~~~~
Принимает пустой массив и возвращает массив из одного элемента, равного значению по умолчанию.
Accepts an empty array as argument and returns an array of one element equal to the default value.
range(N)
~~~~~~~
Возвращает массив чисел от 0 до N-1.
На всякий случай, если на блок данных, создаются массивы суммарной длины больше 100 000 000 элементов, то кидается исключение.
Returns an array of numbers from 0 to N-1.
Just in case, an exception is thrown if arrays with a total length of more than 100,000,000 elements are created in a data block.
array(x1, ...), оператор [x1, ...]
~~~~~~~~~~~~
Создаёт массив из аргументов функции.
Аргументы должны быть константами и иметь типы, для которых есть наименьший общий тип. Должен быть передан хотя бы один аргумент, так как иначе непонятно, какого типа создавать массив. То есть, с помощью этой функции невозможно создать пустой массив (для этого используйте функции emptyArray*, описанные выше).
Возвращает результат типа Array(T), где T - наименьший общий тип от переданных аргументов.
Creates an array from the function arguments.
The arguments must be constants and have types that have the smallest common type. At least one argument must be passed, because otherwise it isn't clear which type of array to create. That is, you can't use this function to create an empty array (to do that, use the 'emptyArray*' function described above).
Returns an 'Array(T)' type result, where 'T' is the smallest common type out of the passed arguments.
arrayElement(arr, n), оператор arr[n]
~~~~~~~~~~~~
Достаёт элемент с индексом n из массива arr.
n должен быть любым целочисленным типом.
Индексы в массиве начинаются с единицы.
Поддерживаются отрицательные индексы - в этом случае, будет выбран соответствующий по номеру элемент с конца. Например, arr[-1] - последний элемент массива.
Get the element with the index 'n' from the array 'arr'.
'n' should be any integer type.
Indexes in an array begin from one.
Negative indexes are supported - in this case, it selects the corresponding element numbered from the end. For example, 'arr[-1]' is the last item in the array.
Если индекс выходит за границы массива, то
- если оба аргумента - константы, то кидается исключение;
- иначе, возвращается некоторое значение по умолчанию (0 для чисел, пустая строка для строк и т. п.).
If the index goes beyond the array bounds:
- if both arguments are constants, an exception is thrown.
- otherwise, a default value is returned (0 for numbers, an empty string for strings, etc.).
has(arr, elem)
~~~~~~~~~~~
Проверяет наличие элемента elem в массиве arr.
Возвращает 0, если элемента в массиве нет, или 1, если есть.
elem должен быть константой.
Checks whether the 'arr' array has the 'elem' element.
Returns 0 if the the element is not in the array, or 1 if it is.
'elem' must be a constant.
indexOf(arr, x)
~~~~~~~~~~
Возвращает индекс элемента x (начиная с 1), если он есть в массиве, или 0, если его нет.
Returns the index of the 'x' element (starting from 1) if it is in the array, or 0 if it is not.
countEqual(arr, x)
~~~~~~~~
Возвращает количество элементов массива, равных x. Эквивалентно arrayCount(elem -> elem = x, arr).
Returns the number of elements in the array equal to 'x'. Equivalent to ``arrayCount(elem -> elem = x, arr)``.
arrayEnumerate(arr)
~~~~~~~~~
Возвращает массив [1, 2, 3, ..., length(arr)]
Returns the array ``[1, 2, 3, ..., length(arr)]``
Эта функция обычно используется совместно с ARRAY JOIN. Она позволяет, после применения ARRAY JOIN, посчитать что-либо только один раз для каждого массива. Пример:
This function is normally used together with ARRAY JOIN. It allows counting something just once for each array after applying ARRAY JOIN. Example:
.. code-block:: sql
......@@ -97,7 +97,7 @@ arrayEnumerate(arr)
│ 95606 │ 31406 │
└─────────┴───────┘
В этом примере, Reaches - число достижений целей (строк, получившихся после применения ARRAY JOIN), а Hits - число хитов (строк, которые были до ARRAY JOIN). В данном случае, тот же результат можно получить проще:
In this example, Reaches is the number of conversions (the strings received after applying ARRAY JOIN), and Hits is the number of pageviews (strings before ARRAY JOIN). In this particular case, you can get the same result in an easier way:
.. code-block:: sql
......@@ -111,15 +111,14 @@ arrayEnumerate(arr)
│ 95606 │ 31406 │
└─────────┴───────┘
Также эта функция может быть использована в функциях высшего порядка. Например, с её помощью можно достать индексы массива для элементов, удовлетворяющих некоторому условию.
This function can also be used in higher-order functions. For example, you can use it to get array indexes for elements that match a condition.
arrayEnumerateUniq(arr, ...)
~~~~~~~~~~
Возвращает массив, такого же размера, как исходный, где для каждого элемента указано, какой он по счету среди элементов с таким же значением.
Например: arrayEnumerateUniq([10, 20, 10, 30]) = [1, 1, 2, 1].
Returns an array the same size as the source array, indicating for each element what its position is among elements with the same value.
For example: ``arrayEnumerateUniq([10, 20, 10, 30]) = [1, 1, 2, 1]``.
Эта функция полезна при использовании ARRAY JOIN и агрегации по элементам массива.
Пример:
This function is useful when using ARRAY JOIN and aggregation of array elements. Example:
.. code-block:: sql
......@@ -149,9 +148,11 @@ arrayEnumerateUniq(arr, ...)
│ 3271094 │ 2256 │ 812 │
└─────────┴─────────┴────────┘
В этом примере, для каждого идентификатора цели, посчитано количество достижений целей (каждый элемент вложенной структуры данных Goals является достижением целей) и количество визитов. Если бы не было ARRAY JOIN, мы бы считали количество визитов как sum(Sign). Но в данном случае, строчки были размножены по вложенной структуре Goals, и чтобы после этого учесть каждый визит один раз, мы поставили условие на значение функции arrayEnumerateUniq(Goals.ID).
In this example, each goal ID has a calculation of the number of conversions (each element in the Goals nested data structure is a goal that was reached, which we refer to as a conversion) and the number of sessions.
Without ARRAY JOIN, we would have counted the number of sessions as ``sum(Sign)``. But in this particular case, the rows were multiplied by the nested Goals structure, so in order to count each session one time after this,
we apply a condition to the value of the ``arrayEnumerateUniq(Goals.ID)`` function.
Функция arrayEnumerateUniq может принимать несколько аргументов - массивов одинаковых размеров. В этом случае, уникальность считается для кортежей элементов на одинаковых позициях всех массивов.
The arrayEnumerateUniq function can take multiple arrays of the same size as arguments. In this case, uniqueness is considered for tuples of elements in the same positions in all the arrays.
.. code-block:: sql
......@@ -161,15 +162,15 @@ arrayEnumerateUniq(arr, ...)
│ [1,2,1,1,2,1] │
└───────────────┘
Это нужно при использовании ARRAY JOIN с вложенной структурой данных и затем агрегации по нескольким элементам этой структуры.
This is necessary when using ARRAY JOIN with a nested data structure and further aggregation across multiple elements in this structure.
arrayUniq(arr, ...)
~~~~~~~~~~~~~~~~~~~
Если передан один аргумент, считает количество разных элементов в массиве.
Если передано несколько аргументов, считает количество разных кортежей из элементов на соответствующих позициях в нескольких массивах.
If a single array is passed, returns a number of unique elements in that array.
If multiple arrays of the same size are passed as arguments to the function, returns a number of unique tuples of elements in the same positions in all the arrays.
Если необходимо получить список уникальных элементов массива, можно воспользоваться arrayReduce('groupUniqArray', arr).
If you need an array of the unique elements, you can use ``arrayReduce('groupUniqArray', arr)``.
arrayJoin(arr)
~~~~~~~~
Особенная функция. Смотрите раздел "Функция arrayJoin".
A special function. See the section "arrayJoin function".
Функция arrayJoin
arrayJoin function
---------------
Это совсем необычная функция.
This is a very unusual function.
Обычные функции не изменяют множество строк, а лишь изменяют значения в каждой строке (map).
Агрегатные функции выполняют свёртку множества строк (fold, reduce).
Функция arrayJoin выполняет размножение каждой строки в множество строк (unfold).
Normal functions don't change a set of rows, but just change the values in each row (map). Aggregate functions compress a set of rows (fold or reduce).
The 'arrayJoin' function takes each row and generates a set of rows (unfold).
Функция принимает в качестве аргумента массив, и размножает исходную строку в несколько строк - по числу элементов массива.
Все значения в столбцах просто копируются, кроме значения в столбце с применением этой функции - он заменяется на соответствующее значение массива.
This function takes an array as an argument, and propagates the source row to multiple rows for the number of elements in the array.
All the values in columns are simply copied, except the values in the column where this function is applied - it is replaced with the corresponding array value.
В запросе может быть использовано несколько функций ``arrayJoin``. В этом случае, соответствующее преобразование делается несколько раз.
A query can use multiple 'arrayJoin' functions. In this case, the transformation is performed multiple times.
Обратите внимание на синтаксис ARRAY JOIN в запросе SELECT, который предоставляет более широкие возможности.
Note the ARRAY JOIN syntax in the SELECT query, which provides broader possibilities.
Пример:
Example:
.. code-block:: sql
......
Битовые функции
Bit functions
---------------
Битовые функции работают для любой пары типов из UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, Float64.
Bit functions work for any pair of types from UInt8, UInt16, UInt32, UInt64, Int8, Int16, Int32, Int64, Float32, or Float64.
``Тип результата`` - целое число, битность которого равна максимальной битности аргументов. Если хотя бы один аргумент знаковый, то результат - знаковое число. Если аргумент - число с плавающей запятой - оно приводится к Int64.
The result type is an integer with bits equal to the maximum bits of its arguments. If at least one of the arguments is signed, the result is a signed number. If an argument is a floating-point number, it is cast to Int64.
bitAnd(a, b)
~~~~~~~~~~~~
......
Функции сравнения
Comparison functions
------------------
Функции сравнения возвращают всегда 0 или 1 (UInt8).
Comparison functions always return 0 or 1 (Uint8).
Сравнивать можно следующие типы:
* числа;
* строки и фиксированные строки;
* даты;
* даты-с-временем;
The following types can be compared:
* numbers
* strings and fixed strings
* dates
* dates with times
внутри каждой группы, но не из разных групп.
within each group, but not between different groups.
Например, вы не можете сравнить дату со строкой. Надо использовать функцию преобразования строки в дату или наоборот.
For example, you can't compare a date with a string. You have to use a function to convert the string to a date, or vice versa.
Строки сравниваются побайтово. Более короткая строка меньше всех строк, начинающихся с неё и содержащих ещё хотя бы один символ.
Strings are compared by bytes. A shorter string is smaller than all strings that start with it and that contain at least one more character.
Замечание. До версии 1.1.54134 сравнение знаковых и беззнаковых целых чисел производилось также, как в C++. То есть, вы могли получить неверный результат в таких случаях: SELECT 9223372036854775807 > -1. С версии 1.1.54134 поведение изменилось и стало математически корректным.
Note: before version 1.1.54134 signed and unsigned numbers were compared the same way as in C++. That is, you could got an incorrect result in such cases: SELECT 9223372036854775807 > -1. From version 1.1.54134, the behavior has changed and numbers are compared mathematically correct.
equals, оператор a = b и a == b
equals, a = b and a == b operator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
notEquals, оператор a != b и a <> b
notEquals, a != b and a <> b operator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
less, оператор <
less, < operator
~~~~~~~~~~~~~~~~~
greater, оператор >
greater, > operator
~~~~~~~~~~~~~~~~~~~
lessOrEquals, оператор <=
lessOrEquals, <= operator
~~~~~~~~~~~~~~~~~~~~~~~~
greaterOrEquals, оператор >=
greaterOrEquals, >= operator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Условные функции
Conditional functions
-------------
if(cond, then, else), оператор cond ? then : else
~~~~~~~~~~~~~~~~~
Возвращает then, если cond != 0 или else, если cond = 0.
cond должно иметь тип UInt8, а then и else должны иметь тип, для которого есть наименьший общий тип.
Returns 'then' if 'cond != 0', or 'else' if 'cond = 0'.
'cond' must be UInt 8, and 'then' and 'else' must be a type that has the smallest common type.
Функции для работы с датами и временем
Functions for working with dates and times
--------------------------------------
Поддержка часовых поясов
Все функции по работе с датой и временем, для которых это имеет смысл, могут принимать второй, необязательный аргумент - имя часового пояса. Пример: Asia/Yekaterinburg. В этом случае, они используют не локальный часовой пояс (по умолчанию), а указанный.
Time Zone Support
All functions for working with the date and time for which this makes sense, can take a second, optional argument - the time zone name. Example: Asia / Yekaterinburg. In this case, they do not use the local time zone (the default), but the specified one.
.. code-block:: sql
SELECT
toDateTime('2016-06-15 23:00:00') AS time,
......@@ -15,127 +14,128 @@
┌────────────────time─┬─date_local─┬─date_yekat─┬─time_samoa──────────┐
│ 2016-06-15 23:00:00 │ 2016-06-15 │ 2016-06-16 │ 2016-06-15 09:00:00 │
└─────────────────────┴────────────┴────────────┴─────────────────────┘
Поддерживаются только часовые пояса, отличающиеся от UTC на целое число часов.
Only time zones are supported, different from UTC for an integer number of hours.
toYear
~~~~~~
Переводит дату или дату-с-временем в число типа UInt16, содержащее номер года (AD).
~~~~~~~
Converts a date or date with time to a UInt16 number containing the year number (AD).
toMonth
~~~~~~~
Переводит дату или дату-с-временем в число типа UInt8, содержащее номер месяца (1-12).
Converts a date or date with time to a UInt8 number containing the month number (1-12).
toDayOfMonth
~~~~~~~~~~~~
Переводит дату или дату-с-временем в число типа UInt8, содержащее номер дня в месяце (1-31).
~~~~~~~
Converts a date or date with time to a UInt8 number containing the number of the day of the month (1-31).
toDayOfWeek
~~~~~~~~~~~
Переводит дату или дату-с-временем в число типа UInt8, содержащее номер дня в неделе (понедельник - 1, воскресенье - 7).
~~~~~~~
Converts a date or date with time to a UInt8 number containing the number of the day of the week (Monday is 1, and Sunday is 7).
toHour
~~~~~~
Переводит дату-с-временем в число типа UInt8, содержащее номер часа в сутках (0-23).
Функция исходит из допущения, что перевод стрелок вперёд, если осуществляется, то на час, в два часа ночи, а перевод стрелок назад, если осуществляется, то на час, в три часа ночи (что, в общем, не верно - даже в Москве два раза перевод стрелок был осуществлён в другое время).
~~~~~~~
Converts a date with time to a UInt8 number containing the number of the hour in 24-hour time (0-23).
This function assumes that if clocks are moved ahead, it is by one hour and occurs at 2 a.m., and if clocks are moved back, it is by one hour and occurs at 3 a.m. (which is not always true - even in Moscow the clocks were once changed at a different time).
toMinute
~~~~~~~~
Переводит дату-с-временем в число типа UInt8, содержащее номер минуты в часе (0-59).
~~~~~~~
Converts a date with time to a UInt8 number containing the number of the minute of the hour (0-59).
toSecond
~~~~~~~~
Переводит дату-с-временем в число типа UInt8, содержащее номер секунды в минуте (0-59).
Секунды координации не учитываются.
~~~~~~~
Converts a date with time to a UInt8 number containing the number of the second in the minute (0-59).
Leap seconds are not accounted for.
toStartOfDay
~~~~~~~
Rounds down a date with time to the start of the day.
toMonday
~~~~~~~~
Округляет дату или дату-с-временем вниз до ближайшего понедельника.
Возвращается дата.
~~~~~~~
Rounds down a date or date with time to the nearest Monday.
Returns the date.
toStartOfMonth
~~~~~~~~~~~~~~
Округляет дату или дату-с-временем вниз до первого дня месяца.
Возвращается дата.
~~~~~~~
Rounds down a date or date with time to the first day of the month.
Returns the date.
toStartOfQuarter
~~~~~~~~~~~~~~~~
Округляет дату или дату-с-временем вниз до первого дня квартала.
Первый день квартала - это одно из 1 января, 1 апреля, 1 июля, 1 октября.
Возвращается дата.
~~~~~~~
Rounds down a date or date with time to the first day of the quarter.
The first day of the quarter is either 1 January, 1 April, 1 July, or 1 October. Returns the date.
toStartOfYear
~~~~~~~~~~~~~~
Округляет дату или дату-с-временем вниз до первого дня года.
Возвращается дата.
~~~~~~~
Rounds down a date or date with time to the first day of the year.
Returns the date.
toStartOfMinute
~~~~~~~~~~~~~~~
Округляет дату-с-временем вниз до начала минуты.
~~~~~~~
Rounds down a date with time to the start of the minute.
toStartOfFiveMinute
~~~~~~~~~~~~~~~~~~~
Округляет дату-с-временем вниз до начала пятиминутного интервала.
Замечание: если вам нужно округлить дату-с-временем до какого-либо другого количества секунд, минут или часов, вы можете перевести её в число с помощью функции toUInt32, затем округлить число с помощью функции intDiv и умножения, а затем перевести обратно, с помощью функции toDateTime.
~~~~~~~
Rounds down a date with time to the start of the 5 minute (00:00, 00:05, 00:10...).
toStartOfHour
~~~~~~~~~~~~~
Округляет дату-с-временем вниз до начала часа.
~~~~~~~
Rounds down a date with time to the start of the hour.
toTime
~~~~~~~
Переводит дату-с-временем на некоторую фиксированную дату, сохраняя при этом время.
Converts a date with time to some fixed date, while preserving the time.
toRelativeYearNum
~~~~~~~~~~~~~~~~~
Переводит дату-с-временем или дату в номер года, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the year, starting from a certain fixed point in the past.
toRelativeMonthNum
~~~~~~~~~~~~~~~~~~
Переводит дату-с-временем или дату в номер месяца, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the month, starting from a certain fixed point in the past.
toRelativeWeekNum
~~~~~~~~~~~~~~~~~
Переводит дату-с-временем или дату в номер недели, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the week, starting from a certain fixed point in the past.
toRelativeDayNum
~~~~~~~~~~~~~~~~
Переводит дату-с-временем или дату в номер дня, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the day, starting from a certain fixed point in the past.
toRelativeHourNum
~~~~~~~~~~~~~~~~~
Переводит дату-с-временем в номер часа, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the hour, starting from a certain fixed point in the past.
toRelativeMinuteNum
~~~~~~~~~~~~~~~~~~~
Переводит дату-с-временем в номер минуты, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the minute, starting from a certain fixed point in the past.
toRelativeSecondNum
~~~~~~~~~~~~~~~~~~~
Переводит дату-с-временем в номер секунды, начиная с некоторого фиксированного момента в прошлом.
~~~~~~~
Converts a date with time or date to the number of the second, starting from a certain fixed point in the past.
now
~~~
Принимает ноль аргументов и возвращает текущее время на один из моментов выполнения запроса.
Функция возвращает константу, даже если запрос выполнялся долго.
~~~~~~~
Accepts zero arguments and returns the current time at one of the moments of request execution.
This function returns a constant, even if the request took a long time to complete.
today
~~~~~
Принимает ноль аргументов и возвращает текущую дату на один из моментов выполнения запроса.
То же самое, что toDate(now())
~~~~~~~
Accepts zero arguments and returns the current date at one of the moments of request execution.
The same as 'toDate(now())'.
yesterday
~~~~~~~~~
Принимает ноль аргументов и возвращает вчерашнюю дату на один из моментов выполнения запроса.
Делает то же самое, что today() - 1.
~~~~~~~
Accepts zero arguments and returns yesterday's date at one of the moments of request execution.
The same as 'today() - 1'.
timeSlot
~~~~~~~~
Округляет время до получаса.
Эта функция является специфичной для Яндекс.Метрики, так как пол часа - минимальное время, для которого, если соседние по времени хиты одного посетителя на одном счётчике отстоят друг от друга строго более, чем на это время, визит может быть разбит на два визита. То есть, кортежи (номер счётчика, идентификатор посетителя, тайм-слот) могут использоваться для поиска хитов, входящий в соответствующий визит.
~~~~~~~
Rounds the time to the half hour.
This function is specific to Yandex.Metrica, since half an hour is the minimum amount of time for breaking a session into two sessions if a counter shows a single user's consecutive pageviews that differ in time by strictly more than this amount. This means that tuples (the counter number, user ID, and time slot) can be used to search for pageviews that are included in the corresponding session.
timeSlots(StartTime, Duration)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Для интервала времени, начинающегося в StartTime и продолжающегося Duration секунд, возвращает массив моментов времени, состоящий из округлений вниз до получаса точек из этого интервала.
Например, ``timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')]``.
Это нужно для поиска хитов, входящих в соответствующий визит.
~~~~~~~
For a time interval starting at 'StartTime' and continuing for 'Duration' seconds, it returns an array of moments in time, consisting of points from this interval rounded down to the half hour.
For example, timeSlots(toDateTime('2012-01-01 12:20:00'), toUInt32(600)) = [toDateTime('2012-01-01 12:00:00'), toDateTime('2012-01-01 12:30:00')].
This is necessary for searching for pageviews in the corresponding session.
Функции кодирования
Encoding functions
--------
hex
~~~~~
Принимает строку, число, дату или дату-с-временем. Возвращает строку, содержащую шестнадцатеричное представление аргумента. Используются заглавные буквы A-F. Не используются префиксы 0x и суффиксы h. Для строк просто все байты кодируются в виде двух шестнадцатеричных цифр. Числа выводятся в big endian ("человеческом") формате. Для чисел вырезаются старшие нули, но только по целым байтам. Например, hex(1) = '01'. Даты кодируются как число дней с начала unix-эпохи. Даты-с-временем кодируются как число секунд с начала unix-эпохи.
Accepts a string, number, date, or date with time. Returns a string containing the argument's hexadecimal representation. Uses uppercase letters A-F.
Doesn't use ``0x`` prefixes or ``h`` suffixes.
For strings, all bytes are simply encoded as two hexadecimal numbers. Numbers are converted to big endian ("human readable") format.
For numbers, older zeros are trimmed, but only by entire bytes.
For example, ``hex(1) = '01'``. Dates are encoded as the number of days since the beginning of the Unix Epoch. Dates with times are encoded as the number of seconds since the beginning of the Unix Epoch.
unhex(str)
~~~~~~~
Принимает строку, содержащую произвольное количество шестнадцатеричных цифр, и возвращает строку, содержащую соответствующие байты. Поддерживаются как строчные, так и заглавные буквы A-F. Число шестнадцатеричных цифр не обязано быть чётным. Если оно нечётное - последняя цифра интерпретируется как младшая половинка байта 00-0F. Если строка-аргумент содержит что-либо кроме шестнадцатеричных цифр, то будет возвращён какой-либо implementation-defined результат (не кидается исключение).
Если вы хотите преобразовать результат в число, то вы можете использовать функции reverse и reinterpretAsType.
Accepts a string containing any number of hexadecimal digits, and returns a string containing the corresponding bytes. Supports both uppercase and lowercase letters A-F. The number of hexadecimal digits doesn't have to be even. If it is odd, the last digit is interpreted as the younger half of the 00-0F byte. If the argument string contains anything other than hexadecimal digits, some implementation-defined result is returned (an exception isn't thrown).
If you want to convert the result to a number, you can use the functions 'reverse' and 'reinterpretAsType'
UUIDStringToNum(str)
~~~~~~~
Принимает строку, содержащую 36 символов в формате 123e4567-e89b-12d3-a456-426655440000, и возвращает в виде набора байт в FixedString(16).
Accepts a string containing the UUID in the text format (``123e4567-e89b-12d3-a456-426655440000``). Returns a binary representation of the UUID in ``FixedString(16)``.
UUIDNumToString(str)
~~~~~~~~
Принимает значение типа FixedString(16). Возвращает строку из 36 символов в текстовом виде.
Accepts a FixedString(16) value containing the UUID in the binary format. Returns a readable string containing the UUID in the text format.
bitmaskToList(num)
~~~~~~~
Принимает целое число. Возвращает строку, содержащую список степеней двойки, в сумме дающих исходное число; по возрастанию, в текстовом виде, через запятую, без пробелов.
Accepts an integer. Returns a string containing the list of powers of two that total the source number when summed. They are comma-separated without spaces in text format, in ascending order.
bitmaskToArray(num)
~~~~~~~~~
Принимает целое число. Возвращает массив чисел типа UInt64, содержащий степени двойки, в сумме дающих исходное число; числа в массиве идут по возрастанию.
Accepts an integer. Returns an array of UInt64 numbers containing the list of powers of two that total the source number when summed. Numbers in the array are in ascending order.
Функции для работы с внешними словарями
Functions for working with external dictionaries
-------
Подробнее смотрите в разделе "Внешние словари".
For more information, see the section "External dictionaries".
dictGetUInt8, dictGetUInt16, dictGetUInt32, dictGetUInt64
~~~~~~~~~
......@@ -17,27 +17,27 @@ dictGetDate, dictGetDateTime
dictGetString
~~~~~~
``dictGetT('dict_name', 'attr_name', id)``
- получить из словаря dict_name значение атрибута attr_name по ключу id.
``dict_name`` и ``attr_name`` - константные строки.
``id`` должен иметь тип UInt64.
Если ключа ``id`` нет в словаре - вернуть значение по умолчанию, заданное в описании словаря.
- Gets the value of the 'attr_name' attribute from the 'dict_name' dictionary by the 'id' key.
'dict_name' and 'attr_name' are constant strings.
'id' must be UInt64.
If the 'id' key is not in the dictionary, it returns the default value set in the dictionary definition.
dictGetTOrDefault
~~~~~~~~
``dictGetT('dict_name', 'attr_name', id, default)``
Аналогично функциям dictGetT, но значение по умолчанию берётся из последнего аргумента функции.
Similar to the functions dictGetT, but the default value is taken from the last argument of the function.
dictIsIn
~~~~~~
``dictIsIn('dict_name', child_id, ancestor_id)``
- для иерархического словаря dict_name - узнать, находится ли ключ child_id внутри ancestor_id (или совпадает с ancestor_id). Возвращает UInt8.
- For the 'dict_name' hierarchical dictionary, finds out whether the 'child_id' key is located inside 'ancestor_id' (or matches 'ancestor_id'). Returns UInt8.
dictGetHierarchy
~~~~~~~~
``dictGetHierarchy('dict_name', id)``
- для иерархического словаря dict_name - вернуть массив ключей словаря, начиная с id и продолжая цепочкой родительских элементов. Возвращает Array(UInt64).
- For the 'dict_name' hierarchical dictionary, returns an array of dictionary keys starting from 'id' and continuing along the chain of parent elements. Returns Array(UInt64).
dictHas
~~~~~~
``dictHas('dict_name', id)``
- проверить наличие ключа в словаре. Возвращает значение типа UInt8, равное 0, если ключа нет и 1, если ключ есть.
- check the presence of a key in the dictionary. Returns a value of type UInt8, equal to 0, if there is no key and 1 if there is a key.
Функции хэширования
Hash functions
-------------
Функции хэширования могут использоваться для детерминированного псевдослучайного разбрасывания элементов.
Hash functions can be used for deterministic pseudo-random shuffling of elements.
halfMD5
~~~~~~
Вычисляет MD5 от строки. Затем берёт первые 8 байт от хэша и интерпретирует их как UInt64 в big endian.
Принимает аргумент типа String. Возвращает UInt64.
Функция работает достаточно медленно (5 миллионов коротких строк в секунду на одном процессорном ядре).
Если вам не нужен конкретно MD5, то используйте вместо этого функцию sipHash64.
Calculates the MD5 from a string. Then it takes the first 8 bytes of the hash and interprets them as UInt64 in big endian.
Accepts a String-type argument. Returns UInt64.
This function works fairly slowly (5 million short strings per second per processor core).
If you don't need MD5 in particular, use the 'sipHash64' function instead.
MD5
~~~
Вычисляет MD5 от строки и возвращает полученный набор байт в виде FixedString(16).
Если вам не нужен конкретно MD5, а нужен неплохой криптографический 128-битный хэш, то используйте вместо этого функцию sipHash128.
Если вы хотите получить такой же результат, как выдаёт утилита md5sum, напишите lower(hex(MD5(s))).
Calculates the MD5 from a string and returns the resulting set of bytes as FixedString(16).
If you don't need MD5 in particular, but you need a decent cryptographic 128-bit hash, use the 'sipHash128' function instead.
If you need the same result as gives 'md5sum' utility, write ``lower(hex(MD5(s)))``.
sipHash64
~~~~~~~
Вычисляет SipHash от строки.
Принимает аргумент типа String. Возвращает UInt64.
SipHash - криптографическая хэш-функция. Работает быстрее чем MD5 не менее чем в 3 раза.
Подробнее смотрите по ссылке: https://131002.net/siphash/
Calculates SipHash from a string.
Accepts a String-type argument. Returns UInt64.
SipHash is a cryptographic hash function. It works at least three times faster than MD5. For more information, see https://131002.net/siphash/
sipHash128
~~~~~
Вычисляет SipHash от строки.
Принимает аргумент типа String. Возвращает FixedString(16).
Отличается от sipHash64 тем, что финальный xor-folding состояния делается только до 128 бит.
Calculates SipHash from a string.
Accepts a String-type argument. Returns FixedString(16).
Differs from sipHash64 in that the final xor-folding state is only done up to 128 bits.
cityHash64
~~~~~
Вычисляет CityHash64 от строки или похожую хэш-функцию для произвольного количества аргументов произвольного типа.
Если аргумент имеет тип String, то используется CityHash. Это быстрая некриптографическая хэш-функция неплохого качества для строк.
Если аргумент имеет другой тип, то используется implementation specific быстрая некриптографическая хэш-функция неплохого качества.
Если передано несколько аргументов, то функция вычисляется по тем же правилам, с помощью комбинации по цепочке с использованием комбинатора из CityHash.
Например, так вы можете вычислить чексумму всей таблицы с точностью до порядка строк: ``SELECT sum(cityHash64(*)) FROM table``.
Calculates CityHash64 from a string or a similar hash function for any number of any type of arguments.
For String-type arguments, CityHash is used. This is a fast non-cryptographic hash function for strings with decent quality.
For other types of arguments, a decent implementation-specific fast non-cryptographic hash function is used.
If multiple arguments are passed, the function is calculated using the same rules and chain combinations using the CityHash combinator.
For example, you can compute the checksum of an entire table with accuracy up to the row order: ``SELECT sum(cityHash64(*)) FROM table``.
intHash32
~~~~~
Вычисляет 32-битный хэш-код от целого числа любого типа.
Это сравнительно быстрая некриптографическая хэш-функция среднего качества для чисел.
Calculates a 32-bit hash code from any type of integer.
This is a relatively fast non-cryptographic hash function of average quality for numbers.
intHash64
~~~~~
Вычисляет 64-битный хэш-код от целого числа любого типа.
Работает быстрее, чем intHash32. Качество среднее.
Calculates a 64-bit hash code from any type of integer.
It works faster than intHash32. Average quality.
SHA1
~~~~
......@@ -55,14 +54,16 @@ SHA224
SHA256
~~~~~
Вычисляет SHA-1, SHA-224, SHA-256 от строки и возвращает полученный набор байт в виде FixedString(20), FixedString(28), FixedString(32).
Функция работает достаточно медленно (SHA-1 - примерно 5 миллионов коротких строк в секунду на одном процессорном ядре, SHA-224 и SHA-256 - примерно 2.2 миллионов).
Рекомендуется использовать эти функции лишь в тех случаях, когда вам нужна конкретная хэш-функция и вы не можете её выбрать.
Даже в этих случаях, рекомендуется применять функцию оффлайн - заранее вычисляя значения при вставке в таблицу, вместо того, чтобы применять её при SELECT-ах.
Calculates SHA-1, SHA-224, or SHA-256 from a string and returns the resulting set of bytes as FixedString(20), FixedString(28), or FixedString(32).
The function works fairly slowly (SHA-1 processes about 5 million short strings per second per processor core, while SHA-224 and SHA-256 process about 2.2 million).
We recommend using this function only in cases when you need a specific hash function and you can't select it.
Even in these cases, we recommend applying the function offline and pre-calculating values when inserting them into the table, instead of applying it in SELECTS.
URLHash(url[, N])
~~~~~~~~
Быстрая некриптографическая хэш-функция неплохого качества для строки, полученной из URL путём некоторой нормализации.
``URLHash(s)`` - вычислить хэш от строки без одного завершающего символа ``/``, ``?`` или ``#`` на конце, если такой там есть.
``URLHash(s, N)`` - вычислить хэш от строки до N-го уровня в иерархии URL, без одного завершающего символа ``/``, ``?`` или ``#`` на конце, если такой там есть.
Уровни аналогичные URLHierarchy. Функция специфична для Яндекс.Метрики.
A fast, decent-quality non-cryptographic hash function for a string obtained from a URL using some type of normalization.
``URLHash(s)`` - Calculates a hash from a string without one of the trailing symbols ``/``,``?`` or ``#`` at the end, if present.
``URL Hash(s, N)`` - Calculates a hash from a string up to the N level in the URL hierarchy, without one of the trailing symbols ``/``,``?`` or ``#`` at the end, if present.
Levels are the same as in URLHierarchy. This function is specific to Yandex.Metrica.
Функции высшего порядка
Higher-order functions
-----------------------
Оператор ->, функция lambda(params, expr)
-> operator, lambda(params, expr) function
~~~~~~~~~~~~~~
Позволяет описать лямбда-функцию для передачи в функцию высшего порядка. Слева от стрелочки стоит формальный параметр - произвольный идентификатор, или несколько формальных параметров - произвольные идентификаторы в кортеже. Справа от стрелочки стоит выражение, в котором могут использоваться эти формальные параметры, а также любые столбцы таблицы.
Allows describing a lambda function for passing to a higher-order function. The left side of the arrow has a formal parameter - any ID, or multiple formal parameters - any IDs in a tuple. The right side of the arrow has an expression that can use these formal parameters, as well as any table columns.
Примеры: ``x -> 2 * x, str -> str != Referer.``
Examples: ``x -> 2 * x, str -> str != Referer.``
Функции высшего порядка, в качестве своего функционального аргумента могут принимать только лямбда-функции.
Higher-order functions can only accept lambda functions as their functional argument.
В функции высшего порядка может быть передана лямбда-функция, принимающая несколько аргументов. В этом случае, в функцию высшего порядка передаётся несколько массивов одинаковых длин, которым эти аргументы будут соответствовать.
A lambda function that accepts multiple arguments can be passed to a higher-order function. In this case, the higher-order function is passed several arrays of identical length that these arguments will correspond to.
Для всех функций кроме arrayMap, arrayFilter, первый аргумент (лямбда-функция) может отсутствовать. В этом случае, подразумевается тождественное отображение.
For all functions other than 'arrayMap' and 'arrayFilter', the first argument (the lambda function) can be omitted. In this case, identical mapping is assumed.
arrayMap(func, arr1, ...)
~~~~~~~~~~~~
Вернуть массив, полученный из исходного применением функции func к каждому элементу массива arr.
Returns an array obtained from the original application of the 'func' function to each element in the 'arr' array.
arrayFilter(func, arr1, ...)
~~~~~~~~~~~~~
Вернуть массив, содержащий только те элементы массива arr1, для которых функция func возвращает не 0.
Returns an array containing only the elements in 'arr1' for which 'func' returns something other than 0.
Примеры:
Examples:
.. code-block:: sql
......@@ -44,24 +44,24 @@ arrayFilter(func, arr1, ...)
arrayCount([func,] arr1, ...)
~~~~~~~~~
Вернуть количество элементов массива arr, для которых функция func возвращает не 0. Если func не указана - вернуть количество ненулевых элементов массива.
Returns the number of elements in 'arr' for which 'func' returns something other than 0. If 'func' is not specified, it returns the number of non-zero items in the array.
arrayExists([func,] arr1, ...)
~~~~~~~~~~
Вернуть 1, если существует хотя бы один элемент массива arr, для которого функция func возвращает не 0. Иначе вернуть 0.
Returns 1 if there is at least one element in 'arr' for which 'func' returns something other than 0. Otherwise, it returns 0.
arrayAll([func,] arr1, ...)
~~~~~~~~~
Вернуть 1, если для всех элементов массива arr, функция func возвращает не 0. Иначе вернуть 0.
Returns 1 if 'func' returns something other than 0 for all the elements in 'arr'. Otherwise, it returns 0.
arraySum([func,] arr1, ...)
~~~~~~~~~~~
Вернуть сумму значений функции func. Если функция не указана - просто вернуть сумму элементов массива.
Returns the sum of the 'func' values. If the function is omitted, it just returns the sum of the array elements.
arrayFirst(func, arr1, ...)
~~~~~~~~~
Вернуть первый элемент массива arr1, для которого функция func возвращает не 0.
Returns the first element in the 'arr1' array for which 'func' returns something other than 0.
arrayFirstIndex(func, arr1, ...)
~~~~~~~
Вернуть индекс первого элемента массива arr1, для которого функция func возвращает не 0.
Returns the index of the first element in the 'arr1' array for which 'func' returns something other than 0.
Функции для реализации оператора IN.
Functions for implementing the IN operator
---------------
in, notIn, globalIn, globalNotIn
~~~~~~~~~~~~~
Смотрите раздел "Операторы IN".
See the section "IN operators".
tuple(x, y, ...), оператор (x, y, ...)
~~~~~~~~~~~~~
Функция, позволяющая сгруппировать несколько столбцов.
Для столбцов, имеющих типы T1, T2, ... возвращает кортеж типа Tuple(T1, T2, ...), содержащий эти столбцы. Выполнение функции ничего не стоит.
Кортежи обычно используются как промежуточное значение в качестве аргумента операторов IN, или для создания списка формальных параметров лямбда-функций. Кортежи не могут быть записаны в таблицу.
A function that allows grouping multiple columns.
For columns with the types T1, T2, ..., it returns a Tuple(T1, T2, ...) type tuple containing these columns. There is no cost to execute the function.
Tuples are normally used as intermediate values for an argument of IN operators, or for creating a list of formal parameters of lambda functions. Tuples can't be written to a table.
tupleElement(tuple, n), оператор x.N
~~~~~~~~~~~
Функция, позволяющая достать столбец из кортежа.
N - индекс столбца начиная с 1. N должно быть константой. N должно быть целым строго положительным числом не большим размера кортежа.
Выполнение функции ничего не стоит.
A function that allows getting columns from a tuple.
'N' is the column index, starting from 1. 'N' must be a constant. 'N' must be a strict postive integer no greater than the size of the tuple.
There is no cost to execute the function.
Функции
Functions
=======
Функции бывают как минимум* двух видов - обычные функции (называются просто, функциями) и агрегатные функции. Это совершенно разные вещи. Обычные функции работают так, как будто применяются к каждой строке по отдельности (для каждой строки, результат вычисления функции не зависит от других строк). Агрегатные функции аккумулируют множество значений из разных строк (то есть, зависят от целого множества строк).
There are at least* two types of functions - regular functions (they are just called "functions") and aggregate functions. These are completely different concepts. Regular functions work as if they are applied to each row separately (for each row, the result of the function doesn't depend on the other rows). Aggregate functions accumulate a set of values from various rows (i.e. they depend on the entire set of rows).
В этом разделе речь пойдёт об обычных функциях. Для агрегатных функций, смотрите раздел "Агрегатные функции".
*\* - есть ещё третий вид функций, к которым относится функция arrayJoin; также можно отдельно иметь ввиду табличные функции.*
In this section we discuss regular functions. For aggregate functions, see the section "Aggregate functions".
* - There is a third type of function that the 'arrayJoin' function belongs to; table functions can also be mentioned separately.
......@@ -16,61 +15,57 @@
*/index
Строгая типизация
Strong typing
~~~~~~~~~~~~~~~~~
In contrast to standard SQL, ClickHouse has strong typing. In other words, it doesn't make implicit conversions between types. Each function works for a specific set of types. This means that sometimes you need to use type conversion functions.
В ClickHouse, в отличие от стандартного SQL, типизация является строгой. То есть, не производится неявных преобразований между типами. Все функции работают для определённого набора типов. Это значит, что иногда вам придётся использовать функции преобразования типов.
Склейка одинаковых выражений
Common subexpression elimination
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All expressions in a query that have the same AST (the same record or same result of syntactic parsing) are considered to have identical values. Such expressions are concatenated and executed once. Identical subqueries are also eliminated this way.
Все выражения в запросе, имеющие одинаковые AST (одинаковую запись или одинаковый результат синтаксического разбора), считаются имеющими одинаковые значения. Такие выражения склеиваются и исполняются один раз. Одинаковые подзапросы тоже склеиваются.
Типы результата
Types of results
~~~~~~~~~~~~~~~
All functions return a single return as the result (not several values, and not zero values). The type of result is usually defined only by the types of arguments, not by the values. Exceptions are the tupleElement function (the a.N operator), and the toFixedString function.
Все функции возвращают одно (не несколько, не ноль) значение в качестве результата. Тип результата обычно определяется только типами аргументов, но не значениями аргументов. Исключение - функция tupleElement (оператор a.N), а также функция toFixedString.
Константы
Constants
~~~~~~~~~
For simplicity, certain functions can only work with constants for some arguments. For example, the right argument of the LIKE operator must be a constant.
Almost all functions return a constant for constant arguments. The exception is functions that generate random numbers.
The 'now' function returns different values for queries that were run at different times, but the result is considered a constant, since constancy is only important within a single query.
A constant expression is also considered a constant (for example, the right half of the LIKE operator can be constructed from multiple constants).
Для простоты, некоторые функции могут работать только с константами в качестве некоторых аргументов. Например, правый аргумент оператора LIKE должен быть константой.
Почти все функции возвращают константу для константных аргументов. Исключение - функции генерации случайных чисел.
Функция now возвращает разные значения для запросов, выполненных в разное время, но результат считается константой, так как константность важна лишь в пределах одного запроса.
Константное выражение также считается константой (например, правую часть оператора LIKE можно сконструировать из нескольких констант).
Функции могут быть по-разному реализованы для константных и не константных аргументов (выполняется разный код). Но результат работы для константы и полноценного столбца, содержащего только одно такое же значение, должен совпадать.
Functions can be implemented in different ways for constant and non-constant arguments (different code is executed). But the results for a constant and for a true column containing only the same value should match each other.
Неизменяемость
Immutability
~~~~~~~~~~~~~~
Функции не могут поменять значения своих аргументов - любые изменения возвращаются в качестве результата. Соответственно, от порядка записи функций в запросе, результат вычислений отдельных функций не зависит.
Functions can't change the values of their arguments - any changes are returned as the result. Thus, the result of calculating separate functions does not depend on the order in which the functions are written in the query.
Обработка ошибок
Error handling
~~~~~~~~~~~~~~~~
Некоторые функции могут кидать исключения в случае ошибочных данных. В этом случае, выполнение запроса прерывается, и текст ошибки выводится клиенту. При распределённой обработке запроса, при возникновении исключения на одном из серверов, на другие серверы пытается отправиться просьба тоже прервать выполнение запроса.
Some functions might throw an exception if the data is invalid. In this case, the query is canceled and an error text is returned to the client. For distributed processing, when an exception occurs on one of the servers, the other servers also attempt to abort the query.
Вычисление выражений-аргументов
Evaluation of argument expressions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
В почти всех языках программирования, для некоторых операторов может не вычисляться один из аргументов. Обычно - для операторов ``&&``, ``||``, ``?:``.
Но в ClickHouse, аргументы функций (операторов) вычисляются всегда. Это связано с тем, что вычисления производятся не по отдельности для каждой строки, а сразу для целых кусочков столбцов.
In almost all programming languages, one of the arguments might not be evaluated for certain operators. This is usually for the operators ``&&``, ``||``, ``?:``.
But in ClickHouse, arguments of functions (operators) are always evaluated. This is because entire parts of columns are evaluated at once, instead of calculating each row separately.
Выполнение функций при распределённой обработке запроса
Performing functions for distributed query processing
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
При распределённой обработке запроса, как можно большая часть стадий выполнения запроса производится на удалённых серверах, а оставшиеся стадии (слияние промежуточных результатов и всё, что дальше) - на сервере-инициаторе запроса.
For distributed query processing, as many stages of query processing as possible are performed on remote servers, and the rest of the stages (merging intermediate results and everything after that) are performed on the requestor server.
Это значит, что выполнение функций может производиться на разных серверах.
Например, в запросе ``SELECT f(sum(g(x))) FROM distributed_table GROUP BY h(y),``
- если ``distributed_table`` имеет хотя бы два шарда, то функции g и h выполняются на удалённых серверах, а функция f - на сервере-инициаторе запроса;
- если ``distributed_table`` имеет только один шард, то все функции f, g, h выполняются на сервере этого шарда.
This means that functions can be performed on different servers.
For example, in the query ``SELECT f(sum(g(x))) FROM distributed_table GROUP BY h(y)``,
- if distributed_table has at least two shards, the functions ``g`` and ``h`` are performed on remote servers, and the function ``f`` - is performed on the requestor server.
- if distributed_table has only one shard, all the functions ``f``, ``g``, and ``h`` are performed on this shard's server.
Обычно результат выполнения функции не зависит от того, на каком сервере её выполнить. Но иногда это довольно важно.
Например, функции, работающие со словарями, будут использовать словарь, присутствующий на том сервере, на котором они выполняются.
Другой пример - функция ``hostName`` вернёт имя сервера, на котором она выполняется, и это можно использовать для служебных целей - чтобы в запросе ``SELECT`` сделать ``GROUP BY`` по серверам.
The result of a function usually doesn't depend on which server it is performed on. However, sometimes this is important.
For example, functions that work with dictionaries use the dictionary that exists on the server they are running on.
Another example is the hostName function, which returns the name of the server it is running on in order to make GROUP BY by servers in a SELECT query.
Если функция в запросе выполняется на сервере-инициаторе запроса, а вам нужно, чтобы она выполнялась на удалённых серверах, вы можете обернуть её в агрегатную функцию any или добавить в ключ в ``GROUP BY``.
If a function in a query is performed on the requestor server, but you need to perform it on remote servers, you can wrap it in an 'any' aggregate function or add it to a key in GROUP BY.
Функции для работы с IP-адресами
Functions for working with IP addresses
-------------------------
IPv4NumToString(num)
~~~~~~~~~~~~~
Принимает число типа UInt32. Интерпретирует его, как IPv4-адрес в big endian. Возвращает строку, содержащую соответствующий IPv4-адрес в формате A.B.C.D (числа в десятичной форме через точки).
Takes a UInt32 number. Interprets it as an IPv4 address in big endian. Returns a string containing the corresponding IPv4 address in the format A.B.C.d (dot-separated numbers in decimal form).
IPv4StringToNum(s)
~~~~~~~~
Функция, обратная к IPv4NumToString. Если IPv4 адрес в неправильном формате, то возвращает 0.
The reverse function of IPv4NumToString. If the IPv4 address has an invalid format, it returns 0.
IPv4NumToStringClassC(num)
~~~~~~~~~~~
Похоже на IPv4NumToString, но вместо последнего октета используется xxx.
Similar to IPv4NumToString, but using ``xxx`` instead of the last octet.
Пример:
Example:
.. code-block:: sql
......@@ -38,12 +38,12 @@ IPv4NumToStringClassC(num)
│ 83.149.48.xxx │ 17406 │
└────────────────┴───────┘
В связи с тем, что использование xxx весьма необычно, это может быть изменено в дальнейшем, и вам не следует полагаться на конкретный вид этого фрагмента.
Since using ``'xxx'`` is highly unusual, this may be changed in the future. We recommend that you don't rely on the exact format of this fragment.
IPv6NumToString(x)
~~~~~~~~~~~~
Принимает значение типа FixedString(16), содержащее IPv6-адрес в бинарном виде. Возвращает строку, содержащую этот адрес в текстовом виде.
IPv6-mapped IPv4 адреса выводится в формате ::ffff:111.222.33.44. Примеры:
Accepts a FixedString(16) value containing the IPv6 address in binary format. Returns a string containing this address in text format.
IPv6-mapped IPv4 addresses are output in the format ``::ffff:111.222.33.44``. Examples:
.. code-block:: sql
......@@ -97,5 +97,5 @@ IPv6-mapped IPv4 адреса выводится в формате ::ffff:111.22
IPv6StringToNum(s)
~~~~~~~~
Функция, обратная к IPv6NumToString. Если IPv6 адрес в неправильном формате, то возвращает строку из нулевых байт.
HEX может быть в любом регистре.
The reverse function of IPv6NumToString. If the IPv6 address has an invalid format, it returns a string of null bytes.
HEX can be uppercase or lowercase.
Функции для работы с JSON.
Functions for working with JSON.
-------------------
В Яндекс.Метрике пользователями передаётся JSON в качестве параметров визитов. Для работы с таким JSON-ом, реализованы некоторые функции. (Хотя в большинстве случаев, JSON-ы дополнительно обрабатываются заранее, и полученные значения кладутся в отдельные столбцы в уже обработанном виде.) Все эти функции исходят из сильных допущений о том, каким может быть JSON, и при этом стараются почти ничего не делать.
In Yandex.Metrica, JSON is passed by users as session parameters. There are several functions for working with this JSON. (Although in most of the cases, the JSONs are additionally pre-processed, and the resulting values are put in separate columns in their processed format.) All these functions are based on strong assumptions about what the JSON can be, but they try not to do anything.
Делаются следующие допущения:
#. Имя поля (аргумент функции) должно быть константой;
#. Считается, что имя поля в JSON-е закодировано некоторым каноническим образом. Например, ``visitParamHas('{"abc":"def"}', 'abc') = 1``, но ``visitParamHas('{"\\u0061\\u0062\\u0063":"def"}', 'abc') = 0``
#. Поля ищутся на любом уровне вложенности, без разбора. Если есть несколько подходящих полей - берётся первое.
#. В JSON-е нет пробельных символов вне строковых литералов.
The following assumptions are made:
#. The field name (function argument) must be a constant.
#. The field name is somehow canonically encoded in JSON. For example, ``visitParamHas('{"abc":"def"}', 'abc') = 1``, but ``visitParamHas('{"\\u0061\\u0062\\u0063":"def"}', 'abc') = 0``
#. Fields are searched for on any nesting level, indiscriminately. If there are multiple matching fields, the first occurrence is used.
#. JSON doesn't have space characters outside of string literals.
visitParamHas(params, name)
~~~~~~~
Проверить наличие поля с именем name.
Checks whether there is a field with the 'name' name.
visitParamExtractUInt(params, name)
~~~~~~~~~
Распарсить UInt64 из значения поля с именем name. Если поле строковое - попытаться распарсить число из начала строки. Если такого поля нет, или если оно есть, но содержит не число, то вернуть 0.
Parses UInt64 from the value of the field named 'name'. If this is a string field, it tries to parse a number from the beginning of the string. If the field doesn't exist, or it exists but doesn't contain a number, it returns 0.
visitParamExtractInt(params, name)
~~~~~~~
Аналогично для Int64.
The same as for Int64.
visitParamExtractFloat(params, name)
~~~~~~~
Аналогично для Float64.
The same as for Float64.
visitParamExtractBool(params, name)
~~~~~~~~
Распарсить значение true/false. Результат - UInt8.
Parses a true/false value. The result is UInt8.
visitParamExtractRaw(params, name)
~~~~~~~
Вернуть значение поля, включая разделители.
Returns the value of a field, including separators.
Примеры:
Examples:
::
visitParamExtractRaw('{"abc":"\\n\\u0000"}', 'abc') = '"\\n\\u0000"'
visitParamExtractRaw('{"abc":{"def":[1,2,3]}}', 'abc') = '{"def":[1,2,3]}'
visitParamExtractString(params, name)
~~~~~~~~~~~
Распарсить строку в двойных кавычках. У значения убирается экранирование. Если убрать экранированные символы не удалось, то возвращается пустая строка.
Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string.
Примеры:
Examples:
::
visitParamExtractString('{"abc":"\\n\\u0000"}', 'abc') = '\n\0'
visitParamExtractString('{"abc":"\\u263a"}', 'abc') = '☺'
visitParamExtractString('{"abc":"\\u263"}', 'abc') = ''
visitParamExtractString('{"abc":"hello}', 'abc') = ''
На данный момент, не поддерживаются записанные в формате ``\uXXXX\uYYYY`` кодовые точки не из basic multilingual plane (они переводятся не в UTF-8, а в CESU-8).
Currently, there is no support for code points not from the basic multilingual plane written in the format ``\uXXXX\uYYYY`` (they are converted to CESU-8 instead of UTF-8).
Логические функции
Logical functions
------------------
Логические функции принимают любые числовые типы, а возвращают число типа UInt8, равное 0 или 1.
Logical functions accept any numeric types, but return a UInt8 number equal to 0 or 1.
Ноль в качестве аргумента считается "ложью", а любое ненулевое значение - "истиной".
Zero as an argument is considered "false," while any non-zero value is considered "true"..
and, оператор AND
and, AND operator
~~~~~~~~~~~~~~~~~
or, оператор OR
or, OR operator
~~~~~~~~~~~~~~~
not, оператор NOT
~~~~~~~~~~~~~~~~~
not, NOT operator
~~~~~~~~~~~~~~~
xor
~~~
~~~~~~~~~~~~~~~
Математические функции
Mathematical functions
---------------
Все функции возвращают число типа Float64. Точность результата близка к максимально возможной, но результат может не совпадать с наиболее близким к соответствующему вещественному числу машинно представимым числом.
All the functions return a Float64 number. The accuracy of the result is close to the maximum precision possible, but the result might not coincide with the machine representable number nearest to the corresponding real number.
e()
~~~~
Принимает ноль аргументов, возвращает число типа Float64, близкое к числу e.
Accepts zero arguments and returns a Float64 number close to the e number.
pi()
~~~~
Принимает ноль аргументов, возвращает число типа Float64, близкое к числу π.
Accepts zero arguments and returns a Float64 number close to π.
exp(x)
~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к экспоненте от аргумента.
Accepts a numeric argument and returns a Float64 number close to the exponent of the argument.
log(x)
~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к натуральному логарифму от аргумента.
Accepts a numeric argument and returns a Float64 number close to the natural logarithm of the argument.
exp2(x)
~~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к 2x.
Accepts a numeric argument and returns a Float64 number close to 2x.
log2(x)
~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к двоичному логарифму от аргумента.
Accepts a numeric argument and returns a Float64 number close to the binary logarithm of the argument.
exp10(x)
~~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к 10x.
Accepts a numeric argument and returns a Float64 number close to 10x.
log10(x)
~~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к десятичному логарифму от аргумента.
Accepts a numeric argument and returns a Float64 number close to the decimal logarithm of the argument.
sqrt(x)
~~~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к квадратному корню от аргумента.
Accepts a numeric argument and returns a Float64 number close to the square root of the argument.
cbrt(x)
~~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к кубическому корню от аргумента.
Accepts a numeric argument and returns a Float64 number close to the cubic root of the argument.
erf(x)
~~~~~~~
Если x неотрицательно, то erf(x / σ√2) - вероятность того, что случайная величина, имеющая нормальное распределение со среднеквадратичным отклонением σ, принимает значение, отстоящее от мат. ожидания больше чем на x.
If 'x' is non-negative, then erf(x / σ√2) - is the probability that a random variable having a normal distribution with standard deviation 'σ' takes the value that is separated from the expected value by more than 'x'.
Пример (правило трёх сигм):
Example (three sigma rule):
.. code-block:: sql
......@@ -59,39 +59,39 @@ erf(x)
erfc(x)
~~~~~~
Принимает числовой аргумент, возвращает число типа Float64, близкое к 1 - erf(x), но без потери точности для больших x.
Accepts a numeric argument and returns a Float64 number close to 1 - erf(x), but without loss of precision for large 'x' values.
lgamma(x)
~~~~~~~
Логарифм от гамма функции.
The logarithm of the gamma function.
tgamma(x)
~~~~~~
Гамма функция.
Gamma function.
sin(x)
~~~~~
Синус.
The sine.
cos(x)
~~~~~
Косинус.
The cosine.
tan(x)
~~~~~~
Тангенс.
The tangent.
asin(x)
~~~~~~
Арксинус.
The arc sine
acos(x)
~~~~~~
Арккосинус.
The arc cosine.
atan(x)
~~~~~
Арктангенс.
The arc tangent.
pow(x, y)
~~~~~~~
......
Прочие функции
Other functions
-------------
hostName()
~~~~~~~
Возвращает строку - имя хоста, на котором эта функция была выполнена. При распределённой обработке запроса, это будет имя хоста удалённого сервера, если функция выполняется на удалённом сервере.
Returns a string with the name of the host that this function was performed on. For distributed processing, this is the name of the remote server host, if the function is performed on a remote server.
visibleWidth(x)
~~~~~~~~~
Вычисляет приблизительную ширину при выводе значения в текстовом (tab-separated) виде на консоль.
Функция используется системой для реализации Pretty форматов.
Calculates the approximate width when outputting values to the console in text format (tab-separated). This function is used by the system for implementing Pretty formats.
toTypeName(x)
~~~~~~~~
Возвращает строку, содержащую имя типа переданного аргумента.
Gets the type name. Returns a string containing the type name of the passed argument.
blockSize()
~~~~~~~~
Получить размер блока.
В ClickHouse выполнение запроса всегда идёт по блокам (наборам кусочков столбцов). Функция позволяет получить размер блока, для которого её вызвали.
Gets the size of the block.
In ClickHouse, queries are always run on blocks (sets of column parts). This function allows getting the size of the block that you called it for.
materialize(x)
~~~~~~~~
Превращает константу в полноценный столбец, содержащий только одно значение.
В ClickHouse полноценные столбцы и константы представлены в памяти по-разному. Функции по-разному работают для аргументов-констант и обычных аргументов (выполняется разный код), хотя результат почти всегда должен быть одинаковым. Эта функция предназначена для отладки такого поведения.
Turns a constant into a full column containing just one value.
In ClickHouse, full columns and constants are represented differently in memory. Functions work differently for constant arguments and normal arguments (different code is executed), although the result is almost always the same. This function is for debugging this behavior.
ignore(...)
~~~~~~~
Принимает любые аргументы, всегда возвращает 0.
При этом, аргумент всё равно вычисляется. Это может использоваться для бенчмарков.
A function that accepts any arguments and always returns 0.
However, the argument is still calculated. This can be used for benchmarks.
sleep(seconds)
~~~~~~~~~
Спит seconds секунд на каждый блок данных. Можно указать как целое число, так и число с плавающей запятой.
Sleeps 'seconds' seconds on each data block. You can specify an integer or a floating-point number.
currentDatabase()
~~~~~~~~~~
Возвращает имя текущей базы данных.
Эта функция может использоваться в параметрах движка таблицы в запросе CREATE TABLE там, где нужно указать базу данных.
Returns the name of the current database.
You can use this function in table engine parameters in a CREATE TABLE query where you need to specify the database..
isFinite(x)
~~~~~~~
Принимает Float32 или Float64 и возвращает UInt8, равный 1, если аргумент не бесконечный и не NaN, иначе 0.
Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is not infinite and not a NaN, otherwise 0.
isInfinite(x)
~~~~~~~
Принимает Float32 или Float64 и возвращает UInt8, равный 1, если аргумент бесконечный, иначе 0. Отметим, что в случае NaN возвращается 0.
Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is infinite, otherwise 0.
Note that 0 is returned for a NaN
isNaN(x)
~~~~~
Принимает Float32 или Float64 и возвращает UInt8, равный 1, если аргумент является NaN, иначе 0.
Accepts Float32 and Float64 and returns UInt8 equal to 1 if the argument is a NaN, otherwise 0.
hasColumnInTable('database', 'table', 'column')
~~~~~~~~
Принимает константные строки - имя базы данных, имя таблицы и название столбца. Возвращает константное выражение типа UInt8, равное 1,
если есть столбец, иначе 0.
Функция кидает исключение, если таблица не существует.
Для элементов вложенной структуры данных функция проверяет существование столбца. Для самой же вложенной структуры данных функция возвращает 0.
Accepts constant String columns - database name, table name and column name. Returns constant UInt8 value, equal to 1 if column exists,
otherwise 0.
If table doesn't exist than exception is thrown.
For elements of nested data structure function checks existence of column. For nested data structure 0 is returned.
bar
~~~~~
Позволяет построить unicode-art диаграмму.
Allows building a unicode-art diagram.
``bar(x, min, max, width)`` - рисует полосу ширины пропорциональной (x - min) и равной width символов при x == max.
``min, max`` - целочисленные константы, значение должно помещаться в Int64.
``width`` - константа, положительное число, может быть дробным.
``bar(x, min, max, width)`` - Draws a band with a width proportional to (x - min) and equal to 'width' characters when x == max.
``min, max`` - Integer constants. The value must fit in Int64.
``width`` - Constant, positive number, may be a fraction.
Полоса рисуется с точностью до одной восьмой символа.
Пример:
The band is drawn with accuracy to one eighth of a symbol. Example:
.. code-block:: sql
......@@ -108,32 +106,32 @@ bar
transform
~~~~~~~
Преобразовать значение согласно явно указанному отображению одних элементов на другие.
Имеется два варианта функции:
Transforms a value according to the explicitly defined mapping of some elements to other ones.
There are two variations of this function:
1. ``transform(x, array_from, array_to, default)``
``x`` - что преобразовывать.
``x`` - What to transform
``array_from`` - константный массив значений для преобразования.
``array_from`` - Constant array of values for converting.
``array_to`` - константный массив значений, в которые должны быть преобразованы значения из from.
``array_to`` - Constant array of values to convert the values in 'from' to.
``default`` - какое значение использовать, если x не равен ни одному из значений во from.
``default`` - Constant. Which value to use if 'x' is not equal to one of the values in 'from'
``array_from`` и ``array_to`` - массивы одинаковых размеров.
``'array_from'`` and ``'array_to'`` are arrays of the same size.
Типы:
Types:
``transform(T, Array(T), Array(U), U) -> U``
``T`` и ``U`` - могут быть числовыми, строковыми, или Date или DateTime типами.
При этом, где обозначена одна и та же буква (T или U), могут быть, в случае числовых типов, не совпадающие типы, а типы, для которых есть общий тип.
Например, первый аргумент может иметь тип Int64, а второй - Array(UInt16).
``'T'`` and ``'U'`` can be numeric, string, or Date or DateTime types.
Where the same letter is indicated (T or U), for numeric types these might not be matching types, but types that have a common type.
For example, the first argument can have the Int64 type, while the second has the Array(Uint16) type.
Если значение x равно одному из элементов массива array_from, то возвращает соответствующий (такой же по номеру) элемент массива array_to; иначе возвращает default. Если имеется несколько совпадающих элементов в array_from, то возвращает какой-нибудь из соответствующих.
If the 'x' value is equal to one of the elements in the 'array_from' array, it returns the existing element (that is numbered the same) from the 'array_to' array. Otherwise, it returns 'default'. If there are multiple matching elements in 'array_from', it returns one of the matches.
Пример:
Example:
.. code-block:: sql
......@@ -154,14 +152,14 @@ transform
2. ``transform(x, array_from, array_to)``
Отличается от первого варианта отсутствующим аргументом default.
Если значение x равно одному из элементов массива array_from, то возвращает соответствующий (такой же по номеру) элемент массива array_to; иначе возвращает x.
Differs from the first variation in that the 'default' argument is omitted.
If the 'x' value is equal to one of the elements in the 'array_from' array, it returns the matching element (that is numbered the same) from the 'array_to' array. Otherwise, it returns 'x'.
Типы:
Types:
``transform(T, Array(T), Array(T)) -> T``
Пример:
Example:
.. code-block:: sql
......@@ -188,9 +186,9 @@ transform
formatReadableSize(x)
~~~~~~~~~~~
Принимает размер (число байт). Возвращает округленный размер с суффиксом (KiB, MiB и т.д.) в виде строки.
Gets a size (number of bytes). Returns a string that contains rounded size with the suffix (KiB, MiB etc.).
Пример:
Example:
.. code-block:: sql
......@@ -207,33 +205,33 @@ formatReadableSize(x)
least(a, b)
~~~~~~
Возвращает наименьшее значение из a и b.
Returns the least element of a and b.
greatest(a, b)
~~~~~~~~
Возвращает наибольшее значение из a и b.
Returns the greatest element of a and b
uptime()
~~~~~~
Возвращает аптайм сервера в секундах.
Returns server's uptime in seconds.
version()
~~~~~~~
Возвращает версию сервера в виде строки.
Returns server's version as a string.
rowNumberInAllBlocks()
~~~~~~~~~~
Возвращает порядковый номер строки в блоке данных. Функция учитывает только задействованные блоки данных.
Returns an incremental row number within all blocks that were processed by this function.
runningDifference(x)
~~~~~~~~
Считает разницу между последовательными значениями строк в блоке данных.
Возвращает 0 для первой строки и разницу с предыдущей строкой для каждой последующей строки.
Calculates the difference between consecutive values in the data block.
Result of the function depends on the order of the data in the blocks.
Результат функции зависит от затронутых блоков данных и порядка данных в блоке.
Если сделать подзапрос с ORDER BY и вызывать функцию извне подзапроса, можно будет получить ожидаемый результат.
It works only inside of the each processed block of data. Data splitting in the blocks is not explicitly controlled by the user.
If you specify ORDER BY in subquery and call runningDifference outside of it, you could get an expected result.
Пример:
Example:
.. code-block:: sql
......
Функции генерации псевдослучайных чисел
Functions for generating pseudo-random numbers
----------------------
Используются некриптографические генераторы псевдослучайных чисел.
Non-cryptographic generators of pseudo-random numbers are used.
Все функции принимают ноль аргументов или один аргумент.
В случае, если передан аргумент - он может быть любого типа, и его значение никак не используется.
Этот аргумент нужен только для того, чтобы предотвратить склейку одинаковых выражений - чтобы две разные записи одной функции возвращали разные столбцы, с разными случайными числами.
All the functions accept zero arguments or one argument.
If an argument is passed, it can be any type, and its value is not used for anything.
The only purpose of this argument is to prevent common subexpression elimination, so that two different instances of the same function return different columns with different random numbers.
rand
~~~~
Возвращает псевдослучайное число типа UInt32, равномерно распределённое среди всех чисел типа UInt32.
Используется linear congruential generator.
Returns a pseudo-random UInt32 number, evenly distributed among all UInt32-type numbers.
Uses a linear congruential generator.
rand64
~~~~
Возвращает псевдослучайное число типа UInt64, равномерно распределённое среди всех чисел типа UInt64.
Используется linear congruential generator.
Returns a pseudo-random UInt64 number, evenly distributed among all UInt64-type numbers.
Uses a linear congruential generator.
Функции округления
Rounding functions
----------------
floor(x[, N])
~~~~~~~
Возвращает наибольшее круглое число, которое меньше или равно, чем x.
Круглым называется число, кратное 1 / 10N или ближайшее к нему число соответствующего типа данных, если 1 / 10N не представимо точно.
N - целочисленная константа, не обязательный параметр. По умолчанию - ноль, что означает - округлять до целого числа.
N может быть отрицательным.
Returns a rounder number that is less than or equal to 'x'.
A round number is a multiple of 1 / 10N, or the nearest number of the appropriate data type ``if 1 / 10N`` isn't exact.
'N' is an integer constant, optional parameter. By default it is zero, which means to round to an integer.
'N' may be negative.
Примеры: ``floor(123.45, 1) = 123.4, floor(123.45, -1) = 120.``
Examples: ``floor(123.45, 1) = 123.4, floor(123.45, -1) = 120``.
``x`` - любой числовой тип. Результат - число того же типа.
Для целочисленных аргументов имеет смысл округление с отрицательным значением N (для неотрицательных N, функция ничего не делает).
В случае переполнения при округлении (например, floor(-128, -1)), возвращается implementation specific результат.
'x' is any numeric type. The result is a number of the same type.
For integer arguments, it makes sense to round with a negative 'N' value (for non-negative 'N', the function doesn't do anything).
If rounding causes overflow (for example, ``floor(-128, -1))``, an implementation-specific result is returned.
ceil(x[, N])
~~~~~~
Возвращает наименьшее круглое число, которое больше или равно, чем x.
В остальном, аналогично функции floor, см. выше.
Returns the smallest round number that is greater than or equal to 'x'. In every other way, it is the same as the 'floor' function (see above)..
round(x[, N])
~~~~~~~
Возвращает ближайшее к num круглое число, которое может быть меньше или больше или равно x.
Если x находится посередине от ближайших круглых чисел, то возвращается какое-либо одно из них (implementation specific).
Число -0. может считаться или не считаться круглым (implementation specific).
В остальном, аналогично функциям floor и ceil, см. выше.
Returns the round number nearest to 'num', which may be less than, greater than, or equal to 'x'.
If 'x' is exactly in the middle between the nearest round numbers, one of them is returned (implementation-specific).
The number '-0.' may or may not be considered round (implementation-specific).
In every other way, this function is the same as 'floor' and 'ceil' described above.
roundToExp2(num)
~~~~~~~~
Принимает число. Если число меньше единицы - возвращает 0. Иначе округляет число вниз до ближайшей (целой неотрицательной) степени двух.
Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to the nearest (whole non-negative) degree of two.
roundDuration(num)
~~~~~~~~
Принимает число. Если число меньше единицы - возвращает 0. Иначе округляет число вниз до чисел из набора: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. Эта функция специфична для Яндекс.Метрики и предназначена для реализации отчёта по длительности визита.
Accepts a number. If the number is less than one, it returns 0. Otherwise, it rounds the number down to numbers from the set: 1, 10, 30, 60, 120, 180, 240, 300, 600, 1200, 1800, 3600, 7200, 18000, 36000. This function is specific to Yandex.Metrica and used for implementing the report on session length.
roundAge(num)
~~~~~~~
Принимает число. Если число меньше 18 - возвращает 0. Иначе округляет число вниз до чисел из набора: 18, 25, 35, 45. Эта функция специфична для Яндекс.Метрики и предназначена для реализации отчёта по возрасту посетителей.
Accepts a number. If the number is less than 18, it returns 0. Otherwise, it rounds the number down to numbers from the set: 18, 25, 35, 45. This function is specific to Yandex.Metrica and used for implementing the report on user age.
Функции разбиения и слияния строк и массивов
Functions for splitting and merging strings and arrays
----------------
splitByChar(separator, s)
~~~~~~~~~~~~
Разбивает строку на подстроки, используя в качестве разделителя separator.
separator должен быть константной строкой из ровно одного символа.
Возвращается массив выделенных подстрок. Могут выделяться пустые подстроки, если разделитель идёт в начале или в конце строки, или если идёт более одного разделителя подряд.
Splits a string into substrings, using 'separator' as the separator.
'separator' must be a string constant consisting of exactly one character.
Returns an array of selected substrings. Empty substrings may be selected if the separator occurs at the beginning or end of the string, or if there are multiple consecutive separators.
splitByString(separator, s)
~~~~~~~~~~~
То же самое, но использует строку из нескольких символов в качестве разделителя. Строка должна быть непустой.
The same as above, but it uses a string of multiple characters as the separator. The string must be non-empty.
arrayStringConcat(arr[, separator])
~~~~~~~~~~~~~
Склеивает строки, перечисленные в массиве, с разделителем separator.
separator - необязательный параметр, константная строка, по умолчанию равен пустой строке.
Возвращается строка.
Concatenates strings from the array elements, using 'separator' as the separator.
'separator' is a string constant, an optional parameter. By default it is an empty string.
Returns a string.
alphaTokens(s)
~~~~~~~~~~
Выделяет подстроки из подряд идущих байт из диапазонов a-z и A-Z.
Возвращается массив выделенных подстрок.
Selects substrings of consecutive bytes from the range a-z and A-Z.
Returns an array of selected substrings.
Функции для работы со строками
Functions for working with strings
------------------------------
empty
~~~~~
Возвращает 1 для пустой строки, и 0 для непустой строки.
Тип результата - UInt8.
Строка считается непустой, если содержит хотя бы один байт, пусть даже это пробел или нулевой байт.
Функция также работает для массивов.
Returns 1 for an empty string or 0 for a non-empty string.
The result type is UInt8.
A string is considered non-empty if it contains at least one byte, even if this is a space or a null byte.
The function also works for arrays.
notEmpty
~~~~~~~~
Возвращает 0 для пустой строки, и 1 для непустой строки.
Тип результата - UInt8.
Функция также работает для массивов.
Returns 0 for an empty string or 1 for a non-empty string.
The result type is UInt8.
The function also works for arrays.
length
~~~~~~
Возвращает длину строки в байтах (не символах, не кодовых точках).
Тип результата - UInt64.
Функция также работает для массивов.
Returns the length of a string in bytes (not in characters, and not in code points).
The result type is UInt64.
The function also works for arrays.
lengthUTF8
~~~~~~~~~~
Возвращает длину строки в кодовых точках Unicode (не символах), при допущении, что строка содержит набор байт, являющийся текстом в кодировке UTF-8. Если допущение не выполнено - то возвращает какой-нибудь результат (не кидает исключение).
Тип результата - UInt64.
Returns the length of a string in Unicode code points (not in characters), assuming that the string contains a set of bytes that make up UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
The result type is UInt64.
lower
~~~~~~
Переводит ASCII-символы латиницы в строке в нижний регистр.
Converts ASCII Latin symbols in a string to lowercase.
upper
~~~~~
Переводит ASCII-символы латиницы в строке в верхний регистр.
Converts ASCII Latin symbols in a string to uppercase.
lowerUTF8
~~~~~~~~~
Переводит строку в нижний регистр, при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8.
Не учитывает язык. То есть, для турецкого языка, результат может быть не совсем верным.
Если длина UTF-8 последовательности байт различна для верхнего и нижнего регистра кодовой точки, то для этой кодовой точки, результат работы может быть некорректным.
Если строка содержит набор байт, не являющийся UTF-8, то поведение не определено.
Converts a string to lowercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct.
If length of UTF-8 sequence is different for upper and lower case of code point, then result for that code point could be incorrect.
If value contains invalid UTF-8, the behavior is unspecified.
upperUTF8
~~~~~~~~~
Переводит строку в верхний регистр, при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8.
Не учитывает язык. То есть, для турецкого языка, результат может быть не совсем верным.
Если длина UTF-8 последовательности байт различна для верхнего и нижнего регистра кодовой точки, то для этой кодовой точки, результат работы может быть некорректным.
Если строка содержит набор байт, не являющийся UTF-8, то поведение не определено.
Converts a string to uppercase, assuming the string contains a set of bytes that make up a UTF-8 encoded text. It doesn't detect the language. So for Turkish the result might not be exactly correct.
If length of UTF-8 sequence is different for upper and lower case of code point, then result for that code point could be incorrect.
If value contains invalid UTF-8, the behavior is unspecified.
reverse
~~~~~~~
Разворачивает строку (как последовательность байт).
Reverses the string (as a sequence of bytes).
reverseUTF8
~~~~~~~~~~~
Разворачивает последовательность кодовых точек Unicode, при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8. Иначе - что-то делает (не кидает исключение).
Reverses a sequence of Unicode code points, assuming that the string contains a set of bytes representing a UTF-8 text. Otherwise, it does something else (it doesn't throw an exception).
concat(s1, s2, ...)
~~~~~~~~~~~~~~~~~~~
Склеивает строки, перечисленные в аргументах, без разделителей.
Concatenates strings from the function arguments, without a separator.
substring(s, offset, length)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Возвращает подстроку, начиная с байта по индексу offset, длины length байт. Индексация символов - начиная с единицы (как в стандартном SQL). Аргументы offset и length должны быть константами.
Returns a substring starting with the byte from the 'offset' index that is 'length' bytes long. Character indexing starts from one (as in standard SQL). The 'offset' and 'length' arguments must be constants.
substringUTF8(s, offset, length)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Так же, как substring, но для кодовых точек Unicode. Работает при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8. Если допущение не выполнено - то возвращает какой-нибудь результат (не кидает исключение).
The same as 'substring', but for Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
appendTrailingCharIfAbsent(s, c)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Если строка s непустая и не содержит символ c на конце, то добавляет символ c в конец.
If the ``s`` string is non-empty and does not contain the ``c`` character at the end, it appends the ``c`` character to the end.
convertCharset(s, from, to)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Возвращает сконвертированную из кодировки from в кодировку to строку s.
Returns a string with the data s (encoded as from charset) that was converted to the to charset.
Функции поиска и замены в строках
Functions for searching and replacing in strings
---------------------------------
replaceOne(haystack, pattern, replacement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Замена первого вхождения, если такое есть, подстроки pattern в haystack на подстроку replacement.
Здесь и далее, pattern и replacement должны быть константами.
Replaces the first occurrence, if it exists, of the 'pattern' substring in 'haystack' with the 'replacement' substring.
Hereafter, 'pattern' and 'replacement' must be constants.
replaceAll(haystack, pattern, replacement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Замена всех вхождений подстроки pattern в haystack на подстроку replacement.
Replaces all occurrences of the 'pattern' substring in 'haystack' with the 'replacement' substring.
replaceRegexpOne(haystack, pattern, replacement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Замена по регулярному выражению pattern. Регулярное выражение re2.
Заменяется только первое вхождение, если есть.
В качестве replacement может быть указан шаблон для замен. Этот шаблон может включать в себя подстановки ``\0-\9``.
Подстановка ``\0`` - вхождение регулярного выражения целиком. Подстановки ``\1-\9`` - соответствующие по номеру subpattern-ы.
Для указания символа ``\`` в шаблоне, он должен быть экранирован с помощью символа ``\``.
Также помните о том, что строковый литерал требует ещё одно экранирование.
Replacement using the 'pattern' regular expression. A re2 regular expression. Replaces only the first occurrence, if it exists.
A pattern can be specified as 'replacement'. This pattern can include substitutions \0-\9\.
The substitution \0 includes the entire regular expression.
The substitutions \1-\9 include the subpattern corresponding to the number.
In order to specify the \ symbol in a pattern, you must use a \ symbol to escape it.
Also keep in mind that a string literal requires an extra escape.
Пример 1. Переведём дату в американский формат:
Example 1. Converting the date to American format:
.. code-block:: sql
......@@ -38,7 +38,7 @@ replaceRegexpOne(haystack, pattern, replacement)
2014-03-22 03/22/2014
2014-03-23 03/23/2014
Пример 2. Размножить строку десять раз:
Example 2. Copy the string ten times:
.. code-block:: sql
......@@ -50,7 +50,7 @@ replaceRegexpOne(haystack, pattern, replacement)
replaceRegexpAll(haystack, pattern, replacement)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
То же самое, но делается замена всех вхождений. Пример:
This does the same thing, but replaces all the occurrences. Example:
.. code-block:: sql
SELECT replaceRegexpAll('Hello, World!', '.', '\\0\\0') AS res
......@@ -59,8 +59,8 @@ replaceRegexpAll(haystack, pattern, replacement)
│ HHeelllloo,, WWoorrlldd!! │
└────────────────────────────┘
В качестве исключения, если регулярное выражение сработало на пустой подстроке, то замена делается не более одного раза.
Пример:
As an exception, if a regular expression worked on an empty substring, the replacement is not made more than once.
Example:
.. code-block:: sql
SELECT replaceRegexpAll('Hello, World!', '^', 'here: ') AS res
......
Функции поиска в строках
Functions for searching strings
------------------------
Во всех функциях, поиск регистрозависимый.
Во всех функциях, подстрока для поиска или регулярное выражение, должно быть константой.
The search is case-sensitive in all these functions.
The search substring or regular expression must be a constant in all these functions.
position(haystack, needle)
~~~~~~~~~~~~~~~~~~~~~~~~~~
Поиск подстроки needle в строке haystack.
Возвращает позицию (в байтах) найденной подстроки, начиная с 1, или 0, если подстрока не найдена.
Есть также функция positionCaseInsensitive.
Searches for the 'needle' substring in the 'haystack' string.
Returns the position (in bytes) of the found substring, starting from 1, or returns 0 if the substring was not found.
There's also positionCaseInsensitive function.
positionUTF8(haystack, needle)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Так же, как position, но позиция возвращается в кодовых точках Unicode. Работает при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8. Если допущение не выполнено - то возвращает какой-нибудь результат (не кидает исключение).
Есть также функция positionCaseInsensitiveUTF8.
The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There's also positionCaseInsensitiveUTF8 function.
match(haystack, pattern)
~~~~~~~~~~~~~~~~~~~~~~~~
Проверка строки на соответствие регулярному выражению pattern. Регулярное выражение re2.
Возвращает 0 (если не соответствует) или 1 (если соответствует).
Checks whether the string matches the 'pattern' regular expression.
The regular expression is re2.
Returns 0 if it doesn't match, or 1 if it matches.
Обратите внимание, что для экранирования в регулярном выражении, используется символ ``\`` (обратный слеш). Этот же символ используется для экранирования в строковых литералах. Поэтому, чтобы экранировать символ в регулярном выражении, необходимо написать в строковом литерале \\ (два обратных слеша).
Note that the backslash symbol (``\``) is used for escaping in the regular expression. The same symbol is used for escaping in string literals.
So in order to escape the symbol in a regular expression, you must write two backslashes (``\\``) in a string literal.
Регулярное выражение работает со строкой как с набором байт. Регулярное выражение не может содержать нулевые байты.
Для шаблонов на поиск подстроки в строке, лучше используйте LIKE или position, так как они работают существенно быстрее.
The regular expression works with the string as if it is a set of bytes.
The regular expression can't contain null bytes.
For patterns to search for substrings in a string, it is better to use LIKE or 'position', since they work much faster.
extract(haystack, pattern)
~~~~~~~~~~~~~~~~~~~~~~~~~~
Извлечение фрагмента строки по регулярному выражению. Если haystack не соответствует регулярному выражению pattern, то возвращается пустая строка. Если регулярное выражение не содержит subpattern-ов, то вынимается фрагмент, который подпадает под всё регулярное выражение. Иначе вынимается фрагмент, который подпадает под первый subpattern.
Extracts a fragment of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. If the regex doesn't contain subpatterns, it takes the fragment that matches the entire regex. Otherwise, it takes the fragment that matches the first subpattern.
extractAll(haystack, pattern)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Извлечение всех фрагментов строки по регулярному выражению. Если haystack не соответствует регулярному выражению pattern, то возвращается пустая строка. Возвращается массив строк, состоящий из всех соответствий регулярному выражению. В остальном, поведение аналогично функции extract (по прежнему, вынимается первый subpattern, или всё выражение, если subpattern-а нет).
Extracts all the fragments of a string using a regular expression. If 'haystack' doesn't match the 'pattern' regex, an empty string is returned. Returns an array of strings consisting of all matches to the regex. In general, the behavior is the same as the 'extract' function (it takes the first subpattern, or the entire expression if there isn't a subpattern).
like(haystack, pattern), оператор haystack LIKE pattern
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Проверка строки на соответствие простому регулярному выражению.
Регулярное выражение может содержать метасимволы ``%`` и ``_``.
Checks whether a string matches a simple regular expression. The regular expression can contain the metasymbols ``%`` and ``_``.
``%`` обозначает любое количество любых байт (в том числе, нулевое количество символов).
``%`` indicates any quantity of any bytes (including zero characters).
``_`` обозначает один любой байт.
``_`` indicates any one byte.
Для экранирования метасимволов, используется символ ``\`` (обратный слеш). Смотрите замечание об экранировании в описании функции match.
Use the backslash (``\``) for escaping metasymbols. See the note on escaping in the description of the 'match' function.
Для регулярных выражений вида ``%needle%`` действует более оптимальный код, который работает также быстро, как функция ``position``.
Для остальных регулярных выражений, код аналогичен функции match.
For regular expressions like%needle%, the code is more optimal and works as fast as the 'position' function. For other regular expressions, the code is the same as for the 'match' function.
notLike(haystack, pattern), оператор haystack NOT LIKE pattern
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
То же, что like, но с отрицанием.
The same thing as 'like', but negative.
Функции преобразования типов
Type conversion functions
----------------------------
toUInt8, toUInt16, toUInt32, toUInt64
......@@ -18,26 +18,25 @@ toDate, toDateTime
toString
~~~~~~~~
Функции преобразования между числами, строками (но не фиксированными строками), датами и датами-с-временем.
Все эти функции принимают один аргумент.
Functions for converting between numbers, strings (but not fixed strings), dates, and dates with times. All these functions accept one argument.
При преобразовании в строку или из строки, производится форматирование или парсинг значения по тем же правилам, что и для формата TabSeparated (и почти всех остальных текстовых форматов). Если распарсить строку не удаётся - кидается исключение и выполнение запроса прерывается.
When converting to or from a string, the value is formatted or parsed using the same rules as for the TabSeparated format (and almost all other text formats). If the string can't be parsed, an exception is thrown and the request is canceled.
При преобразовании даты в число или наоборот, дате соответствует число дней от начала unix эпохи.
При преобразовании даты-с-временем в число или наоборот, дате-с-временем соответствует число секунд от начала unix эпохи.
When converting dates to numbers or vice versa, the date corresponds to the number of days since the beginning of the Unix epoch.
When converting dates with times to numbers or vice versa, the date with time corresponds to the number of seconds since the beginning of the Unix epoch.
Форматы даты и даты-с-временем для функций toDate/toDateTime определены следующим образом:
Formats of date and date with time for toDate/toDateTime functions are defined as follows:
::
YYYY-MM-DD
YYYY-MM-DD hh:mm:ss
В качестве исключения, если делается преобразование из числа типа UInt32, Int32, UInt64, Int64 в Date, и если число больше или равно 65536, то число рассматривается как unix timestamp (а не как число дней) и округляется до даты. Это позволяет поддержать распространённый случай, когда пишут toDate(unix_timestamp), что иначе было бы ошибкой и требовало бы написания более громоздкого toDate(toDateTime(unix_timestamp))
As an exception, if converting from UInt32, Int32, UInt64, or Int64 type numbers to Date, and if the number is greater than or equal to 65536, the number is interpreted as a Unix timestamp (and not as the number of days) and is rounded to the date. This allows support for the common occurrence of writing 'toDate(unix_timestamp)', which otherwise would be an error and would require writing the more cumbersome 'toDate(toDateTime(unix_timestamp))'.
Преобразование между датой и датой-с-временем производится естественным образом: добавлением нулевого времени или отбрасыванием времени.
Conversion between a date and date with time is performed the natural way: by adding a null time or dropping the time.
Преобразование между числовыми типами производится по тем же правилам, что и присваивание между разными числовыми типами в C++.
Conversion between numeric types uses the same rules as assignments between different numeric types in C++.
Дополнительно, функция toString от аргумента типа DateTime может принимать второй аргумент String - имя тайм-зоны. Пример: ``Asia/Yekaterinburg`` В этом случае, форматирование времени производится согласно указанной тайм-зоне.
To do transformations on DateTime in given time zone, pass second argument with time zone name:
.. code-block:: sql
......@@ -49,18 +48,23 @@ toString
│ 2016-06-15 00:11:21 │ 2016-06-15 02:11:21 │
└─────────────────────┴─────────────────────┘
Также смотрите функцию ``toUnixTimestamp``.
To format DateTime in given time zone:
::
toString(now(), 'Asia/Yekaterinburg')
To get unix timestamp for string with datetime in specified time zone:
::
toUnixTimestamp('2000-01-01 00:00:00', 'Asia/Yekaterinburg')
toFixedString(s, N)
~~~~~~~~~~~~~~~~~~~~
Преобразует аргумент типа String в тип FixedString(N) (строку фиксированной длины N). N должно быть константой.
Если строка имеет меньше байт, чем N, то она дополняется нулевыми байтами справа. Если строка имеет больше байт, чем N - кидается исключение.
Converts a String type argument to a FixedString(N) type (a string with fixed length N). N must be a constant. If the string has fewer bytes than N, it is passed with null bytes to the right. If the string has more bytes than N, an exception is thrown.
toStringCutToZero(s)
~~~~~~~~~~~~~~~~~~~~
Принимает аргумент типа String или FixedString. Возвращает String, вырезая содержимое строки до первого найденного нулевого байта.
Accepts a String or FixedString argument. Returns a String that is cut to a first null byte occurrence.
Пример:
Example:
.. code-block:: sql
......@@ -87,18 +91,18 @@ reinterpretAsFloat32, reinterpretAsFloat64
reinterpretAsDate, reinterpretAsDateTime
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Функции принимают строку и интерпретируют байты, расположенные в начале строки, как число в host order (little endian). Если строка имеет недостаточную длину, то функции работают так, как будто строка дополнена необходимым количеством нулевых байт. Если строка длиннее, чем нужно, то лишние байты игнорируются. Дата интерпретируется, как число дней с начала unix-эпохи, а дата-с-временем - как число секунд с начала unix-эпохи.
These functions accept a string and interpret the bytes placed at the beginning of the string as a number in host order (little endian). If the string isn't long enough, the functions work as if the string is padded with the necessary number of null bytes. If the string is longer than needed, the extra bytes are ignored. A date is interpreted as the number of days since the beginning of the Unix Epoch, and a date with time is interpreted as the number of seconds since the beginning of the Unix Epoch.
reinterpretAsString
~~~~~~~~~~~~~~~~~~~
Функция принимает число или дату или дату-с-временем и возвращает строку, содержащую байты, представляющие соответствующее значение в host order (little endian). При этом, отбрасываются нулевые байты с конца. Например, значение 255 типа UInt32 будет строкой длины 1 байт.
This function accepts a number or date or date with time, and returns a string containing bytes representing the corresponding value in host order (little endian). Null bytes are dropped from the end. For example, a UInt32 type value of 255 is a string that is one byte long.
CAST(x, t)
~~~~~~~~~~
Преобразует x в тип данных t.
Поддерживается также синтаксис CAST(x AS t).
Casts x to the t data type.
The syntax ``CAST(x AS t)`` is also supported.
Пример:
Example:
.. code-block:: sql
......@@ -113,4 +117,4 @@ CAST(x, t)
│ 2016-06-15 23:00:00 │ 2016-06-15 23:00:00 │ 2016-06-15 │ 2016-06-15 23:00:00 │ 2016-06-15 23:00:00\0\0\0 │
└─────────────────────┴─────────────────────┴────────────┴─────────────────────┴───────────────────────────┘
Преобразование в FixedString(N) работает только для аргументов типа String или FixedString(N).
Casting to FixedString(N) works only for String and FixedString(N).
Функции для работы с URL
Functions for working with URLs
------------------------
Все функции работают не по RFC - то есть, максимально упрощены ради производительности.
All these functions don't follow the RFC. They are maximally simplified for improved performance.
Функции, извлекающие часть URL-а.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Если в URL-е нет ничего похожего, то возвращается пустая строка.
If there isn't anything similar in a URL, an empty string is returned.
protocol
""""""""
Возвращает протокол. Примеры: http, ftp, mailto, magnet...
- Selects the protocol. Examples: http, ftp, mailto, magnet...
domain
"""""""
Возвращает домен.
- Selects the domain.
domainWithoutWWW
""""""""""""
Возвращает домен, удалив не более одного 'www.' с начала, если есть.
- Selects the domain and removes no more than one 'www.' from the beginning of it, if present.
topLevelDomain
"""""""""""
Возвращает домен верхнего уровня. Пример: .ru.
- Selects the top-level domain. Example: .ru.
firstSignificantSubdomain
""""""""""""""
Возвращает "первый существенный поддомен". Это понятие является нестандартным и специфично для Яндекс.Метрики. Первый существенный поддомен - это домен второго уровня, если он не равен одному из com, net, org, co, или домен третьего уровня, иначе. Например, firstSignificantSubdomain('https://news.yandex.ru/') = 'yandex', firstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex'. Список "несущественных" доменов второго уровня и другие детали реализации могут изменяться в будущем.
- Selects the "first significant subdomain". This is a non-standard concept specific to Yandex.Metrica. The first significant subdomain is a second-level domain if it is 'com', 'net', 'org', or 'co'. Otherwise, it is a third-level domain. For example, firstSignificantSubdomain('https://news.yandex.ru/') = 'yandex', firstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex'. The list of "insignificant" second-level domains and other implementation details may change in the future.
cutToFirstSignificantSubdomain
""""""""""""""""
Возвращает часть домена, включающую поддомены верхнего уровня до "первого существенного поддомена" (см. выше).
- Selects the part of the domain that includes top-level subdomains up to the "first significant subdomain" (see the explanation above).
Например, ``cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'``.
For example, ``cutToFirstSignificantSubdomain('https://news.yandex.com.tr/') = 'yandex.com.tr'``.
path
""""
Возвращает путь. Пример: ``/top/news.html`` Путь не включает в себя query string.
- Selects the path. Example: /top/news.html The path does not include the query-string.
pathFull
"""""""
То же самое, но включая query string и fragment. Пример: /top/news.html?page=2#comments
- The same as above, but including query-string and fragment. Example: /top/news.html?page=2#comments
queryString
"""""""""
Возвращает query-string. Пример: page=1&lr=213. query-string не включает в себя начальный знак вопроса, а также # и всё, что после #.
- Selects the query-string. Example: page=1&lr=213. query-string does not include the first question mark, or # and everything that comes after #.
fragment
""""""
Возвращает fragment identifier. fragment не включает в себя начальный символ решётки.
- Selects the fragment identifier. fragment does not include the first number sign (#).
queryStringAndFragment
"""""""""
Возвращает query string и fragment identifier. Пример: страница=1#29390.
- Selects the query-string and fragment identifier. Example: page=1#29390.
extractURLParameter(URL, name)
"""""""""
Возвращает значение параметра name в URL, если такой есть; или пустую строку, иначе; если параметров с таким именем много - вернуть первый попавшийся. Функция работает при допущении, что имя параметра закодировано в URL в точности таким же образом, что и в переданном аргументе.
- Selects the value of the 'name' parameter in the URL, if present. Otherwise, selects an empty string. If there are many parameters with this name, it returns the first occurrence. This function works under the assumption that the parameter name is encoded in the URL in exactly the same way as in the argument passed.
extractURLParameters(URL)
""""""""""
Возвращает массив строк вида name=value, соответствующих параметрам URL. Значения никак не декодируются.
- Gets an array of name=value strings corresponding to the URL parameters. The values are not decoded in any way.
extractURLParameterNames(URL)
""""""""
Возвращает массив строк вида name, соответствующих именам параметров URL. Значения никак не декодируются.
- Gets an array of name=value strings corresponding to the names of URL parameters. The values are not decoded in any way.
URLHierarchy(URL)
"""""""""
Возвращает массив, содержащий URL, обрезанный с конца по символам /, ? в пути и query-string. Подряд идущие символы-разделители считаются за один. Резка производится в позиции после всех подряд идущих символов-разделителей. Пример:
- Gets an array containing the URL trimmed to the ``/``, ``?`` characters in the path and query-string. Consecutive separator characters are counted as one. The cut is made in the position after all the consecutive separator characters. Example:
URLPathHierarchy(URL)
""""""""
То же самое, но без протокола и хоста в результате. Элемент / (корень) не включается. Пример:
Функция используется для реализации древовидных отчётов по URL в Яндекс.Метрике.
- The same thing, but without the protocol and host in the result. The / element (root) is not included. Example:
This function is used for implementing tree-view reports by URL in Yandex.Metrica.
::
URLPathHierarchy('https://example.com/browse/CONV-6788') =
[
......@@ -82,8 +82,8 @@ URLPathHierarchy(URL)
decodeURLComponent(URL)
"""""""""""
Возвращает декодированный URL.
Пример:
Returns a URL-decoded URL.
Example:
.. code-block:: sql
......@@ -93,26 +93,26 @@ decodeURLComponent(URL)
│ http://127.0.0.1:8123/?query=SELECT 1; │
└────────────────────────────────────────┘
Функции, удаляющие часть из URL-а.
Functions that remove part of a URL.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Если в URL-е нет ничего похожего, то URL остаётся без изменений.
If the URL doesn't have anything similar, the URL remains unchanged.
cutWWW
"""""
Удаляет не более одного 'www.' с начала домена URL-а, если есть.
Removes no more than one 'www.' from the beginning of the URL's domain, if present.
cutQueryString
""""""
Удаляет query string. Знак вопроса тоже удаляется.
Removes the query-string. The question mark is also removed..
cutFragment
""""""""
Удаляет fragment identifier. Символ решётки тоже удаляется.
Removes the fragment identifier. The number sign is also removed.
cutQueryStringAndFragment
""""""""""
Удаляет query string и fragment identifier. Знак вопроса и символ решётки тоже удаляются.
Removes the query-string and fragment identifier. The question mark and number sign are also removed.
cutURLParameter(URL, name)
""""""""""
Удаляет параметр URL с именем name, если такой есть. Функция работает при допущении, что имя параметра закодировано в URL в точности таким же образом, что и в переданном аргументе.
Removes the URL parameter named 'name', if present. This function works under the assumption that the parameter name is encoded in the URL exactly the same way as in the passed argument.
Функции для работы со словарями Яндекс.Метрики
Functions for working with Yandex.Metrica dictionaries
----------------
Чтобы указанные ниже функции работали, в конфиге сервера должны быть указаны пути и адреса для получения всех словарей Яндекс.Метрики. Словари загружаются при первом вызове любой из этих функций. Если справочники не удаётся загрузить - будет выкинуто исключение.
In order for the functions below to work, the server config must specify the paths and addresses for getting all the Yandex.Metrica dictionaries. The dictionaries are loaded at the first call of any of these functions. If the reference lists can't be loaded, an exception is thrown.
О том, как создать справочники, смотрите в разделе "Словари".
For information about creating reference lists, see the section "Dictionaries".
Множественные геобазы
Multiple geobases
~~~~~~~~~
ClickHouse поддерживает работу одновременно с несколькими альтернативными геобазами (иерархиями регионов), для того чтобы можно было поддержать разные точки зрения о принадлежности регионов странам.
ClickHouse supports working with multiple alternative geobases (regional hierarchies) simultaneously, in order to support various perspectives on which countries certain regions belong to.
В конфиге clickhouse-server указывается файл с иерархией регионов:
The 'clickhouse-server' config specifies the file with the regional hierarchy:
``<path_to_regions_hierarchy_file>/opt/geo/regions_hierarchy.txt</path_to_regions_hierarchy_file>``
Кроме указанного файла, рядом ищутся файлы, к имени которых (до расширения) добавлен символ _ и какой угодно суффикс.
Например, также найдётся файл ``/opt/geo/regions_hierarchy_ua.txt``, если такой есть.
Besides this file, it also searches for files nearby that have the _ symbol and any suffix appended to the name (before the file extension).
For example, it will also find the file ``/opt/geo/regions_hierarchy_ua.txt``, if present.
``ua`` называется ключом словаря. Для словаря без суффикса, ключ является пустой строкой.
``ua`` is called the dictionary key. For a dictionary without a suffix, the key is an empty string.
Все словари перезагружаются в рантайме (раз в количество секунд, заданное в конфигурационном параметре builtin_dictionaries_reload_interval, по умолчанию - раз в час), но перечень доступных словарей определяется один раз, при старте сервера.
All the dictionaries are re-loaded in runtime (once every certain number of seconds, as defined in the builtin_dictionaries_reload_interval config parameter, or once an hour by default). However, the list of available dictionaries is defined one time, when the server starts.
Во все функции по работе с регионами, в конце добавлен один необязательный аргумент - ключ словаря. Далее он обозначен как geobase.
Пример:
All functions for working with regions have an optional argument at the end - the dictionary key. It is indicated as the geobase.
Example:
::
regionToCountry(RegionID) - использует словарь по умолчанию: /opt/geo/regions_hierarchy.txt;
regionToCountry(RegionID, '') - использует словарь по умолчанию: /opt/geo/regions_hierarchy.txt;
regionToCountry(RegionID, 'ua') - использует словарь для ключа ua: /opt/geo/regions_hierarchy_ua.txt;
regionToCountry(RegionID) - Uses the default dictionary: /opt/geo/regions_hierarchy.txt
regionToCountry(RegionID, '') - Uses the default dictionary: /opt/geo/regions_hierarchy.txt
regionToCountry(RegionID, 'ua') - Uses the dictionary for the 'ua' key: /opt/geo/regions_hierarchy_ua.txt
regionToCity(id[, geobase])
~~~~~~~~
Принимает число типа UInt32 - идентификатор региона из геобазы Яндекса. Если регион является городом или входит в некоторый город, то возвращает идентификатор региона - соответствующего города. Иначе возвращает 0.
Accepts a UInt32 number - the region ID from the Yandex geobase. If this region is a city or part of a city, it returns the region ID for the appropriate city. Otherwise, returns 0.
regionToArea(id[, geobase])
~~~~~~~~
Переводит регион в область (тип в геобазе - 5). В остальном, аналогично функции regionToCity.
Converts a region to an area (type 5 in the geobase). In every other way, this function is the same as 'regionToCity'.
.. code-block:: sql
SELECT DISTINCT regionToName(regionToArea(toUInt32(number), 'ua'))
SELECT DISTINCT regionToName(regionToArea(toUInt32(number), 'ua'), 'en')
FROM system.numbers
LIMIT 15
┌─regionToName(regionToArea(toUInt32(number), \'ua\'))─┐
│ │
Москва и Московская область
Санкт-Петербург и Ленинградская область
Белгородская область
Ивановская область
Калужская область
Костромская область
Курская область
Липецкая область
Орловская область
Рязанская область
Смоленская область
Тамбовская область
Тверская область
Тульская область
└──────────────────────────────────────────────────────┘
┌─regionToName(regionToArea(toUInt32(number), \'ua\'), \'en\')─┐
Moscow and Moscow region
Saint-Petersburg and Leningradskaya oblast
Belgorod District
Ivanovo district
Kaluga District
Kostroma District
Kursk District
Lipetsk District
Orel District
Ryazhan District
Smolensk District
Tambov District
Tver District
Tula District
└──────────────────────────────────────────────────────────────
regionToDistrict(id[, geobase])
~~~~~~~~~
Переводит регион в федеральный округ (тип в геобазе - 4). В остальном, аналогично функции regionToCity.
Converts a region to a federal district (type 4 in the geobase). In every other way, this function is the same as 'regionToCity'.
.. code-block:: sql
SELECT DISTINCT regionToName(regionToDistrict(toUInt32(number), 'ua'))
SELECT DISTINCT regionToName(regionToDistrict(toUInt32(number), 'ua'), 'en')
FROM system.numbers
LIMIT 15
┌─regionToName(regionToDistrict(toUInt32(number), \'ua\'))─┐
│ │
Центральный федеральный округ
Северо-Западный федеральный округ
Южный федеральный округ
Северо-Кавказский федеральный округ
Приволжский федеральный округ
Уральский федеральный округ
Сибирский федеральный округ
Дальневосточный федеральный округ
Шотландия
Фарерские острова
Фламандский регион
Брюссельский столичный регион
Валлония
Федерация Боснии и Герцеговины
└──────────────────────────────────────────────────────────┘
┌─regionToName(regionToDistrict(toUInt32(number), \'ua\'), \'en\')─┐
Central
Northwest
South
North Kavkaz
Volga Region
Ural
Siberian
Far East
Scotland
Faroe Islands
Flemish Region
Brussels-Capital Region
Wallonia
Federation of Bosnia and Herzegovina
└──────────────────────────────────────────────────────────────────
regionToCountry(id[, geobase])
~~~~~~~~~
Переводит регион в страну. В остальном, аналогично функции regionToCity.
Пример: ``regionToCountry(toUInt32(213)) = 225`` - преобразовали Москву (213) в Россию (225).
Converts a region to a country. In every other way, this function is the same as 'regionToCity'.
Example: ``regionToCountry(toUInt32(213)) = 225`` converts ``Moscow (213)`` to ``Russia (225)``.
regionToContinent(id[, geobase])
~~~~~~~~~
Переводит регион в континент. В остальном, аналогично функции regionToCity.
Пример: ``regionToContinent(toUInt32(213)) = 10001`` - преобразовали Москву (213) в Евразию (10001).
Converts a region to a continent. In every other way, this function is the same as 'regionToCity'.
Example: ``regionToContinent(toUInt32(213)) = 10001`` converts Moscow (213) to Eurasia (10001).
regionToPopulation(id[, geobase])
~~~~~~~~
Получает население для региона.
Население может быть прописано в файлах с геобазой. Смотрите в разделе "Встроенные словари".
Если для региона не прописано население, возвращается 0.
В геобазе Яндекса, население может быть прописано для дочерних регионов, но не прописано для родительских.
Gets the population for a region.
The population can be recorded in files with the geobase. See the section "External dictionaries".
If the population is not recorded for the region, it returns 0.
In the Yandex geobase, the population might be recorded for child regions, but not for parent regions..
regionIn(lhs, rhs[, geobase])
~~~~~~~~~~
Проверяет принадлежность региона lhs региону rhs. Возвращает число типа UInt8, равное 1, если принадлежит и 0, если не принадлежит.
Отношение рефлексивное - любой регион принадлежит также самому себе.
Checks whether a 'lhs' region belongs to a 'rhs' region. Returns a UInt8 number equal to 1 if it belongs, or 0 if it doesn't belong.
The relationship is reflexive - any region also belongs to itself.
regionHierarchy(id[, geobase])
~~~~~~~~~
Принимает число типа UInt32 - идентификатор региона из геобазы Яндекса. Возвращает массив идентификаторов регионов, состоящий из переданного региона и всех родителей по цепочке.
Пример: ``regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]``.
ПAccepts a UInt32 number - the region ID from the Yandex geobase. Returns an array of region IDs consisting of the passed region and all parents along the chain.
Example: ``regionHierarchy(toUInt32(213)) = [213,1,3,225,10001,10000]``.
regionToName(id[, lang])
~~~~~~~~
Принимает число типа UInt32 - идентификатор региона из геобазы Яндекса. Вторым аргументом может быть передана строка - название языка. Поддерживаются языки ru, en, ua, uk, by, kz, tr. Если второй аргумент отсутствует - используется язык ru. Если язык не поддерживается - кидается исключение. Возвращает строку - название региона на соответствующем языке. Если региона с указанным идентификатором не существует - возвращается пустая строка.
Accepts a UInt32 number - the region ID from the Yandex geobase. A string with the name of the language can be passed as a second argument. Supported languages are: ru, en, ua, uk, by, kz, tr. If the second argument is omitted, the language 'ru' is used. If the language is not supported, an exception is thrown. Returns a string - the name of the region in the corresponding language. If the region with the specified ID doesn't exist, an empty string is returned.
``ua`` и ``uk`` обозначают одно и то же - украинский язык.
``ua`` and ``uk`` mean the same thing - Ukrainian.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册