diff --git a/docs/en/getting_started.rst b/docs/en/getting_started.rst index 95b76f9f0f1..c91fe20979a 100644 --- a/docs/en/getting_started.rst +++ b/docs/en/getting_started.rst @@ -1,103 +1,100 @@ -Начало работы +Getting started ============= -Системные требования +System requirements ----------------- -Система некроссплатформенная. Требуется ОС Linux Ubuntu не более старая, чем Precise (12.04); архитектура x86_64 с поддержкой набора инструкций SSE 4.2. -Для проверки наличия SSE 4.2, выполните: +This is not a cross-platform system. It requires Linux Ubuntu Precise (12.04) or newer, x86_64 architecture with SSE 4.2 instruction set. +To test for SSE 4.2 support, do: :: grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not supported" -Рекомендуется использовать Ubuntu Trusty или Ubuntu Xenial или Ubuntu Precise. -Терминал должен работать в кодировке UTF-8 (как по умолчанию в Ubuntu). +We recommend using Ubuntu Trusty or Ubuntu Xenial or Ubuntu Precise. +The terminal must use UTF-8 encoding (the default in Ubuntu). -Установка +Installation ----------------- -В целях тестирования и разработки, система может быть установлена на один сервер или на рабочий компьютер. +For testing and development, the system can be installed on a single server or on a desktop computer. -Установка из пакетов +Installing from packages ~~~~~~~~~~~~~~~~~~~~ -Пропишите в `/etc/apt/sources.list` (или в отдельный файл `/etc/apt/sources.list.d/clickhouse.list`) репозитории: +In `/etc/apt/sources.list` (or in a separate `/etc/apt/sources.list.d/clickhouse.list` file), add the repository: :: deb http://repo.yandex.ru/clickhouse/trusty stable main -На других версиях Ubuntu, замените `trusty` на `xenial` или `precise`. +For other Ubuntu versions, replace `trusty` to `xenial` or `precise`. -Затем выполните: +Then run: :: sudo apt-key adv --keyserver keyserver.ubuntu.com --recv E0C56BD4 # optional sudo apt-get update sudo apt-get install clickhouse-client clickhouse-server-common -Также можно скачать и установить пакеты вручную, отсюда: +You can also download and install packages manually from here: http://repo.yandex.ru/clickhouse/trusty/pool/main/c/clickhouse/, http://repo.yandex.ru/clickhouse/xenial/pool/main/c/clickhouse/, http://repo.yandex.ru/clickhouse/precise/pool/main/c/clickhouse/. -ClickHouse содержит настройки ограничения доступа. Они расположены в файле users.xml (рядом с config.xml). -По умолчанию, разрешён доступ отовсюду для пользователя default без пароля. См. секцию users/default/networks. -Подробнее смотрите в разделе "конфигурационные файлы". +ClickHouse contains access restriction settings. They are located in the 'users.xml' file (next to 'config.xml'). +By default, access is allowed from everywhere for the default user without a password. See 'user/default/networks'. For more information, see the section "Configuration files". -Установка из исходников +Installing from source ~~~~~~~~~~~~~~~~~~~~~~~ -Для сборки воспользуйтесь инструкцией: build.md +To build, follow the instructions in build.md (for Linux) or in build_osx.md (for Mac OS X). -Вы можете собрать пакеты и установить их. -Также вы можете использовать программы без установки пакетов. +You can compile packages and install them. You can also use programs without installing packages. :: - Клиент: dbms/src/Client/ - Сервер: dbms/src/Server/ + Client: dbms/src/Client/ + Server: dbms/src/Server/ -Для сервера создаёте директории с данными, например: +For the server, create a catalog with data, such as: :: /opt/clickhouse/data/default/ /opt/clickhouse/metadata/default/ -(Настраивается в конфиге сервера.) -Сделайте chown под нужного пользователя. +(Configured in the server config.) +Run 'chown' for the desired user. -Обратите внимание на путь к логам в конфиге сервера (src/dbms/src/Server/config.xml). +Note the path to logs in the server config (src/dbms/src/Server/config.xml). -Другие методы установки +Other methods of installation ~~~~~~~~~~~~~~~~~~~~~~~ -Docker образ: https://hub.docker.com/r/yandex/clickhouse-server/ +The Docker image is located here: https://hub.docker.com/r/yandex/clickhouse-server/ -Gentoo overlay: https://github.com/kmeaw/clickhouse-overlay +There is Gentoo overlay located here: https://github.com/kmeaw/clickhouse-overlay -Запуск +Launch ------- -Для запуска сервера (в качестве демона), выполните: +To start the server (as a daemon), run: :: sudo service clickhouse-server start -Смотрите логи в директории `/var/log/clickhouse-server/` +View the logs in the catalog `/var/log/clickhouse-server/` -Если сервер не стартует - проверьте правильность конфигурации в файле `/etc/clickhouse-server/config.xml` +If the server doesn't start, check the configurations in the file `/etc/clickhouse-server/config.xml` -Также можно запустить сервер из консоли: +You can also launch the server from the console: :: clickhouse-server --config-file=/etc/clickhouse-server/config.xml -При этом, лог будет выводиться в консоль - удобно для разработки. -Если конфигурационный файл лежит в текущей директории, то указывать параметр --config-file не требуется - по умолчанию будет использован файл ./config.xml +In this case, the log will be printed to the console, which is convenient during development. If the configuration file is in the current directory, you don't need to specify the '--config-file' parameter. By default, it uses './config.xml'. -Соединиться с сервером можно с помощью клиента командной строки: +You can use the command-line client to connect to the server: :: clickhouse-client -Параметры по умолчанию обозначают - соединяться с localhost:9000, от имени пользователя default без пароля. -Клиент может быть использован для соединения с удалённым сервером. Пример: +The default parameters indicate connecting with localhost:9000 on behalf of the user 'default' without a password. +The client can be used for connecting to a remote server. For example: :: clickhouse-client --host=example.com -Подробнее смотри раздел "Клиент командной строки". +For more information, see the section "Command-line client". -Проверим работоспособность системы: +Checking the system: :: milovidov@milovidov-Latitude-E6320:~/work/metrica/src/dbms/src/Client$ ./clickhouse-client ClickHouse client version 0.0.18749. @@ -116,18 +113,18 @@ Gentoo overlay: https://github.com/kmeaw/clickhouse-overlay :) -Поздравляю, система работает! +Congratulations, it works! -Тестовые данные +Test data --------------- -Если вы сотрудник Яндекса, вы можете воспользоваться тестовыми данными Яндекс.Метрики для изучения возможностей системы. -Как загрузить тестовые данные, написано здесь. +If you are Yandex employee, you can use Yandex.Metrica test data to explore the system's capabilities. You can find instructions for using the test data here. -Если вы внешний пользователь системы, вы можете воспользоваться использовать общедоступные данные, способы загрузки которых указаны здесь. +Otherwise, you could use one of available public datasets, described here. -Если возникли вопросы + +If you have questions --------------------- -Если вы являетесь сотрудником Яндекса, обращайтесь на внутреннюю рассылку по ClickHouse. -Вы можете подписаться на эту рассылку, чтобы получать анонсы, быть в курсе нововведений, а также видеть вопросы, которые возникают у других пользователей. +If you are Yandex employee, use internal ClickHouse maillist. +You can subscribe to this list to get announcements, information on new developments, and questions that other users have. -Иначе вы можете задавать вопросы на Stackoverflow или участвовать в обсуждениях на Google Groups. Также вы можете отправить приватное сообщение для разрабочиков по адресу clickhouse-feedback@yandex-team.com. +Otherwise, you could ask questions on Stack Overflow; discuss in Google Groups; or send private message to developers to address clickhouse-feedback@yandex-team.com. diff --git a/docs/en/index.rst b/docs/en/index.rst index e57be470a5d..6e8752ca6d3 100644 --- a/docs/en/index.rst +++ b/docs/en/index.rst @@ -1,5 +1,5 @@ -Документация +Documentation ----------------- .. toctree:: diff --git a/docs/en/interfaces/cli.rst b/docs/en/interfaces/cli.rst index 999a2552044..ff5b2d3f481 100644 --- a/docs/en/interfaces/cli.rst +++ b/docs/en/interfaces/cli.rst @@ -1,4 +1,4 @@ -Клиент командной строки +Command-line client ----------------------- Для работы из командной строки вы можете использовать clickhouse-client: :: @@ -10,46 +10,45 @@ :) SELECT 1 +The ``clickhouse-client`` program accepts the following parameters, which are all optional: -Программа ``clickhouse-client`` принимает следующие параметры, все из которых являются необязательными: +``--host, -h`` - server name, by defaul - localhost. +You can use either the name or the IPv4 or IPv6 address. -``--host, -h`` - имя сервера, по умолчанию - localhost. -Вы можете использовать как имя, так и IPv4 или IPv6 адрес. +``--port`` - The port to connect to, by default - 9000. +Note that the HTTP interface and the native interface use different ports. -``--port`` - порт, к которому соединяться, по умолчанию - 9000. -Замечу, что для HTTP и родного интерфейса используются разные порты. +``--user, -u`` - The username, by default - default. -``--user, -u`` - имя пользователя, по умолчанию - default. +``--password`` - The password, by default - empty string. -``--password`` - пароль, по умолчанию - пустая строка. +``--query, -q`` - Query to process when using non-interactive mode. -``--query, -q`` - запрос для выполнения, при использовании в неинтерактивном режиме. +``--database, -d`` - Select the current default database, by default - the current DB from the server settings (by default, the 'default' DB). -``--database, -d`` - выбрать текущую БД, по умолчанию - текущая БД из настроек сервера (по умолчанию - БД default). +``--multiline, -m`` - If specified, allow multiline queries (do not send request on Enter). -``--multiline, -m`` - если указано - разрешить многострочные запросы, не отправлять запрос по нажатию Enter. +``--multiquery, -n`` - If specified, allow processing multiple queries separated by semicolons. +Only works in non-interactive mode. -``--multiquery, -n`` - если указано - разрешить выполнять несколько запросов, разделённых точкой с запятой. -Работает только в неинтерактивном режиме. - -``--format, -f`` - использовать указанный формат по умолчанию для вывода результата. -``--vertical, -E`` - если указано, использовать формат Vertical по умолчанию для вывода результата. То же самое, что --format=Vertical. В этом формате каждое значение выводится на отдельной строке, что удобно для отображения широких таблиц. -``--time, -t`` - если указано, в неинтерактивном режиме вывести время выполнения запроса в stderr. -``--stacktrace`` - если указано, в случае исключения, выводить также его стек трейс. -``--config-file`` - имя конфигурационного файла, в котором есть дополнительные настройки или изменены умолчания для настроек, указанных выше. -По умолчанию, ищутся файлы в следующем порядке: +``--format, -f`` - Use the specified default format to output the result. +``--vertical, -E`` - If specified, use the Vertical format by default to output the result. This is the same as '--format=Vertical'. In this format, each value is printed on a separate line, which is helpful when displaying wide tables. +``--time, -t`` - If specified, print the query execution time to 'stderr' in non-interactive mode. +``--stacktrace`` - If specified, also prints the stack trace if an exception occurs. +``--config-file`` - Name of the configuration file that has additional settings or changed defaults for the settings listed above. +By default, files are searched for in this order: ./clickhouse-client.xml ~/./clickhouse-client/config.xml /etc/clickhouse-client/config.xml -Настройки берутся только из первого найденного файла. +Settings are only taken from the first file found. -Также вы можете указать любые настроки, которые будут использованы для обработки запросов. Например, clickhouse-client --max_threads=1. Подробнее см. раздел "Настройки". +You can also specify any settings that will be used for processing queries. For example, ``clickhouse-client --max_threads=1``. For more information, see the section "Settings". -Клиент может быть использован в интерактивном и неинтерактивном (batch) режиме. -Чтобы использовать batch режим, укажите параметр query, или отправьте данные в stdin (проверяется, что stdin - не терминал), или и то, и другое. -Аналогично HTTP интерфейсу, при использовании одновременно параметра query и отправке данных в stdin, запрос составляется из конкатенации параметра query, перевода строки, и данных в stdin. Это удобно для больших INSERT запросов. +The client can be used in interactive and non-interactive (batch) mode. +To use batch mode, specify the 'query' parameter, or send data to 'stdin' (it verifies that 'stdin' is not a terminal), or both. +Similar to the HTTP interface, when using the 'query' parameter and sending data to 'stdin', the request is a concatenation of the 'query' parameter, a line break, and the data in 'stdin'. This is convenient for large INSERT queries. -Примеры использования клиента для вставки данных: +Examples for insert data via clickhouse-client: :: echo -ne "1, 'some text', '2016-08-14 00:00:00'\n2, 'some more text', '2016-08-14 00:00:01'" | clickhouse-client --database=test --query="INSERT INTO test FORMAT CSV"; @@ -61,37 +60,34 @@ cat file.csv | clickhouse-client --database=test --query="INSERT INTO test FORMAT CSV"; -В batch режиме в качестве формата данных по умолчанию используется формат TabSeparated. Формат может быть указан в секции FORMAT запроса. +In batch mode, the default data format is TabSeparated. You can set the format in the FORMAT clause of the query. -По умолчанию, в batch режиме вы можете выполнить только один запрос. Чтобы выполнить несколько запросов из "скрипта", используйте параметр --multiquery. Это работает для всех запросов кроме INSERT. Результаты запросов выводятся подряд без дополнительных разделителей. -Также, при необходимости выполнить много запросов, вы можете запускать clickhouse-client на каждый запрос. Заметим, что запуск программы clickhouse-client может занимать десятки миллисекунд. +By default, you can only process a single query in batch mode. To make multiple queries from a "script," use the 'multiquery' parameter. This works for all queries except INSERT. Query results are output consecutively without additional separators. +Similarly, to process a large number of queries, you can run 'clickhouse-client' for each query. Note that it may take tens of milliseconds to launch the 'clickhouse-client' program. -В интерактивном режиме, вы получите командную строку, в которую можно вводить запросы. +In interactive mode, you get a command line where you can enter queries. -Если не указано multiline (по умолчанию): -Чтобы выполнить запрос, нажмите Enter. Точка с запятой на конце запроса не обязательна. Чтобы ввести запрос, состоящий из нескольких строк, перед переводом строки, введите символ обратного слеша: ``\`` - тогда после нажатия Enter, вам предложат ввести следующую строку запроса. +If 'multiline' is not specified (the default): +To run a query, press Enter. The semicolon is not necessary at the end of the query. To enter a multiline query, enter a backslash ``\`` before the line break - after you press Enter, you will be asked to enter the next line of the query. -Если указано multiline (многострочный режим): -Чтобы выполнить запрос, завершите его точкой с запятой и нажмите Enter. Если в конце введённой строки не было точки с запятой, то вам предложат ввести следующую строчку запроса. +If 'multiline' is specified: +To run a query, end it with a semicolon and press Enter. If the semicolon was omitted at the end of the entered line, you will be asked to enter the next line of the query. -Исполняется только один запрос, поэтому всё, что введено после точки с запятой, игнорируется. +You can specify ``\G`` instead of or after the semicolon. This indicates using Vertical format. In this format, each value is printed on a separate line, which is convenient for wide tables. This unusual feature was added for compatibility with the MySQL CLI. -Вместо или после точки с запятой может быть указано ``\G``. Это обозначает использование формата Vertical. В этом формате каждое значение выводится на отдельной строке, что удобно для широких таблиц. Столь необычная функциональность добавлена для совместимости с MySQL CLI. +The command line is based on 'readline' (and 'history') (or 'libedit', or even nothing, depending on build). In other words, it uses the familiar keyboard shortcuts and keeps a history. The history is written to /.clickhouse-client-history. -Командная строка сделана на основе readline (и history) (или libedit, или без какой-либо библиотеки, в зависимости от сборки) - то есть, в ней работают привычные сочетания клавиш, а также присутствует история. -История пишется в ~/.clickhouse-client-history. +By default, the format used is PrettyCompact. You can change the format in the FORMAT clause of the query, or by specifying '\G' at the end of the query, using the '--format' or '--vertical' argument in the command line, or using the client configuration file. -По умолчанию, в качестве формата, используется формат PrettyCompact (красивые таблички). Вы можете изменить формат с помощью секции FORMAT запроса, или с помощью указания `\G` на конце запроса, с помощью аргумента командной строки --format или --vertical, или с помощью конфигурационного файла клиента. - -Чтобы выйти из клиента, нажмите Ctrl+D (или Ctrl+C), или наберите вместо запроса одно из: +To exit the client, press Ctrl+D (or Ctrl+C), or enter one of the following : "exit", "quit", "logout", "учше", "йгше", "дщпщге", "exit;", "quit;", "logout;", "учшеж", "йгшеж", "дщпщгеж", "q", "й", "\q", "\Q", ":q", "\й", "\Й", "Жй" -При выполнении запроса, клиент показывает: - 1. Прогресс выполнение запроса, который обновляется не чаще, чем 10 раз в секунду (по умолчанию). При быстрых запросах, прогресс может не успеть отобразиться. - 2. Отформатированный запрос после его парсинга - для отладки. - 3. Результат в заданном формате. - 4. Количество строк результата, прошедшее время, а также среднюю скорость выполнения запроса. +When processing a query, the client shows: +#. Progress, which is updated no more than 10 times per second (by default). For quick queries, the progress might not have time to be displayed. +#. The formatted query after parsing, for debugging. +#. The result in the specified format. +#. The number of lines in the result, the time passed, and the average speed of query processing. -Вы можете прервать длинный запрос, нажав Ctrl+C. При этом вам всё равно придётся чуть-чуть подождать, пока сервер остановит запрос. На некоторых стадиях выполнения, запрос невозможно прервать. Если вы не дождётесь и нажмёте Ctrl+C второй раз, то клиент будет завершён. +To cancel a lengthy query, press Ctrl+C. However, you will still need to wait a little for the server to abort the request. It is not possible to cancel a query at certain stages. If you don't wait and press Ctrl+C a second time, the client will exit. -Клиент командной строки позволяет передать внешние данные (внешние временные таблицы) для использования запроса. Подробнее смотрите раздел "Внешние данные для обработки запроса" +The command-line client allows passing external data (external temporary tables) for querying. For more information, see the section "External data for request processing". diff --git a/docs/en/interfaces/http_interface.rst b/docs/en/interfaces/http_interface.rst index b097faddeab..016226f188c 100644 --- a/docs/en/interfaces/http_interface.rst +++ b/docs/en/interfaces/http_interface.rst @@ -1,24 +1,24 @@ -HTTP-интерфейс +HTTP interface ============== -HTTP интерфейс позволяет использовать ClickHouse на любой платформе, из любого языка программирования. У нас он используется для работы из Java и Perl, а также из shell-скриптов. В других отделах, HTTP интерфейс используется из Perl, Python и Go. HTTP интерфейс более ограничен по сравнению с родным интерфейсом, но является более совместимым. +The HTTP interface lets you use ClickHouse on any platform from any programming language. We use it for working from Java and Perl, as well as shell scripts. In other departments, the HTTP interface is used from Perl, Python, and Go. The HTTP interface is more limited than the native interface, but it has better compatibility. -По умолчанию, clickhouse-server слушает HTTP на порту 8123 (это можно изменить в конфиге). -Если запросить GET / без параметров, то вернётся строка "Ok." (с переводом строки на конце). Это может быть использовано в скриптах проверки живости. +By default, clickhouse-server listens for HTTP on port 8123 (this can be changed in the config). +If you make a GET / request without parameters, it returns the string "Ok" (with a line break at the end). You can use this in health-check scripts. .. code-block:: bash $ curl 'http://localhost:8123/' Ok. -Запрос отправляется в виде параметра URL query. Или POST-ом. Или начало запроса в параметре query, а продолжение POST-ом (зачем это нужно, будет объяснено ниже). Размер URL ограничен 16KB, это следует учитывать при отправке больших запросов. +Send the request as a URL 'query' parameter, or as a POST. Or send the beginning of the request in the 'query' parameter, and the rest in the POST (we'll explain later why this is necessary). URL length is limited by 16KB, this limit should be taken into account when sending long queries in the 'query' parameter. -В случае успеха, вам вернётся код ответа 200 и результат обработки запроса в теле ответа. -В случае ошибки, вам вернётся код ответа 500 и текст с описанием ошибки в теле ответа. +If successful, you receive the 200 response code and the result in the response body. +If an error occurs, you receive the 500 response code and an error description text in the response body. -При использовании метода GET, выставляется настройка readonly. То есть, для запросов, модифицирующие данные, можно использовать только метод POST. Сам запрос при этом можно отправлять как в теле POST-а, так и в параметре URL. +When using the GET method, 'readonly' is set. In other words, for queries that modify data, you can only use the POST method. You can send the query itself either in the POST body, or in the URL parameter. -Примеры: +Examples: .. code-block:: bash @@ -38,8 +38,7 @@ HTTP интерфейс позволяет использовать ClickHouse 1 -Как видно, curl немного неудобен тем, что надо URL-эскейпить пробелы. -wget сам всё эскейпит, но его не рекомендуется использовать, так как он плохо работает по HTTP 1.1 при использовании keep-alive и Transfer-Encoding: chunked. +As you can see, curl is not very convenient because spaces have to be URL-escaped. Although wget escapes everything on its own, we don't recommend it because it doesn't work well over HTTP 1.1 when using keep-alive and Transfer-Encoding: chunked. .. code-block:: bash @@ -52,8 +51,8 @@ wget сам всё эскейпит, но его не рекомендуется $ echo '1' | curl 'http://localhost:8123/?query=SELECT' --data-binary @- 1 -Если часть запроса отправляется в параметре, а часть POST-ом, то между этими двумя кусками данных ставится перевод строки. -Пример (так работать не будет): +If part of the query is sent in the parameter, and part in the POST, a line break is inserted between these two data parts. +Example (this won't work): .. code-block:: bash @@ -62,8 +61,8 @@ wget сам всё эскейпит, но его не рекомендуется ECT 1 , expected One of: SHOW TABLES, SHOW DATABASES, SELECT, INSERT, CREATE, ATTACH, RENAME, DROP, DETACH, USE, SET, OPTIMIZE., e.what() = DB::Exception -По умолчанию, данные возвращаются в формате TabSeparated (подробнее смотри раздел "Форматы"). -Можно попросить любой другой формат - с помощью секции FORMAT запроса. +By default, data is returned in TabSeparated format (for more information, see the "Formats" section). +You use the FORMAT clause of the query to request any other format. .. code-block:: bash @@ -74,40 +73,41 @@ wget сам всё эскейпит, но его не рекомендуется │ 1 │ └───┘ -Возможность передавать данные POST-ом нужна для INSERT-запросов. В этом случае вы можете написать начало запроса в параметре URL, а вставляемые данные передать POST-ом. Вставляемыми данными может быть, например, tab-separated дамп, полученный из MySQL. Таким образом, запрос INSERT заменяет LOAD DATA LOCAL INFILE из MySQL. +The POST method of transmitting data is necessary for INSERT queries. In this case, you can write the beginning of the query in the URL parameter, and use POST to pass the data to insert. The data to insert could be, for example, a tab-separated dump from MySQL. In this way, the INSERT query replaces LOAD DATA LOCAL INFILE from MySQL. -Примеры: -Создаём таблицу: +Examples: + +Creating a table: .. code-block:: bash echo 'CREATE TABLE t (a UInt8) ENGINE = Memory' | POST 'http://localhost:8123/' -Используем привычный запрос INSERT для вставки данных: +Using the familiar INSERT query for data insertion: .. code-block:: bash echo 'INSERT INTO t VALUES (1),(2),(3)' | POST 'http://localhost:8123/' -Данные можно отправить отдельно от запроса: +Data can be sent separately from the query: .. code-block:: bash echo '(4),(5),(6)' | POST 'http://localhost:8123/?query=INSERT INTO t VALUES' -Можно указать любой формат для данных. Формат Values - то же, что используется при записи INSERT INTO t VALUES: +You can specify any data format. The 'Values' format is the same as what is used when writing INSERT INTO t VALUES: .. code-block:: bash echo '(7),(8),(9)' | POST 'http://localhost:8123/?query=INSERT INTO t FORMAT Values' -Можно вставить данные из tab-separated дампа, указав соответствующий формат: +To insert data from a tab-separated dump, specify the corresponding format: .. code-block:: bash echo -ne '10\n11\n12\n' | POST 'http://localhost:8123/?query=INSERT INTO t FORMAT TabSeparated' -Прочитаем содержимое таблицы. Данные выводятся в произвольном порядке из-за параллельной обработки запроса: +Reading the table contents. Data is output in random order due to parallel query processing: .. code-block:: bash @@ -125,22 +125,22 @@ wget сам всё эскейпит, но его не рекомендуется 5 6 -Удаляем таблицу. +Deleting the table. .. code-block:: bash POST 'http://localhost:8123/?query=DROP TABLE t' -Для запросов, которые не возвращают таблицу с данными, в случае успеха, выдаётся пустое тело ответа. +For successful requests that don't return a data table, an empty response body is returned. -Вы можете использовать сжатие при передаче данных. Формат сжатых данных нестандартный, и вам придётся использовать для работы с ним специальную программу compressor (`sudo apt-get install compressor-metrika-yandex`). +You can use compression when transmitting data. The compressed data has a non-standard format, and you will need to use a special compressor program to work with it (`sudo apt-get install compressor-metrika-yandex`). -Если вы указали в URL compress=1, то сервер будет сжимать отправляемые вам данные. -Если вы указали в URL decompress=1, то сервер будет разжимать те данные, которые вы передаёте ему POST-ом. +If you specified 'compress=1' in the URL, the server will compress the data it sends you. +If you specified 'decompress=1' in the URL, the server will decompress the same data that you pass in the POST method. -Это может быть использовано для уменьшения трафика по сети при передаче большого количества данных, а также для создания сразу сжатых дампов. +You can use this to reduce network traffic when transmitting a large amount of data, or for creating dumps that are immediately compressed. -В параметре URL database может быть указана БД по умолчанию. +You can use the 'database' URL parameter to specify the default database. .. code-block:: bash @@ -156,23 +156,28 @@ wget сам всё эскейпит, но его не рекомендуется 8 9 -По умолчанию используется БД, которая прописана в настройках сервера, как БД по умолчанию. По умолчанию, это - БД default. Также вы всегда можете указать БД через точку перед именем таблицы. +By default, the database that is registered in the server settings is used as the default database. By default, this is the database called 'default'. Alternatively, you can always specify the database using a dot before the table name. -Имя пользователя и пароль могут быть указаны в одном из двух вариантов: +The username and password can be indicated in one of two ways: -1. С использованием HTTP Basic Authentification. Пример: :: +1. Using HTTP Basic Authentication. Example: :: echo 'SELECT 1' | curl 'http://user:password@localhost:8123/' -d @- -2. В параметрах URL user и password. Пример: :: +2. In the 'user' and 'password' URL parameters. Example: :: echo 'SELECT 1' | curl 'http://localhost:8123/?user=user&password=password' -d @- -Если имя пользователя не указано, то используется имя пользователя default. Если пароль не указан, то используется пустой пароль. -Также в параметрах URL вы можете указать любые настроки, которые будут использованы для обработки одного запроса, или целые профили настроек. Пример: +3. Using 'X-ClickHouse-User' and 'X-ClickHouse-Key' headers. Example: :: + + echo 'SELECT 1' | curl -H "X-ClickHouse-User: user" -H "X-ClickHouse-Key: password" 'http://localhost:8123/' -d @- + + +If the user name is not indicated, the username 'default' is used. If the password is not indicated, an empty password is used. +You can also use the URL parameters to specify any settings for processing a single query, or entire profiles of settings. Example: `http://localhost:8123/?profile=web&max_rows_to_read=1000000000&query=SELECT+1` -Подробнее см. раздел "Настройки". +For more information, see the section "Settings". .. code-block:: bash @@ -188,28 +193,12 @@ wget сам всё эскейпит, но его не рекомендуется 8 9 -Об остальных параметрах смотри раздел "SET". +For information about other parameters, see the section "SET". -В отличие от родного интерфейса, HTTP интерфейс не поддерживает понятие сессии и настройки в пределах сессии, не позволяет (вернее, позволяет лишь в некоторых случаях) прервать выполнение запроса, не показывает прогресс выполнения запроса. Парсинг и форматирование данных производится на стороне сервера и использование сети может быть неэффективным. -Может быть передан необязательный параметр query_id - идентификатор запроса, произвольная строка. Подробнее смотрите раздел "Настройки, replace_running_query". +In contrast to the native interface, the HTTP interface does not support the concept of sessions or session settings, does not allow aborting a query (to be exact, it allows this in only a few cases), and does not show the progress of query processing. Parsing and data formatting are performed on the server side, and using the network might be ineffective. -Может быть передан необязательный параметр quota_key - ключ квоты, произвольная строка. Подробнее смотрите раздел "Квоты". +The optional 'query_id' parameter can be passed as the query ID (any string). For more information, see the section "Settings, replace_running_query". -HTTP интерфейс позволяет передать внешние данные (внешние временные таблицы) для использования запроса. Подробнее смотрите раздел "Внешние данные для обработки запроса" +The optional 'quota_key' parameter can be passed as the quota key (any string). It can also be passed as 'X-ClickHouse-Quota' header. For more information, see the section "Quotas". -Буферизация ответа ------------------- - -Существует возможность включить буферизацию ответа на стороне сервера. Для этого предусмотрены параметры URL ``buffer_size`` и ``wait_end_of_query``. - -``buffer_size`` определяет количество байт результата которые будут буферизованы в памяти сервера. Если тело результата больше этого порога, то буфер будет переписан в HTTP канал, а оставшиеся данные будут отправляться в HTTP-канал напрямую. - -Чтобы гарантировать буферизацию всего ответа необходимо выставить ``wait_end_of_query=1``. В этом случае данные, не поместившиеся в памяти, будут буферизованы во временном файле сервера. - -Пример: - -.. code-block:: bash - - curl -sS 'http://localhost:8123/?max_result_bytes=4000000&buffer_size=3000000&wait_end_of_query=1' -d 'SELECT toUInt8(number) FROM system.numbers LIMIT 9000000 FORMAT RowBinary' - -Буферизация позволяет избежать ситуации когда код ответа и HTTP-заголовки были отправлены клиенту, после чего возникла ошибка выполнения запроса. В такой ситуации сообщение об ошибке записывается в конце тела ответа, и на стороне клиента ошибка может быть обнаружена только на этапе парсинга. \ No newline at end of file +The HTTP interface allows passing external data (external temporary tables) for querying. For more information, see the section "External data for query processing". diff --git a/docs/en/interfaces/index.rst b/docs/en/interfaces/index.rst index 036b200108e..e681fc3dffb 100644 --- a/docs/en/interfaces/index.rst +++ b/docs/en/interfaces/index.rst @@ -1,7 +1,7 @@ -Интерфейсы +Interfaces ========== -Для изучения возможностей системы, загрузки данных в таблицы, ручных запросов, используйте программу clickhouse-client. +To explore the system's capabilities, download data to tables, or make manual queries, use the clickhouse-client program. .. toctree:: :glob: diff --git a/docs/en/interfaces/jdbc.rst b/docs/en/interfaces/jdbc.rst index b3c1a86bfdb..57cbcb6fdfe 100644 --- a/docs/en/interfaces/jdbc.rst +++ b/docs/en/interfaces/jdbc.rst @@ -1,4 +1,4 @@ -JDBC-драйвер +JDBC driver ------------ -Для ClickHouse существует официальный JDBC драйвер. Смотрите `здесь `_ . +There is official JDBC driver for ClickHouse. See `here `_ . diff --git a/docs/en/interfaces/tcp.rst b/docs/en/interfaces/tcp.rst index 784beaf1522..be87c68d927 100644 --- a/docs/en/interfaces/tcp.rst +++ b/docs/en/interfaces/tcp.rst @@ -1,4 +1,4 @@ -Родной интерфейс (TCP) +Native interface (TCP) ---------------------- -Родной интерфейс используется в клиенте командной строки clickhouse-client, при межсерверном взаимодействии для распределённой обработки запроса, а также в программах на C++. Будет рассмотрен только клиент командной строки. +The native interface is used in the "clickhouse-client" command-line client for interaction between servers with distributed query processing, and also in C++ programs. We will only cover the command-line client. diff --git a/docs/en/interfaces/third-party_client_libraries.rst b/docs/en/interfaces/third-party_client_libraries.rst index 091c3850f27..4b7310948f3 100644 --- a/docs/en/interfaces/third-party_client_libraries.rst +++ b/docs/en/interfaces/third-party_client_libraries.rst @@ -1,7 +1,7 @@ -Библиотеки от сторонних разработчиков +Third-party client libraries -------------------------------------- -Существуют библиотеки для работы с ClickHouse для: +There exist third-party client libraries for ClickHouse: * Python: - `infi.clickhouse_orm `_ @@ -27,4 +27,4 @@ * .NET - `ClickHouse-Net `_ -Библиотеки не тестировались нами. Порядок перечисления произвольный. +Libraries was not tested by us. Ordering is arbitrary. diff --git a/docs/en/interfaces/third-party_gui.rst b/docs/en/interfaces/third-party_gui.rst index 842ad84c79b..f122ce8e904 100644 --- a/docs/en/interfaces/third-party_gui.rst +++ b/docs/en/interfaces/third-party_gui.rst @@ -1,4 +1,15 @@ -GUI от сторонних разработчиков +Third-party GUI ------------------------------ -Существует минималистичный веб-интерфейс для ClickHouse от `SMI2 `_. +There are `open source project Tabix `_ company of SMI2, which implements a graphical web interface for ClickHouse. + +Tabix key features: +- works with ClickHouse from the browser directly, without installing additional software; +- query editor that supports highlighting of SQL syntax ClickHouse, auto-completion for all objects, including dictionaries and context-sensitive help for built-in functions. +- graphs, charts and geo-referenced for mapping query results; +- interactive designer PivotTables (pivot) for query results; +- graphical tools for analysis ClickHouse; +- two color theme: light and dark. + + +`Tabix documentation `_ diff --git a/docs/en/introduction/distinctive_features.rst b/docs/en/introduction/distinctive_features.rst index 55e2eaca1d9..4ac206a3057 100644 --- a/docs/en/introduction/distinctive_features.rst +++ b/docs/en/introduction/distinctive_features.rst @@ -1,63 +1,62 @@ -Отличительные возможности ClickHouse +Distinctive features of ClickHouse =================================== -1. По-настоящему столбцовая СУБД. +1. True column-oriented DBMS. --------------------------------- -В по-настоящему столбцовой СУБД рядом со значениями не хранится никакого "мусора". Например, должны поддерживаться значения постоянной длины, чтобы не хранить рядом со значениями типа "число" их длины. Для примера, миллиард значений типа UInt8 должен действительно занимать в несжатом виде около 1GB, иначе это сильно ударит по эффективности использования CPU. Очень важно хранить данные компактно (без "мусора") в том числе в несжатом виде, так как скорость разжатия (использование CPU) зависит, в основном, от объёма несжатых данных. +In a true column-oriented DBMS, there isn't any "garbage" stored with the values. For example, constant-length values must be supported, to avoid storing their length "number" next to the values. As an example, a billion UInt8-type values should actually consume around 1 GB uncompressed, or this will strongly affect the CPU use. It is very important to store data compactly (without any "garbage") even when uncompressed, since the speed of decompression (CPU usage) depends mainly on the volume of uncompressed data. -Этот пункт пришлось выделить, так как существуют системы, которые могут хранить значения отдельных столбцов по отдельности, но не могут эффективно выполнять аналитические запросы в силу оптимизации под другой сценарий работы. Примеры: HBase, BigTable, Cassandra, HyperTable. В этих системах вы получите throughput в районе сотен тысяч строк в секунду, но не сотен миллионов строк в секунду. +This is worth noting because there are systems that can store values of separate columns separately, but that can't effectively process analytical queries due to their optimization for other scenarios. Example are HBase, BigTable, Cassandra, and HyperTable. In these systems, you will get throughput around a hundred thousand rows per second, but not hundreds of millions of rows per second. -Также стоит заметить, что ClickHouse является СУБД, а не одной базой данных. То есть, ClickHouse позволяет создавать таблицы и базы данных в runtime, загружать данные и выполнять запросы без переконфигурирования и перезапуска сервера. +Also note that ClickHouse is a DBMS, not a single database. ClickHouse allows creating tables and databases in runtime, loading data, and running queries without reconfiguring and restarting the server. -2. Сжатие данных. +2. Data compression. ----------------- -Некоторые столбцовые СУБД (InfiniDB CE, MonetDB) не используют сжатие данных. Но сжатие данных действительно серьёзно увеличивает производительность. +Some column-oriented DBMSs (InfiniDB CE and MonetDB) do not use data compression. However, data compression really improves performance. -3. Хранение данных на диске. +3. Disk storage of data. ---------------------------- -Многие столбцовые СУБД (SAP HANA, Google PowerDrill) могут работать только в оперативке. Но оперативки (даже на тысячах серверах) слишком мало для хранения всех хитов и визитов в Яндекс.Метрике. +Many column-oriented DBMSs (SAP HANA, and Google PowerDrill) can only work in RAM. But even on thousands of servers, the RAM is too small for storing all the pageviews and sessions in Yandex.Metrica. -4. Параллельная обработка запроса на многих процессорных ядрах. +4. Parallel processing on multiple cores. --------------------------------------------------------------- -Большие запросы естественным образом распараллеливаются. +Large queries are parallelized in a natural way. -5. Распределённая обработка запроса на многих серверах. +5. Distributed processing on multiple servers. ----------------------------------------------- -Почти все перечисленные ранее столбцовые СУБД не поддерживают распределённую обработку запроса. -В ClickHouse данные могут быть расположены на разных шардах. Каждый шард может представлять собой группу реплик, которые используются для отказоустойчивости. Запрос будет выполнен на всех шардах параллельно. Это делается прозрачно для пользователя. +Almost none of the columnar DBMSs listed above have support for distributed processing. +In ClickHouse, data can reside on different shards. Each shard can be a group of replicas that are used for fault tolerance. The query is processed on all the shards in parallel. This is transparent for the user. -6. Поддержка SQL. +6. SQL support. --------------- -Если вы знаете, что такое стандартный SQL, то говорить о поддержке SQL всё-таки нельзя. -Не поддерживаются NULL-ы. Все функции названы по-другому. -Тем не менее, это - декларативный язык запросов на основе SQL и во многих случаях не отличимый от SQL. -Поддерживаются JOIN-ы. Поддерживаются подзапросы в секциях FROM, IN, JOIN, а также скалярные подзапросы. -Зависимые подзапросы не поддерживаются. +If you are familiar with standard SQL, we can't really talk about SQL support. +NULLs are not supported. All the functions have different names. However, this is a declarative query language based on SQL that can't be differentiated from SQL in many instances. +JOINs are supported. Subqueries are supported in FROM, IN, JOIN clauses; and scalar subqueries. +Correlated subqueries are not supported. -7. Векторный движок. +7. Vector engine. ----------------- -Данные не только хранятся по столбцам, но и обрабатываются по векторам - кусочкам столбцов. За счёт этого достигается высокая эффективность по CPU. +Data is not only stored by columns, but is processed by vectors - parts of columns. This allows us to achieve high CPU performance. -8. Обновление данных в реальном времени. +8. Real-time data updates. ----------------------- -ClickHouse поддерживает таблицы с первичным ключом. Для того, чтобы можно было быстро выполнять запросы по диапазону первичного ключа, данные инкрементально сортируются с помощью merge дерева. За счёт этого, поддерживается постоянное добавление данных в таблицу. Блокировки при добавлении данных отсутствуют. +ClickHouse supports primary key tables. In order to quickly perform queries on the range of the primary key, the data is sorted incrementally using the merge tree. Due to this, data can continually be added to the table. There is no locking when adding data. -9. Наличие индексов. +9. Indexes. ----------------- -Наличие первичного ключа позволяет, например, вынимать данные для конкретных клиентов (счётчиков Метрики), для заданного диапазона времени, с низкими задержками - менее десятков миллисекунд. +Having a primary key allows, for example, extracting data for specific clients (Metrica counters) for a specific time range, with low latency less than several dozen milliseconds. -10. Подходит для онлайн запросов. +10. Suitable for online queries. ------------------ -Это позволяет использовать систему в качестве бэкенда для веб-интерфейса. Низкие задержки позволяют не откладывать выполнение запроса, а выполнять его в момент загрузки страницы интерфейса Яндекс.Метрики. То есть, в режиме онлайн. +This lets us use the system as the back-end for a web interface. Low latency means queries can be processed without delay, while the Yandex.Metrica interface page is loading (in online mode). -11. Поддержка приближённых вычислений. +11. Support for approximated calculations. ----------------- -#. Система содержит агрегатные функции для приближённого вычисления количества различных значений, медианы и квантилей. -#. Поддерживается возможность выполнить запрос на основе части (выборки) данных и получить приближённый результат. При этом, с диска будет считано пропорционально меньше данных. -#. Поддерживается возможность выполнить агрегацию не для всех ключей, а для ограниченного количества первых попавшихся ключей. При выполнении некоторых условий на распределение ключей в данных, это позволяет получить достаточно точный результат с использованием меньшего количества ресурсов. +#. The system contains aggregate functions for approximated calculation of the number of various values, medians, and quantiles. +#. Supports running a query based on a part (sample) of data and getting an approximated result. In this case, proportionally less data is retrieved from the disk. +#. Supports running an aggregation for a limited number of random keys, instead of for all keys. Under certain conditions for key distribution in the data, this provides a reasonably accurate result while using fewer resources. -14. Репликация данных, поддержка целостности данных на репликах. +14. Data replication and support for data integrity on replicas. ----------------- -Используется асинхронная multimaster репликация. После записи на любую доступную реплику, данные распространяются на все остальные реплики. Система поддерживает полную идентичность данных на разных репликах. Восстановление после сбоя осуществляется автоматически, а в сложных случаях - "по кнопке". -Подробнее смотрите раздел "Репликация данных". +Uses asynchronous multimaster replication. After being written to any available replica, data is distributed to all the remaining replicas. The system maintains identical data on different replicas. Data is restored automatically after a failure, or using a "button" for complex cases. +For more information, see the section "Data replication". diff --git a/docs/en/introduction/features.rst b/docs/en/introduction/features.rst index 2ad1b7e44e0..3f462ac7140 100644 --- a/docs/en/introduction/features.rst +++ b/docs/en/introduction/features.rst @@ -1,6 +1,6 @@ -Особенности ClickHouse, которые могут считаться недостатками +ClickHouse features that can be considered disadvantages ------------------------------------------------------------ -#. Отсутствие транзакций. -#. Необходимо, чтобы результат выполнения запроса, в случае агрегации, помещался в оперативку на одном сервере. Объём исходных данных для запроса, при этом, может быть сколь угодно большим. -#. Отсутствие полноценной реализации UPDATE/DELETE. +#. No transactions. +#. For aggregation, query results must fit in the RAM on a single server. However, the volume of source data for a query may be indefinitely large. +#. Lack of full-fledged UPDATE/DELETE implementation. diff --git a/docs/en/introduction/index.rst b/docs/en/introduction/index.rst index 3ed82c4e743..ead7d9e53f5 100644 --- a/docs/en/introduction/index.rst +++ b/docs/en/introduction/index.rst @@ -1,4 +1,4 @@ -Введение +Introduction ========= .. toctree:: diff --git a/docs/en/introduction/performance.rst b/docs/en/introduction/performance.rst index 24f635eb9a5..9340c3a72bf 100644 --- a/docs/en/introduction/performance.rst +++ b/docs/en/introduction/performance.rst @@ -1,21 +1,21 @@ -Производительность +Performance =================== -По результатам внутреннего тестирования, ClickHouse обладает наиболее высокой производительностью (как наиболее высоким throughput на длинных запросах, так и наиболее низкой latency на коротких запросах), при соответствующем сценарии работы, среди доступных для тестирования систем подобного класса. Результаты тестирования можно посмотреть на отдельной странице. +According to internal testing results, ClickHouse shows the best performance for comparable operating scenarios among systems of its class that were available for testing. This includes the highest throughput for long queries, and the lowest latency on short queries. Testing results are shown on this page. -Пропускная способность при обработке одного большого запроса +Throughput for a single large query ------------------------------- -Пропускную способность можно измерять в строчках в секунду и в мегабайтах в секунду. При условии, что данные помещаются в page cache, не слишком сложный запрос обрабатывается на современном железе со скоростью около 2-10 GB/sec. несжатых данных на одном сервере (в простейшем случае скорость может достигать 30 GB/sec). Если данные не помещаются в page cache, то скорость работы зависит от скорости дисковой подсистемы и коэффициента сжатия данных. Например, если дисковая подсистема позволяет читать данные со скоростью 400 MB/sec., а коэффициент сжатия данных составляет 3, то скорость будет около 1.2GB/sec. Для получения скорости в строчках в секунду, следует поделить скорость в байтах в секунду на суммарный размер используемых в запросе столбцов. Например, если вынимаются столбцы на 10 байт, то скорость будет в районе 100-200 млн. строчек в секунду. +Throughput can be measured in rows per second or in megabytes per second. If the data is placed in the page cache, a query that is not too complex is processed on modern hardware at a speed of approximately 2-10 GB/s of uncompressed data on a single server (for the simplest cases, the speed may reach 30 GB/s). If data is not placed in the page cache, the speed depends on the disk subsystem and the data compression rate. For example, if the disk subsystem allows reading data at 400 MB/s, and the data compression rate is 3, the speed will be around 1.2 GB/s. To get the speed in rows per second, divide the speed in bytes per second by the total size of the columns used in the query. For example, if 10 bytes of columns are extracted, the speed will be around 100-200 million rows per second. -При распределённой обработке запроса, скорость обработки запроса растёт почти линейно, но только при условии, что в результате агрегации или при сортировке получается не слишком большое множество строчек. +The processing speed increases almost linearly for distributed processing, but only if the number of rows resulting from aggregation or sorting is not too large. -Задержки при обработке коротких запросов. +Latency when processing short queries. -------------------- -Если запрос использует первичный ключ, и выбирает для обработки не слишком большое количество строчек (сотни тысяч), и использует не слишком большое количество столбцов, то вы можете рассчитывать на latency менее 50 миллисекунд (от единиц миллисекунд в лучшем случае), при условии, что данные помещаются в page cache. Иначе latency вычисляется из количества seek-ов. Если вы используйте вращающиеся диски, то на не слишком сильно нагруженной системе, latency вычисляется по формуле: seek time (10 мс.) * количество столбцов в запросе * количество кусков с данными. +If a query uses a primary key and does not select too many rows to process (hundreds of thousands), and does not use too many columns, we can expect less than 50 milliseconds of latency (single digits of milliseconds in the best case) if data is placed in the page cache. Otherwise, latency is calculated from the number of seeks. If you use rotating drives, for a system that is not overloaded, the latency is calculated by this formula: seek time (10 ms) * number of columns queried * number of data parts. -Пропускная способность при обработке большого количества коротких запросов. +Throughput when processing a large quantity of short queries. -------------------- -При тех же условиях, ClickHouse может обработать несколько сотен (до нескольких тысяч в лучшем случае) запросов в секунду на одном сервере. Так как такой сценарий работы не является типичным для аналитических СУБД, рекомендуется рассчитывать не более чем на 100 запросов в секунду. +Under the same conditions, ClickHouse can handle several hundred queries per second on a single server (up to several thousand in the best case). Since this scenario is not typical for analytical DBMSs, we recommend expecting a maximum of 100 queries per second. -Производительность при вставке данных. +Performance on data insertion. ------------------ -Данные рекомендуется вставлять пачками не менее 1000 строк или не более одного запроса в секунду. При вставке в таблицу типа MergeTree из tab-separated дампа, скорость вставки будет в районе 50-200 МБ/сек. Если вставляются строчки размером около 1 КБ, то скорость будет в районе 50 000 - 200 000 строчек в секунду. Если строчки маленькие - производительность в строчках в секунду будет выше (на данных БК - > 500 000 строк в секунду, на данных Graphite - > 1 000 000 строк в секунду). Для увеличения производительности, можно производить несколько запросов INSERT параллельно - при этом производительность растёт линейно. +We recommend inserting data in packets of at least 1000 rows, or no more than a single request per second. When inserting to a MergeTree table from a tab-separated dump, the insertion speed will be from 50 to 200 MB/s. If the inserted rows are around 1 Kb in size, the speed will be from 50,000 to 200,000 rows per second. If the rows are small, the performance will be higher in rows per second (on Yandex Banner System data -> 500,000 rows per second, on Graphite data -> 1,000,000 rows per second). To improve performance, you can make multiple INSERT queries in parallel, and performance will increase linearly. diff --git a/docs/en/introduction/possible_silly_questions.rst b/docs/en/introduction/possible_silly_questions.rst index 80f075ba501..fdf4bad0922 100644 --- a/docs/en/introduction/possible_silly_questions.rst +++ b/docs/en/introduction/possible_silly_questions.rst @@ -1,16 +1,19 @@ -Возможные глупые вопросы +Possible silly questions ----------------------- -1. Почему бы не использовать системы типа map-reduce? +1. Why not to use systems like map-reduce? """"""""""""""""""" -Системами типа map-reduce будем называть системы распределённых вычислений, в которых операция reduce сделана на основе распределённой сортировки. Таким образом, к ним относятся YAMR, Hadoop, YT. +Systems like map-reduce are distributed computing systems, where the reduce phase is performed using distributed sorting. +Regarding this aspect, map-reduce is similar to other systems like YAMR, Hadoop, YT. -Такие системы не подходят для онлайн запросов в силу слишком большой latency. То есть, не могут быть использованы в качестве бэкенда для веб-интерфейса. -Такие системы не подходят для обновления данных в реальном времени. -Распределённая сортировка не является оптимальным способом выполнения операции reduce, если результат выполнения операции и все промежуточные результаты, при их наличии, помещаются в оперативку на одном сервере, как обычно бывает в запросах, выполняющихся в режиме онлайн. В таком случае, оптимальным способом выполнения операции reduce является хэш-таблица. Частым способом оптимизации map-reduce задач является предагрегация (частичный reduce) с использованием хэш-таблицы в оперативке. Эта оптимизация делается пользователем в ручном режиме. -Распределённая сортировка является основной причиной тормозов при выполнении несложных map-reduce задач. +These systems are not suitable for online queries because of latency, So they can't be used in backend-level for web interface. +Systems like this also are not suitable for real-time updates. +Distributed sorting is not optimal solution for reduce operations, if the result of the operation and all intermediate results, shall they exist, fit in operational memory of a single server, as usually happens in case of online analytical queries. +In this case the optimal way to perform reduce operations is by using a hash-table. A common optimization method for map-reduce tasks is combine operation (partial reduce) which uses hash-tables in memory. This optimization is done by the user manually. +Distributed sorting is the main reason for long latencies of simple map-reduce jobs. -Системы типа map-reduce позволяют выполнять произвольный код на кластере. Но для OLAP задач лучше подходит декларативный язык запросов, который позволяет быстро проводить исследования. Для примера, для Hadoop существует Hive и Pig. Также смотрите Cloudera Impala, Shark (устаревший) для Spark а также Spark SQL, Presto, Apache Drill. Впрочем, производительность при выполнении таких задач является сильно неоптимальной по сравнению со специализированными системами, а сравнительно высокая latency не позволяет использовать эти системы в качестве бэкенда для веб-интерфейса. +Systems similar to map-reduce enable running any code on the cluster. But for OLAP use-cases declarative query languages are better suited as they allow to carry out investigations faster. For example, for Hadoop there are Hive and Pig. There are others: Cloudera Impala, Shark (deprecated) and Spark SQL for Spark, Presto, Apache Drill. +However, performance of such tasks is highly sub-optimal compared to the performance of specialized systems and relatively high latency does not allow the use of these systems as a backend for the web interface. -YT позволяет хранить группы столбцов по отдельности. Но YT нельзя назвать по-настоящему столбцовой системой, так как в системе отсутствуют типы данных постоянной длины (чтобы можно было эффективно хранить числа без "мусора"), а также за счёт отсутствия векторного движка. Задачи в YT выполняются с помощью произвольного кода в режиме streaming, то есть, не могут быть достаточно оптимизированы (до сотен миллионов строк в секунду на один сервер). В YT в 2014-2016 годах находится в разработке функциональность "динамических сортированных таблиц" с использованием Merge Tree, строгой типизацией значений и языком запросов типа SQL. Динамические сортированные таблицы не подходят для OLAP задач, так как данные в них хранятся по строкам. Разработка языка запросов в YT всё ещё находится в зачаточной стадии, что не позволяет ориентироваться на эту функциональность. Разработчики YT рассматривают динамические сортированные таблицы для применения в OLTP и Key-Value сценариях работы. +YT allows you to store separate groups of columns. But YT is not a truly columnar storage system, as the system has no fixed length data types (so you can efficiently store a number without "garbage"), and there is no vector engine. Tasks in YT are performed by arbitrary code in streaming mode, so can not be sufficiently optimized (up to hundreds of millions of lines per second per server). In 2014-2016 YT is to develop "dynamic table sorting" functionality using Merge Tree, strongly typed values ​​and SQL-like language support. Dynamically sorted tables are not suited for OLAP tasks, since the data is stored in rows. Query language development in YT is still in incubating phase, which does not allow it to focus on this functionality. YT developers are considering dynamically sorted tables for use in OLTP and Key-Value scenarios. diff --git a/docs/en/introduction/use_case.rst b/docs/en/introduction/use_case.rst index 94c11fb9c85..a7bbf51cc5f 100644 --- a/docs/en/introduction/use_case.rst +++ b/docs/en/introduction/use_case.rst @@ -1,14 +1,13 @@ -Использование в Яндекс.Метрике и других отделах Яндекса +Usage in Yandex.Metrica and other Yandex services ------------------------------------------ -В Яндекс.Метрике ClickHouse используется для нескольких задач. -Основная задача - построение отчётов в режиме онлайн по неагрегированным данным. Для решения этой задачи используется кластер из 374 серверов, хранящий более 20,3 триллионов строк в базе данных. Объём сжатых данных, без учёта дублирования и репликации, составляет около 2 ПБ. Объём несжатых данных (в формате tsv) составил бы, приблизительно, 17 ПБ. +ClickHouse is used for multiple purposes in Yandex.Metrica. Its main task is to build reports in online mode using non-aggregated data. It uses a cluster of 374 servers, which store over 20.3 trillion rows in the database. The volume of compressed data, without counting duplication and replication, is about 2 PB. The volume of uncompressed data (in TSV format) would be approximately 17 PB. -Также ClickHouse используется: - * для хранения данных Вебвизора; - * для обработки промежуточных данных; - * для построения глобальных отчётов Аналитиками; - * для выполнения запросов в целях отладки движка Метрики; - * для анализа логов работы API и пользовательского интерфейса. +ClickHouse is also used for: + * Storing WebVisor data. + * Processing intermediate data. + * Building global reports with Analytics. + * Running queries for debugging the Metrica engine. + * Analyzing logs from the API and the user interface. -ClickHouse имеет более десятка инсталляций в других отделах Яндекса: в Вертикальных сервисах, Маркете, Директе, БК, Бизнес аналитике, Мобильной разработке, AdFox, Персональных сервисах и т п. +ClickHouse has at least a dozen installations in other Yandex services: in search verticals, Market, Direct, business analytics, mobile development, AdFox, personal services, and others. diff --git a/docs/en/introduction/what_is_clickhouse.rst b/docs/en/introduction/what_is_clickhouse.rst index 46b8187e6db..06d4857e1d7 100644 --- a/docs/en/introduction/what_is_clickhouse.rst +++ b/docs/en/introduction/what_is_clickhouse.rst @@ -1,18 +1,17 @@ -Что такое ClickHouse +What is ClickHouse? ==================== -ClickHouse - столбцовая СУБД для OLAP (Columnar DBMS). +ClickHouse is a columnar DBMS for OLAP. -В обычной, "строковой" СУБД, данные хранятся в таком порядке: +In a "normal" row-oriented DBMS, data is stored in this order: :: - 5123456789123456789 1 Евробаскет - Греция - Босния и Герцеговина - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0 - 5234985259563631958 0 Консалтинг, налогообложение, бухгалтерский учет, право 1 2011-09-01 01:03:02 6320881 2111222333 213 6458937489576391093 0 3 2 http://www.example.ru/ 0 800 600 16 10 2 153.1 0 0 10 63 1 1 0 0 2111678 000 0 588 368 240 2011-09-01 01:03:17 4 0 60310 0 windows-1251 1466 0 000 778899001 0 0 0 0 0 + 5123456789123456789 1 Eurobasket - Greece - Bosnia and Herzegovina - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0 + 5234985259563631958 0 Consulting, Tax assessment, Accounting, Law 1 2011-09-01 01:03:02 6320881 2111222333 213 6458937489576391093 0 3 2 http://www.example.ru/ 0 800 600 16 10 2 153.1 0 0 10 63 1 1 0 0 2111678 000 0 588 368 240 2011-09-01 01:03:17 4 0 60310 0 windows-1251 1466 0 000 778899001 0 0 0 0 0 ... -То есть, значения, относящиеся к одной строке, хранятся рядом. -Примеры строковых СУБД: MySQL, Postgres, MS SQL Server и т. п. +In other words, all the values related to a row are stored next to each other. Examples of a row-oriented DBMS are MySQL, Postgres, MS SQL Server, and others. -В столбцовых СУБД, данные хранятся в таком порядке: +In a column-oriented DBMS, data is stored like this: :: WatchID: 5385521489354350662 5385521490329509958 5385521489953706054 5385521490476781638 5385521490583269446 5385521490218868806 5385521491437850694 5385521491090174022 5385521490792669254 5385521490420695110 5385521491532181574 5385521491559694406 5385521491459625030 5385521492275175494 5385521492781318214 5385521492710027334 5385521492955615302 5385521493708759110 5385521494506434630 5385521493104611398 JavaEnable: 1 0 1 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1 @@ -20,44 +19,43 @@ ClickHouse - столбцовая СУБД для OLAP (Columnar DBMS). GoodEvent: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 EventTime: 2016-05-18 05:19:20 2016-05-18 08:10:20 2016-05-18 07:38:00 2016-05-18 01:13:08 2016-05-18 00:04:06 2016-05-18 04:21:30 2016-05-18 00:34:16 2016-05-18 07:35:49 2016-05-18 11:41:59 2016-05-18 01:13:32 -В примерах изображён только порядок расположения данных. -То есть, значения из разных столбцов хранятся отдельно, а данные одного столбца - вместе. +These examples only show the order that data is arranged in. +The values from different columns are stored separately, and data from the same column is stored together. +Examples of a column-oriented DBMS: ``Vertica``, ``Paraccel (Actian Matrix) (Amazon Redshift)``, ``Sybase IQ``, ``Exasol``, ``Infobright``, ``InfiniDB``, ``MonetDB (VectorWise) (Actian Vector)``, ``LucidDB``, ``SAP HANA``, ``Google Dremel``, ``Google PowerDrill``, ``Druid``, ``kdb+`` и т. п. -Примеры столбцовых СУБД: ``Vertica``, ``Paraccel (Actian Matrix) (Amazon Redshift)``, ``Sybase IQ``, ``Exasol``, ``Infobright``, ``InfiniDB``, ``MonetDB (VectorWise) (Actian Vector)``, ``LucidDB``, ``SAP HANA``, ``Google Dremel``, ``Google PowerDrill``, ``Druid``, ``kdb+`` и т. п. +Different orders for storing data are better suited to different scenarios. +The data access scenario refers to what queries are made, how often, and in what proportion; how much data is read for each type of query - rows, columns, and bytes; the relationship between reading and updating data; the working size of the data and how locally it is used; whether transactions are used, and how isolated they are; requirements for data replication and logical integrity; requirements for latency and throughput for each type of query, and so on. -Разный порядок хранения данных лучше подходит для разных сценариев работы. -Сценарий работы с данными - это то, какие производятся запросы, как часто и в каком соотношении; сколько читается данных на запросы каждого вида - строк, столбцов, байт; как соотносятся чтения и обновления данных; какой рабочий размер данных и насколько локально он используется; используются ли транзакции и с какой изолированностью; какие требования к дублированию данных и логической целостности; требования к задержкам на выполнение и пропускной способности запросов каждого вида и т. п. +The higher the load on the system, the more important it is to customize the system to the scenario, and the more specific this customization becomes. There is no system that is equally well-suited to significantly different scenarios. If a system is adaptable to a wide set of scenarios, under a high load, the system will handle all the scenarios equally poorly, or will work well for just one of the scenarios. -Чем больше нагрузка на систему, тем более важной становится специализация под сценарий работы, и тем более конкретной становится эта специализация. Не существует системы, одинаково хорошо подходящей под существенно различные сценарии работы. Если система подходит под широкое множество сценариев работы, то при достаточно большой нагрузке, система будет справляться со всеми сценариями работы плохо, или справляться хорошо только с одним из сценариев работы. +We'll say that the following is true for the OLAP (online analytical processing) scenario: -Будем говорить, что OLAP (онлайн обработка аналитических запросов) сценарий работы - это: +* The vast majority of requests are for read access. +* Data is updated in fairly large batches (> 1000 rows), not by single rows; or it is not updated at all. +* Data is added to the DB but is not modified. +* For reads, quite a large number of rows are extracted from the DB, but only a small subset of columns. +* Tables are "wide," meaning they contain a large number of columns. +* Queries are relatively rare (usually hundreds of queries per server or less per second). +* For simple queries, latencies around 50 ms are allowed. +* Column values are fairly small - numbers and short strings (for example, 60 bytes per URL). +* Requires high throughput when processing a single query (up to billions of rows per second per server). +* There are no transactions. +* Low requirements for data consistency. +* There is one large table per query. All tables are small, except for one. +* A query result is significantly smaller than the source data. That is, data is filtered or aggregated. The result fits in a single server's RAM. -* подавляющее большинство запросов - на чтение; -* данные обновляются достаточно большими пачками (> 1000 строк), а не по одной строке, или не обновляются вообще; -* данные добавляются в БД, но не изменяются; -* при чтении, вынимается достаточно большое количество строк из БД, но только небольшое подмножество столбцов; -* таблицы являются "широкими", то есть, содержат большое количество столбцов; -* запросы идут сравнительно редко (обычно не более сотни в секунду на сервер); -* при выполнении простых запросов, допустимы задержки в районе 50 мс; -* значения в столбцах достаточно мелкие - числа и небольшие строки (пример - 60 байт на URL); -* требуется высокая пропускная способность при обработке одного запроса (до миллиардов строк в секунду на один сервер); -* транзакции отсутствуют; -* низкие требования к консистентности данных; -* в запросе одна большая таблица, все таблицы кроме одной маленькие; -* результат выполнения запроса существенно меньше исходных данных - то есть, данные фильтруются или агрегируются; результат выполнения помещается в оперативку на одном сервере; +It is easy to see that the OLAP scenario is very different from other popular scenarios (such as OLTP or Key-Value access). So it doesn't make sense to try to use OLTP or a Key-Value DB for processing analytical queries if you want to get decent performance. For example, if you try to use MongoDB or Elliptics for analytics, you will get very poor performance compared to OLAP databases. -Легко видеть, что OLAP сценарий работы существенно отличается от других распространённых сценариев работы (например, OLTP или Key-Value сценариев работы). Таким образом, не имеет никакого смысла пытаться использовать OLTP или Key-Value БД для обработки аналитических запросов, если вы хотите получить приличную производительность ("выше плинтуса"). Например, если вы попытаетесь использовать для аналитики MongoDB или Elliptics - вы получите анекдотически низкую производительность по сравнению с OLAP-СУБД. +Columnar-oriented databases are better suited to OLAP scenarios (at least 100 times better in processing speed for most queries), for the following reasons: -Столбцовые СУБД лучше (от 100 раз по скорости обработки большинства запросов) подходят для OLAP сценария работы по следующим причинам: +1. For I/O. +1.1. For an analytical query, only a small number of table columns need to be read. In a column-oriented database, you can read just the data you need. For example, if you need 5 columns out of 100, you can expect a 20-fold reduction in I/O. +1.2. Since data is read in packets, it is easier to compress. Data in columns is also easier to compress. This further reduces the I/O volume. +1.3. Due to the reduced I/O, more data fits in the system cache. -1. По I/O. -1.1. Для выполнения аналитического запроса, требуется прочитать небольшое количество столбцов таблицы. В столбцовой БД для этого можно читать только нужные данные. Например, если вам требуется только 5 столбцов из 100, то следует рассчитывать на 20-кратное уменьшение ввода-вывода. -1.2. Так как данные читаются пачками, то их проще сжимать. Данные, лежащие по столбцам также лучше сжимаются. За счёт этого, дополнительно уменьшается объём ввода-вывода. -1.3. За счёт уменьшения ввода-вывода, больше данных влезает в системный кэш. +For example, the query "count the number of records for each advertising platform" requires reading one "advertising platform ID" column, which takes up 1 byte uncompressed. If most of the traffic was not from advertising platforms, you can expect at least 10-fold compression of this column. When using a quick compression algorithm, data decompression is possible at a speed of at least several gigabytes of uncompressed data per second. In other words, this query can be processed at a speed of approximately several billion rows per second on a single server. This speed is actually achieved in practice. -Для примера, для запроса "посчитать количество записей для каждой рекламной системы", требуется прочитать один столбец "идентификатор рекламной системы", который занимает 1 байт в несжатом виде. Если большинство переходов было не с рекламных систем, то можно рассчитывать хотя бы на десятикратное сжатие этого столбца. При использовании быстрого алгоритма сжатия, возможно разжатие данных со скоростью более нескольких гигабайт несжатых данных в секунду. То есть, такой запрос может выполняться со скоростью около нескольких миллиардов строк в секунду на одном сервере. На практике, такая скорость действительно достигается. - -Пример: +Example: :: milovidov@████████.yandex.ru:~$ clickhouse-client ClickHouse client version 0.0.52053. @@ -101,14 +99,14 @@ ClickHouse - столбцовая СУБД для OLAP (Columnar DBMS). :) -2. По CPU. -Так как для выполнения запроса надо обработать достаточно большое количество строк, становится актуальным диспетчеризовывать все операции не для отдельных строк, а для целых векторов, или реализовать движок выполнения запроса так, чтобы издержки на диспетчеризацию были примерно нулевыми. Если этого не делать, то при любой не слишком плохой дисковой подсистеме, интерпретатор запроса неизбежно упрётся в CPU. -Имеет смысл не только хранить данные по столбцам, но и обрабатывать их, по возможности, тоже по столбцам. +2. For CPU. +Since executing a query requires processing a large number of rows, it helps to dispatch all operations for entire vectors instead of for separate rows, or to implement the query engine so that there is almost no dispatching cost. If you don't do this, with any half-decent disk subsystem, the query interpreter inevitably stalls the CPU. +It makes sense to both store data in columns and process it, when possible, by columns. -Есть два способа это сделать: -1. Векторный движок. Все операции пишутся не для отдельных значений, а для векторов. То есть, вызывать операции надо достаточно редко, и издержки на диспетчеризацию становятся пренебрежимо маленькими. Код операции содержит в себе хорошо оптимизированный внутренний цикл. -2. Кодогенерация. Для запроса генерируется код, в котором подставлены все косвенные вызовы. +There are two ways to do this: +1. A vector engine. All operations are written for vectors, instead of for separate values. This means you don't need to call operations very often, and dispatching costs are negligible. Operation code contains an optimized internal cycle. +2. Code generation. The code generated for the query has all the indirect calls in it. -В "обычных" БД этого не делается, так как не имеет смысла при выполнении простых запросов. Хотя есть исключения. Например, в MemSQL кодогенерация используется для уменьшения latency при выполнении SQL запросов. (Для сравнения - в аналитических СУБД, требуется оптимизация throughput, а не latency). +This is not done in "normal" databases, because it doesn't make sense when running simple queries. However, there are exceptions. For example, MemSQL uses code generation to reduce latency when processing SQL queries. (For comparison, analytical DBMSs require optimization of throughput, not latency.) -Стоит заметить, что для эффективности по CPU требуется, чтобы язык запросов был декларативным (SQL, MDX) или хотя бы векторным (J, K). То есть, чтобы запрос содержал циклы только в неявном виде, открывая возможности для оптимизации. +Note that for CPU efficiency, the query language must be declarative (SQL or MDX), or at least a vector (J, K). The query should only contain implicit loops, allowing for optimization. diff --git a/docs/en/introduction/ya_metrika_task.rst b/docs/en/introduction/ya_metrika_task.rst index cb4dfa8759a..6e98d268aa5 100644 --- a/docs/en/introduction/ya_metrika_task.rst +++ b/docs/en/introduction/ya_metrika_task.rst @@ -1,29 +1,26 @@ -Постановка задачи в Яндекс.Метрике +The Yandex.Metrica task ---------------------------------- -Нужно получать произвольные отчёты на основе хитов и визитов, с произвольными сегментами, задаваемыми пользователем. Данные для отчётов обновляются в реальном времени. Запросы должны выполняться сразу (в режиме онлайн). Отчёты должно быть возможно строить за произвольный период. Требуется вычислять сложные агрегаты типа количества уникальных посетителей. -На данный момент (апрель 2014), каждый день в Яндекс.Метрику поступает около 12 миллиардов событий (хитов и кликов мыши). Все эти события должны быть сохранены для возможности строить произвольные отчёты. Один запрос может потребовать просканировать сотни миллионов строк за время не более нескольких секунд, или миллионы строк за время не более нескольких сотен миллисекунд. +We need to get custom reports based on hits and sessions, with custom segments set by the user. Data for the reports is updated in real-time. Queries must be run immediately (in online mode). We must be able to build reports for any time period. Complex aggregates must be calculated, such as the number of unique visitors. +At this time (April 2014), Yandex.Metrica receives approximately 12 billion events (pageviews and mouse clicks) daily. All these events must be stored in order to build custom reports. A single query may require scanning hundreds of millions of rows over a few seconds, or millions of rows in no more than a few hundred milliseconds. -Агрегированные и неагрегированные данные +Aggregated and non-aggregated data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Существует мнение, что для того, чтобы эффективно считать статистику, данные нужно агрегировать, так как это позволяет уменьшить объём данных. +There is a popular opinion that in order to effectively calculate statistics, you must aggregate data, since this reduces the volume of data. -Но агрегированные данные являются очень ограниченным решением, по следующим причинам: - * вы должны заранее знать перечень отчётов, необходимых пользователю; - * то есть, пользователь не может построить произвольный отчёт; - * при агрегации по большому количеству ключей, объём данных не уменьшается и агрегация бесполезна; - * при большом количестве отчётов, получается слишком много вариантов агрегации (комбинаторный взрыв); - * при агрегации по ключам высокой кардинальности (например, URL) объём данных уменьшается не сильно (менее чем в 2 раза); - * из-за этого, объём данных при агрегации может не уменьшиться, а вырасти; - * пользователи будут смотреть не все отчёты, которые мы для них посчитаем - то есть, большая часть вычислений бесполезна; - * возможно нарушение логической целостности данных для разных агрегаций; +But data aggregation is a very limited solution, for the following reasons: -Как видно, если ничего не агрегировать, и работать с неагрегированными данными, то это даже может уменьшить объём вычислений. +* You must have a pre-defined list of reports the user will need. The user can't make custom reports. +* When aggregating a large quantity of keys, the volume of data is not reduced, and aggregation is useless. +* For a large number of reports, there are too many aggregation variations (combinatorial explosion). +* When aggregating keys with high cardinality (such as URLs), the volume of data is not reduced by much (less than twofold). For this reason, the volume of data with aggregation might grow instead of shrink. +* Users will not view all the reports we calculate for them. A large portion of calculations are useless. +* The logical integrity of data may be violated for various aggregations. -Впрочем, при агрегации, существенная часть работы выносится в оффлайне, и её можно делать сравнительно спокойно. Для сравнения, при онлайн вычислениях, вычисления надо делать так быстро, как это возможно, так как именно в момент вычислений пользователь ждёт результата. +If we do not aggregate anything and work with non-aggregated data, this might actually reduce the volume of calculations. -В Яндекс.Метрике есть специализированная система для агрегированных данных - Metrage, на основе которой работает большинство отчётов. -Также в Яндекс.Метрике с 2009 года использовалась специализированная OLAP БД для неагрегированных данных - OLAPServer, на основе которой раньше работал конструктор отчётов. -OLAPServer хорошо подходил для неагрегированных данных, но содержал много ограничений, не позволяющих использовать его для всех отчётах так, как хочется: отсутствие поддержки типов данных (только числа), невозможность инкрементального обновления данных в реальном времени (только перезаписью данных за сутки). OLAPServer не является СУБД, а является специализированной БД. +However, with aggregation, a significant part of the work is taken offline and completed relatively calmly. In contrast, online calculations require calculating as fast as possible, since the user is waiting for the result. -Чтобы снять ограничения OLAPServer-а и решить задачу работы с неагрегированными данными для всех отчётов, разработана СУБД ClickHouse. +Yandex.Metrica has a specialized system for aggregating data called Metrage, which is used for the majority of reports. Starting in 2009, Yandex.Metrica also used a specialized OLAP database for non-aggregated data called OLAPServer, which was previously used for the report builder. OLAPServer worked well for non-aggregated data, but it had many restrictions that did not allow it to be used for all reports as desired. These included the lack of support for data types (only numbers), and the inability to incrementally update data in real-time (it could only be done by rewriting data daily). OLAPServer is not a DBMS, but a specialized DB. + +To remove the limitations of OLAPServer and solve the problem of working with non-aggregated data for all reports, we developed the ClickHouse DBMS. diff --git a/docs/en/query_language/index.rst b/docs/en/query_language/index.rst index a4676e7aa99..7d11bcfe297 100644 --- a/docs/en/query_language/index.rst +++ b/docs/en/query_language/index.rst @@ -1,4 +1,4 @@ -Язык запросов +Query language ========== .. toctree:: diff --git a/docs/en/query_language/queries.rst b/docs/en/query_language/queries.rst index a7e801bcfc8..f4ddeb50fa5 100644 --- a/docs/en/query_language/queries.rst +++ b/docs/en/query_language/queries.rst @@ -1,18 +1,18 @@ -Запросы +Queries ------- CREATE DATABASE ~~~~~~~~~~~~~~~ -Создание базы данных db_name +Creates the 'db_name' database. :: CREATE DATABASE [IF NOT EXISTS] db_name -``База данных`` - это просто директория для таблиц. -Если написано ``IF NOT EXISTS``, то запрос не будет возвращать ошибку, если база данных уже существует. +A database is just a directory for tables. +If "IF NOT EXISTS" is included, the query won't return an error if the database already exists. CREATE TABLE ~~~~~~~~~~~~ -Запрос ``CREATE TABLE`` может иметь несколько форм. +The ``CREATE TABLE`` query can have several forms. :: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name ( @@ -21,233 +21,233 @@ CREATE TABLE ... ) ENGINE = engine -Создаёт таблицу с именем name в БД db или текущей БД, если db не указана, со структурой, указанной в скобках, и движком engine. -Структура таблицы представляет список описаний столбцов. Индексы, если поддерживаются движком, указываются в качестве параметров для движка таблицы. +Creates a table named 'name' in the 'db' database or the current database if 'db' is not set, with the structure specified in brackets and the 'engine' engine. The structure of the table is a list of column descriptions. If indexes are supported by the engine, they are indicated as parameters for the table engine. -Описание столбца, это ``name type``, в простейшем случае. Пример: ``RegionID UInt32``. -Также могут быть указаны выражения для значений по умолчанию - смотрите ниже. +A column description is ``name type`` in the simplest case. For example: ``RegionID UInt32``. +Expressions can also be defined for default values (see below). :: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name AS [db2.]name2 [ENGINE = engine] -Создаёт таблицу с такой же структурой, как другая таблица. Можно указать другой движок для таблицы. Если движок не указан, то будет выбран такой же движок, как у таблицы ``db2.name2``. +Creates a table with the same structure as another table. You can specify a different engine for the table. If the engine is not specified, the same engine will be used as for the 'db2.name2' table. :: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name ENGINE = engine AS SELECT ... -Создаёт таблицу со структурой, как результат запроса ``SELECT``, с движком engine, и заполняет её данными из SELECT-а. +Creates a table with a structure like the result of the ``SELECT`` query, with the 'engine' engine, and fills it with data from SELECT. -Во всех случаях, если указано ``IF NOT EXISTS``, то запрос не будет возвращать ошибку, если таблица уже существует. В этом случае, запрос будет ничего не делать. +In all cases, if IF NOT EXISTS is specified, the query won't return an error if the table already exists. In this case, the query won't do anything. -Значения по умолчанию +Default values """"""""""""""""""""" -В описании столбца, может быть указано выражение для значения по умолчанию, одного из следующих видов: +The column description can specify an expression for a default value, in one of the following ways: ``DEFAULT expr``, ``MATERIALIZED expr``, ``ALIAS expr``. -Пример: ``URLDomain String DEFAULT domain(URL)``. +Example: ``URLDomain String DEFAULT domain(URL)``. -Если выражение для значения по умолчанию не указано, то в качестве значений по умолчанию будут использоваться нули для чисел, пустые строки для строк, пустые массивы для массивов, а также ``0000-00-00`` для дат и ``0000-00-00 00:00:00`` для дат с временем. NULL-ы не поддерживаются. +If an expression for the default value is not defined, the default values will be set to zeros for numbers, empty strings for strings, empty arrays for arrays, and 0000-00-00 for dates or 0000-00-00 00:00:00 for dates with time. NULLs are not supported. -В случае, если указано выражение по умолчанию, то указание типа столбца не обязательно. При отсутствии явно указанного типа, будет использован тип выражения по умолчанию. Пример: ``EventDate DEFAULT toDate(EventTime)`` - для столбца EventDate будет использован тип Date. +If the default expression is defined, the column type is optional. If there isn't an explicitly defined type, the default expression type is used. Example: ``EventDate DEFAULT toDate(EventTime)`` - the 'Date' type will be used for the 'EventDate' column. -При наличии явно указанного типа данных и выражения по умолчанию, это выражение будет приводиться к указанному типу с использованием функций приведения типа. Пример: ``Hits UInt32 DEFAULT 0`` - имеет такой же смысл, как ``Hits UInt32 DEFAULT toUInt32(0)``. +If the data type and default expression are defined explicitly, this expression will be cast to the specified type using type casting functions. Example: ``Hits UInt32 DEFAULT 0`` means the same thing as ``Hits UInt32 DEFAULT toUInt32(0)``. -В качестве выражения для умолчания, может быть указано произвольное выражение от констант и столбцов таблицы. При создании и изменении структуры таблицы, проверяется, что выражения не содержат циклов. При INSERT-е проверяется разрешимость выражений - что все столбцы, из которых их можно вычислить, переданы. +Default expressions may be defined as an arbitrary expression from table constants and columns. When creating and changing the table structure, it checks that expressions don't contain loops. For INSERT, it checks that expressions are resolvable - that all columns they can be calculated from have been passed. ``DEFAULT expr`` -Обычное значение по умолчанию. Если в запросе INSERT не указан соответствующий столбец, то он будет заполнен путём вычисления соответствующего выражения. +Normal default value. If the INSERT query doesn't specify the corresponding column, it will be filled in by computing the corresponding expression. ``MATERIALIZED expr`` -Материализованное выражение. Такой столбец не может быть указан при INSERT-е, то есть, он всегда вычисляется. -При INSERT-е без указания списка столбцов, такие столбцы не рассматриваются. -Также этот столбец не подставляется при использовании звёздочки в запросе SELECT - чтобы сохранить инвариант, что дамп, полученный путём SELECT *, можно вставить обратно в таблицу INSERT-ом без указания списка столбцов. +Materialized expression. Such a column can't be specified for INSERT, because it is always calculated. +For an INSERT without a list of columns, these columns are not considered. +In addition, this column is not substituted when using an asterisk in a SELECT query. This is to preserve the invariant that the dump obtained using SELECT * can be inserted back into the table using INSERT without specifying the list of columns. ``ALIAS expr`` -Синоним. Такой столбец вообще не хранится в таблице. -Его значения не могут быть вставлены в таблицу, он не подставляется при использовании звёздочки в запросе SELECT. -Он может быть использован в SELECT-ах - в таком случае, во время разбора запроса, алиас раскрывается. +Synonym. Such a column isn't stored in the table at all. +Its values can't be inserted in a table, and it is not substituted when using an asterisk in a SELECT query. +It can be used in SELECTs if the alias is expanded during query parsing. -При добавлении новых столбцов с помощью запроса ALTER, старые данные для этих столбцов не записываются. Вместо этого, при чтении старых данных, для которых отсутствуют значения новых столбцов, выполняется вычисление выражений по умолчанию налету. При этом, если выполнение выражения требует использования других столбцов, не указанных в запросе, то эти столбцы будут дополнительно прочитаны, но только для тех блоков данных, для которых это необходимо. +When using the ALTER query to add new columns, old data for these columns is not written. Instead, when reading old data that does not have values for the new columns, expressions are computed on the fly by default. However, if running the expressions requires different columns that are not indicated in the query, these columns will additionally be read, but only for the blocks of data that need it. -Если добавить в таблицу новый столбец, а через некоторое время изменить его выражение по умолчанию, то используемые значения для старых данных (для данных, где значения не хранились на диске) поменяются. Также заметим, что при выполнении фоновых слияний, данные для столбцов, отсутствующих в одном из сливаемых кусков, записываются в объединённый кусок. +If you add a new column to a table but later change its default expression, the values used for old data will change (for data where values were not stored on the disk). Note that when running background merges, data for columns that are missing in one of the merging parts is written to the merged part. -Отсутствует возможность задать значения по умолчанию для элементов вложенных структур данных. +It is not possible to set default values for elements in nested data structures. -Временные таблицы +Temporary tables """"""""""""""""" -Во всех случаях, если указано ``TEMPORARY``, то будет создана временная таблица. Временные таблицы обладают следующими особенностями: -- временные таблицы исчезают после завершения сессии; в том числе, при обрыве соединения; -- временная таблица создаётся с движком Memory; все остальные движки таблиц не поддерживаются; -- для временной таблицы нет возможности указать БД: она создаётся вне баз данных; -- если временная таблица имеет то же имя, что и некоторая другая, то, при упоминании в запросе без указания БД, будет использована временная таблица; -- при распределённой обработке запроса, используемые в запросе временные таблицы, передаются на удалённые серверы. +In all cases, if TEMPORARY is specified, a temporary table will be created. Temporary tables have the following characteristics: +- Temporary tables disappear when the session ends, including if the connection is lost. +- A temporary table is created with the Memory engine. The other table engines are not supported. +- The DB can't be specified for a temporary table. It is created outside of databases. +- If a temporary table has the same name as another one and a query specifies the table name without specifying the DB, the temporary table will be used. +- For distributed query processing, temporary tables used in a query are passed to remote servers. -В большинстве случаев, временные таблицы создаются не вручную, а при использовании внешних данных для запроса, или при распределённом ``(GLOBAL) IN``. Подробнее см. соответствующие разделы +In most cases, temporary tables are not created manually, but when using external data for a query, or for distributed (GLOBAL) IN. For more information, see the appropriate sections. CREATE VIEW ~~~~~~~~~~~~ ``CREATE [MATERIALIZED] VIEW [IF NOT EXISTS] [db.]name [ENGINE = engine] [POPULATE] AS SELECT ...`` -Создаёт представление. Представления бывают двух видов - обычные и материализованные (MATERIALIZED). +Creates a view. There are two types of views: normal and MATERIALIZED. -Обычные представления не хранят никаких данных, а всего лишь производят чтение из другой таблицы. То есть, обычное представление - не более чем сохранённый запрос. При чтении из представления, этот сохранённый запрос, используется в качестве подзапроса в секции FROM. +Normal views don't store any data, but just perform a read from another table. In other words, a normal view is nothing more than a saved query. When reading from a view, this saved query is used as a subquery in the FROM clause. -Для примера, пусть вы создали представление: +As an example, assume you've created a view: :: CREATE VIEW view AS SELECT ... -и написали запрос: +and written a query: :: SELECT a, b, c FROM view -Этот запрос полностью эквивалентен использованию подзапроса: + +This query is fully equivalent to using the subquery: :: SELECT a, b, c FROM (SELECT ...) -Материализованные (MATERIALIZED) представления хранят данные, преобразованные соответствующим запросом SELECT. +Materialized views store data transformed by the corresponding SELECT query. -При создании материализованного представления, можно указать ENGINE - движок таблицы для хранения данных. По умолчанию, будет использован тот же движок, что и у таблицы, из которой делается запрос SELECT. +When creating a materialized view, you can specify ENGINE - the table engine for storing data. By default, it uses the same engine as for the table that the SELECT query is made from. -Материализованное представление устроено следующим образом: при вставке данных в таблицу, указанную в SELECT-е, кусок вставляемых данных преобразуется этим запросом SELECT, и полученный результат вставляется в представление. +A materialized view is arranged as follows: when inserting data to the table specified in SELECT, part of the inserted data is converted by this SELECT query, and the result is inserted in the view. -Если указано POPULATE, то при создании представления, в него будут вставлены имеющиеся данные таблицы, как если бы был сделан запрос ``CREATE TABLE ... AS SELECT ...`` . Иначе, представление будет содержать только данные, вставляемые в таблицу после создания представления. Не рекомендуется использовать POPULATE, так как вставляемые в таблицу данные во время создания представления, не попадут в него. +If you specify POPULATE, the existing table data is inserted in the view when creating it, as if making a CREATE TABLE ... AS SELECT ... query. Otherwise, the query contains only the data inserted in the table after creating the view. We don't recommend using POPULATE, since data inserted in the table during the view creation will not be inserted in it. -Запрос ``SELECT`` может содержать ``DISTINCT``, ``GROUP BY``, ``ORDER BY``, ``LIMIT``... Следует иметь ввиду, что соответствующие преобразования будут выполняться независимо, на каждый блок вставляемых данных. Например, при наличии ``GROUP BY``, данные будут агрегироваться при вставке, но только в рамках одной пачки вставляемых данных. Далее, данные не будут доагрегированы. Исключение - использование ENGINE, производящего агрегацию данных самостоятельно, например, ``SummingMergeTree``. +The SELECT query can contain DISTINCT, GROUP BY, ORDER BY, LIMIT ... Note that the corresponding conversions are performed independently on each block of inserted data. For example, if GROUP BY is set, data is aggregated during insertion, but only within a single packet of inserted data. The data won't be further aggregated. The exception is when using an ENGINE that independently performs data aggregation, such as SummingMergeTree. -Недоработано выполнение запросов ``ALTER`` над материализованными представлениями, поэтому они могут быть неудобными для использования. +The execution of ALTER queries on materialized views has not been fully developed, so they might be inconvenient. -Представления выглядят так же, как обычные таблицы. Например, они перечисляются в результате запроса ``SHOW TABLES``. +Views look the same as normal tables. For example, they are listed in the result of the SHOW TABLES query. -Отсутствует отдельный запрос для удаления представлений. Чтобы удалить представление, следует использовать ``DROP TABLE``. +There isn't a separate query for deleting views. To delete a view, use DROP TABLE. ATTACH ~~~~~~ -Запрос полностью аналогичен запросу ``CREATE``, но -- вместо слова ``CREATE`` используется слово ``ATTACH``; -- запрос не создаёт данные на диске, а предполагает, что данные уже лежат в соответствующих местах, и всего лишь добавляет информацию о таблице в сервер. -После выполнения запроса ATTACH, сервер будет знать о существовании таблицы. +The query is exactly the same as CREATE, except +- The word ATTACH is used instead of CREATE. +- The query doesn't create data on the disk, but assumes that data is already in the appropriate places, and just adds information about the table to the server. +After executing an ATTACH query, the server will know about the existence of the table. -Этот запрос используется при старте сервера. Сервер хранит метаданные таблиц в виде файлов с запросами ``ATTACH``, которые он просто исполняет при запуске (за исключением системных таблиц, создание которых явно вписано в сервер). +This query is used when starting the server. The server stores table metadata as files with ATTACH queries, which it simply runs at launch (with the exception of system tables, which are explicitly created on the server). DROP ~~~~ -Запрос имеет два вида: ``DROP DATABASE`` и ``DROP TABLE``. +This query has two types: ``DROP DATABASE`` and ``DROP TABLE``. :: DROP DATABASE [IF EXISTS] db -Удаляет все таблицы внутри базы данных db, а затем саму базу данных db. -Если указано ``IF EXISTS`` - не выдавать ошибку, если база данных не существует. +Deletes all tables inside the 'db' database, then deletes the 'db' database itself. +If IF EXISTS is specified, it doesn't return an error if the database doesn't exist. :: DROP TABLE [IF EXISTS] [db.]name -Удаляет таблицу. -Если указано ``IF EXISTS`` - не выдавать ошибку, если таблица не существует или база данных не существует. +Deletes the table. +If IF EXISTS is specified, it doesn't return an error if the table doesn't exist or the database doesn't exist. DETACH ~~~~~~ -Удаляет из сервера информацию о таблице `name`. Сервер перестаёт знать о существовании таблицы. +Deletes information about the table from the server. The server stops knowing about the table's existence. :: DETACH TABLE [IF EXISTS] [db.]name -Но ни данные, ни метаданные таблицы не удаляются. При следующем запуске сервера, сервер прочитает метаданные и снова узнает о таблице. -Также, "отцепленную" таблицу можно прицепить заново запросом ``ATTACH`` (за исключением системных таблиц, для которых метаданные не хранятся). +This does not delete the table's data or metadata. On the next server launch, the server will read the metadata and find out about the table again. Similarly, a "detached" table can be re-attached using the ATTACH query (with the exception of system tables, which do not have metadata stored for them). -Запроса ``DETACH DATABASE`` нет. +There is no DETACH DATABASE query. RENAME ~~~~~~ -Переименовывает одну или несколько таблиц. +Renames one or more tables. :: RENAME TABLE [db11.]name11 TO [db12.]name12, [db21.]name21 TO [db22.]name22, ... -Все таблицы переименовываются под глобальной блокировкой. Переименовывание таблицы является лёгкой операцией. Если вы указали после TO другую базу данных, то таблица будет перенесена в эту базу данных. При этом, директории с базами данных должны быть расположены в одной файловой системе (иначе возвращается ошибка). - + All tables are renamed under global locking. Renaming tables is a light operation. If you indicated another database after TO, the table will be moved to this database. However, the directories with databases must reside in the same file system (otherwise, an error is returned). + ALTER ~~~~~ -Запрос ``ALTER`` поддерживается только для таблиц типа ``*MergeTree``, а также ``Merge`` и ``Distributed``. Запрос имеет несколько вариантов. +The ALTER query is only supported for *MergeTree type tables, as well as for Merge and Distributed types. The query has several variations. -Манипуляции со столбцами +Column manipulations """""""""""""""""""""""" -Изменение структуры таблицы. +Lets you change the table structure. :: ALTER TABLE [db].name ADD|DROP|MODIFY COLUMN ... -В запросе указывается список из одного или более действий через запятую. -Каждое действие - операция над столбцом. +In the query, specify a list of one or more comma-separated actions. Each action is an operation on a column. -Существуют следующие действия: +The following actions are supported: :: ADD COLUMN name [type] [default_expr] [AFTER name_after] -Добавляет в таблицу новый столбец с именем name, типом type и выражением для умолчания ``default_expr`` (смотрите раздел "Значения по умолчанию"). Если указано ``AFTER name_after`` (имя другого столбца), то столбец добавляется (в список столбцов таблицы) после указанного. Иначе, столбец добавляется в конец таблицы. Внимательный читатель может заметить, что отсутствует возможность добавить столбец в начало таблицы. Для цепочки действий, name_after может быть именем столбца, который добавляется в одном из предыдущих действий. +Adds a new column to the table with the specified name, type, and default expression (see the section "Default expressions"). If you specify 'AFTER name_after' (the name of another column), the column is added after the specified one in the list of table columns. Otherwise, the column is added to the end of the table. Note that there is no way to add a column to the beginning of a table. For a chain of actions, 'name_after' can be the name of a column that is added in one of the previous actions. -Добавление столбца всего лишь меняет структуру таблицы, и не производит никаких действий с данными - соответствующие данные не появляются на диске после ALTER-а. При чтении из таблицы, если для какого-либо столбца отсутствуют данные, то он заполняется значениями по умолчанию (выполняя выражение по умолчанию, если такое есть, или нулями, пустыми строками). Также, столбец появляется на диске при слиянии кусков данных (см. MergeTree). +Adding a column just changes the table structure, without performing any actions with data. The data doesn't appear on the disk after ALTER. If the data is missing for a column when reading from the table, it is filled in with default values (by performing the default expression if there is one, or using zeros or empty strings). The column appears on the disk after merging data parts (see MergeTree). -Такая схема позволяет добиться мгновенной работы запроса ALTER и отсутствия необходимости увеличивать объём старых данных. +This approach allows us to complete the ALTER query instantly, without increasing the volume of old data. .. code-block:: sql DROP COLUMN name -Удаляет столбец с именем name. -Удаляет данные из файловой системы. Так как это представляет собой удаление целых файлов, запрос выполняется почти мгновенно. +Deletes the column with the name 'name'. + +Deletes data from the file system. Since this deletes entire files, the query is completed almost instantly. .. code-block:: sql MODIFY COLUMN name [type] [default_expr] -Изменяет тип столбца name на type и/или выражение для умолчания на default_expr. При изменении типа, значения преобразуются так, как если бы к ним была применена функция toType. +Changes the 'name' column's type to 'type' and/or the default expression to 'default_expr'. When changing the type, values are converted as if the 'toType' function were applied to them. -Если изменяется только выражение для умолчания, то запрос не делает никакой сложной работы и выполняется мгновенно. +If only the default expression is changed, the query doesn't do anything complex, and is completed almost instantly. -Изменение типа столбца - это единственное действие, которое выполняет сложную работу - меняет содержимое файлов с данными. Для больших таблиц, выполнение может занять длительное время. +Changing the column type is the only complex action - it changes the contents of files with data. For large tables, this may take a long time. -Выполнение производится в несколько стадий: -- подготовка временных (новых) файлов с изменёнными данными; -- переименование старых файлов; -- переименование временных (новых) файлов в старые; -- удаление старых файлов. +There are several stages of execution: +- Preparing temporary (new) files with modified data. +- Renaming old files. +- Renaming the temporary (new) files to the old names. +- Deleting the old files. -Из них, длительной является только первая стадия. Если на этой стадии возникнет сбой, то данные не поменяются. -Если на одной из следующих стадий возникнет сбой, то данные будет можно восстановить вручную. За исключением случаев, когда старые файлы удалены из файловой системы, а данные для новых файлов не доехали на диск и потеряны. +Only the first stage takes time. If there is a failure at this stage, the data is not changed. +If there is a failure during one of the successive stages, data can be restored manually. The exception is if the old files were deleted from the file system but the data for the new files did not get written to the disk and was lost. -Не поддерживается изменение типа столбца у массивов и вложенных структур данных. +There is no support for changing the column type in arrays and nested data structures. -Запрос ``ALTER`` позволяет создавать и удалять отдельные элементы (столбцы) вложенных структур данных, но не вложенные структуры данных целиком. Для добавления вложенной структуры данных, вы можете добавить столбцы с именем вида ``name.nested_name`` и типом ``Array(T)`` - вложенная структура данных полностью эквивалентна нескольким столбцам-массивам с именем, имеющим одинаковый префикс до точки. +The ALTER query lets you create and delete separate elements (columns) in nested data structures, but not whole nested data structures. To add a nested data structure, you can add columns with a name like 'name.nested_name' and the type 'Array(T)'. A nested data structure is equivalent to multiple array columns with a name that has the same prefix before the dot. -Отсутствует возможность удалять столбцы, входящие в первичный ключ или ключ для сэмплирования (в общем, входящие в выражение ``ENGINE``). Изменение типа у столбцов, входящих в первичный ключ возможно только в том случае, если это изменение не приводит к изменению данных (например, разрешено добавление значения в Enum или изменение типа с ``DateTime`` на ``UInt32``). +There is no support for deleting of columns in the primary key or the sampling key (columns that are in the ENGINE expression). Changing the type of columns in the primary key is allowed only if such change doesn't entail changing the actual data (e.g. adding the value to an Enum or changing the type from DateTime to UInt32 is allowed). -Если возможностей запроса ``ALTER`` не хватает для нужного изменения таблицы, вы можете создать новую таблицу, скопировать туда данные с помощью запроса ``INSERT SELECT``, затем поменять таблицы местами с помощью запроса ``RENAME``, и удалить старую таблицу. +If the ALTER query is not sufficient for making the table changes you need, you can create a new table, copy the data to it using the INSERT SELECT query, then switch the tables using the RENAME query and delete the old table. -Запрос ``ALTER`` блокирует все чтения и записи для таблицы. То есть, если на момент запроса ``ALTER``, выполнялся долгий ``SELECT``, то запрос ``ALTER`` сначала дождётся его выполнения. И в это время, все новые запросы к той же таблице, будут ждать, пока завершится этот ``ALTER``. +The ALTER query blocks all reads and writes for the table. In other words, if a long SELECT is running at the time of the ALTER query, the ALTER query will wait for the SELECT to complete. At the same time, all new queries to the same table will wait while this ALTER is running. -Для таблиц, которые не хранят данные самостоятельно (типа ``Merge`` и ``Distributed``), ``ALTER`` всего лишь меняет структуру таблицы, но не меняет структуру подчинённых таблиц. Для примера, при ALTER-е таблицы типа ``Distributed``, вам также потребуется выполнить запрос ``ALTER`` для таблиц на всех удалённых серверах. +For tables that don't store data themselves (Merge and Distributed), ALTER just changes the table structure, and does not change the structure of subordinate tables. For example, when running ALTER for a Distributed table, you will also need to run ALTER for the tables on all remote servers. -Запрос ``ALTER`` на изменение столбцов реплицируется. Соответствующие инструкции сохраняются в ZooKeeper, и затем каждая реплика их применяет. Все запросы ``ALTER`` выполняются в одном и том же порядке. Запрос ждёт выполнения соответствующих действий на всех репликах. Но при этом, запрос на изменение столбцов в реплицируемой таблице можно прервать, и все действия будут осуществлены асинхронно. +The ALTER query for changing columns is replicated. The instructions are saved in ZooKeeper, then each replica applies them. All ALTER queries are run in the same order. The query waits for the appropriate actions to be completed on the other replicas. However, a query to change columns in a replicated table can be interrupted, and all actions will be performed asynchronously. -Манипуляции с партициями и кусками +Manipulations with partitions and parts """""""""""""""""""""""""""""""""" -Работает только для таблиц семейства ``MergeTree``. Существуют следующие виды операций: +Only works for tables in the MergeTree family. The following operations are available: -* ``DETACH PARTITION`` - перенести партицию в директорию detached и забыть про неё. -* ``DROP PARTITION`` - удалить партицию. -* ``ATTACH PART|PARTITION`` - добавить в таблицу новый кусок или партицию из директории ``detached``. -* ``FREEZE PARTITION`` - создать бэкап партиции. -* ``FETCH PARTITION`` - скачать партицию с другого сервера. +* ``DETACH PARTITION`` - Move a partition to the 'detached' directory and forget it. +* ``DROP PARTITION`` - Delete a partition. +* ``ATTACH PART|PARTITION`` - Add a new part or partition from the 'detached' directory to the table. +* ``FREEZE PARTITION`` - Create a backup of a partition. +* ``FETCH PARTITION`` - Download a partition from another server. -Ниже будет рассмотрен каждый вид запроса по-отдельности. +Each type of query is covered separately below. -Партицией (partition) в таблице называются данные за один календарный месяц. Это определяется значениями ключа-даты, указанной в параметрах движка таблицы. Данные за каждый месяц хранятся отдельно, чтобы упростить всевозможные манипуляции с этими данными. +A partition in a table is data for a single calendar month. This is determined by the values of the date key specified in the table engine parameters. Each month's data is stored separately in order to simplify manipulations with this data. -Куском (part) в таблице называется часть данных одной партиции, отсортированная по первичному ключу. +A "part" in the table is part of the data from a single partition, sorted by the primary key. -Чтобы посмотреть набор кусков и партиций таблицы, можно воспользоваться системной таблицей ``system.parts``: +You can use the ``system.parts`` table to view the set of table parts and partitions: :: SELECT * FROM system.parts WHERE active -``active`` - учитывать только активные куски. Неактивными являются, например, исходные куски оставшиеся после слияния в более крупный кусок - такие куски удаляются приблизительно через 10 минут после слияния. +``active`` - Only count active parts. Inactive parts are, for example, source parts remaining after merging to a larger part - these parts are deleted approximately 10 minutes after merging. -Другой способ посмотреть набор кусков и партиций - зайти в директорию с данными таблицы. -Директория с данными - ``/var/lib/clickhouse/data/database/table/``, -где ``/var/lib/clickhouse/`` - путь к данным ClickHouse, database - имя базы данных, table - имя таблицы. Пример: +Another way to view a set of parts and partitions is to go into the directory with table data. +The directory with data is +/var/lib/clickhouse/data/database/table/, +where /var/lib/clickhouse/ is the path to ClickHouse data, 'database' is the database name, and 'table' is the table name. Example: :: $ ls -l /var/lib/clickhouse/data/test/visits/ total 48 @@ -256,110 +256,106 @@ ALTER drwxrwxrwx 2 clickhouse clickhouse 4096 мая 13 02:55 detached -rw-rw-rw- 1 clickhouse clickhouse 2 мая 13 02:58 increment.txt -Здесь ``20140317_20140323_2_2_0``, ``20140317_20140323_4_4_0`` - директории кусков. +Here ``20140317_20140323_2_2_0``, ``20140317_20140323_4_4_0`` - are directories of parts. -Рассмотрим по порядку имя первого куска: ``20140317_20140323_2_2_0``. - * ``20140317`` - минимальная дата данных куска - * ``20140323`` - максимальная дата данных куска .. |br| raw:: html - * ``2`` - минимальный номер блока данных .. |br| raw:: html - * ``2`` - максимальный номер блока данных .. |br| raw:: html - * ``0`` - уровень куска - глубина дерева слияний, которыми он образован +Let's look at the name of the first part: ``20140317_20140323_2_2_0``. + * ``20140317`` - minimum date of part data + * ``20140323`` - maximum date of part data .. |br| raw:: html + * ``2`` - minimum number of the data block .. |br| raw:: html + * ``2`` - maximum number of the data block .. |br| raw:: html + * ``0`` - part level - depth of the merge tree that formed it -Каждый кусок относится к одной партиции и содержит данные только за один месяц. -``201403`` - имя партиции. Партиция представляет собой набор кусков за один месяц. +Each part corresponds to a single partition and contains data for a single month. +201403 - The partition name. A partition is a set of parts for a single month. -При работающем сервере, нельзя вручную изменять набор кусков или их данные на файловой системе, так как сервер не будет об этом знать. -Для нереплицируемых таблиц, вы можете это делать при остановленном сервере, хотя это не рекомендуется. -Для реплицируемых таблиц, набор кусков нельзя менять в любом случае. +On an operating server, you can't manually change the set of parts or their data on the file system, since the server won't know about it. For non-replicated tables, you can do this when the server is stopped, but we don't recommended it. For replicated tables, the set of parts can't be changed in any case. -Директория ``detached`` содержит куски, не используемые сервером - отцепленные от таблицы с помощью запроса ``ALTER ... DETACH``. Также в эту директорию переносятся куски, признанные повреждёнными, вместо их удаления. Вы можете в любое время добавлять, удалять, модифицировать данные в директории detached - сервер не будет об этом знать, пока вы не сделаете запрос ``ALTER TABLE ... ATTACH``. +The 'detached' directory contains parts that are not used by the server - detached from the table using the ALTER ... DETACH query. Parts that are damaged are also moved to this directory, instead of deleting them. You can add, delete, or modify the data in the 'detached' directory at any time - the server won't know about this until you make the ALTER TABLE ... ATTACH query. :: ALTER TABLE [db.]table DETACH PARTITION 'name' -Перенести все данные для партиции с именем name в директорию detached и забыть про них. -Имя партиции указывается в формате YYYYMM. Оно может быть указано в одинарных кавычках или без них. +Move all data for partitions named 'name' to the 'detached' directory and forget about them. +The partition name is specified in YYYYMM format. It can be indicated in single quotes or without them. -После того, как запрос будет выполнен, вы можете самостоятельно сделать что угодно с данными в директории detached, например, удалить их из файловой системы, или ничего не делать. +After the query is executed, you can do whatever you want with the data in the 'detached' directory — delete it from the file system, or just leave it. -Запрос реплицируется - данные будут перенесены в директорию detached и забыты на всех репликах. Запрос может быть отправлен только на реплику-лидер. Вы можете узнать, является ли реплика лидером, сделав SELECT в системную таблицу system.replicas. Или, проще, вы можете выполнить запрос на всех репликах, и на всех кроме одной, он кинет исключение. +The query is replicated - data will be moved to the 'detached' directory and forgotten on all replicas. The query can only be sent to a leader replica. To find out if a replica is a leader, perform SELECT to the 'system.replicas' system table. Alternatively, it is easier to make a query on all replicas, and all except one will throw an exception. :: ALTER TABLE [db.]table DROP PARTITION 'name' -Аналогично операции ``DETACH``. Удалить данные из таблицы. Куски с данными будут помечены как неактивные и будут полностью удалены примерно через 10 минут. Запрос реплицируется - данные будут удалены на всех репликах. +Similar to the DETACH operation. Deletes data from the table. Data parts will be tagged as inactive and will be completely deleted in approximately 10 minutes. The query is replicated - data will be deleted on all replicas. :: ALTER TABLE [db.]table ATTACH PARTITION|PART 'name' -Добавить данные в таблицу из директории detached. +Adds data to the table from the 'detached' directory. -Существует возможность добавить данные для целой партиции (PARTITION) или отдельный кусок (PART). В случае PART, укажите полное имя куска в одинарных кавычках. +It is possible to add data for an entire partition or a separate part. For a part, specify the full name of the part in single quotes. -Запрос реплицируется. Каждая реплика проверяет, если ли данные в директории detached. Если данные есть - проверяет их целостность, проверяет их соответствие данным на сервере-инициаторе запроса, и если всё хорошо, то добавляет их. Если нет, то скачивает данные с реплики-инициатора запроса, или с другой реплики, на которой уже добавлены эти данные. +The query is replicated. Each replica checks whether there is data in the 'detached' directory. If there is data, it checks the integrity, verifies that it matches the data on the server that initiated the query, and then adds it if everything is correct. If not, it downloads data from the query requestor replica, or from another replica where the data has already been added. -То есть, вы можете разместить данные в директории detached на одной реплике и, с помощью запроса ALTER ... ATTACH добавить их в таблицу на всех репликах. +So you can put data in the 'detached' directory on one replica, and use the ALTER ... ATTACH query to add it to the table on all replicas. :: ALTER TABLE [db.]table FREEZE PARTITION 'name' -Создаёт локальный бэкап одной или нескольких партиций. В качестве имени может быть указано полное имя партиции (например, 201403) или его префикс (например, 2014) - тогда бэкап будет создан для всех соответствующих партиций. +Creates a local backup of one or multiple partitions. The name can be the full name of the partition (for example, 201403), or its prefix (for example, 2014) - then the backup will be created for all the corresponding partitions. -Запрос делает следующее: для снэпшота данных на момент его выполнения, создаёт hardlink-и на данные таблиц в директории ``/var/lib/clickhouse/shadow/N/...`` +The query does the following: for a data snapshot at the time of execution, it creates hardlinks to table data in the directory /var/lib/clickhouse/shadow/N/... +/var/lib/clickhouse/ is the working ClickHouse directory from the config. +N is the incremental number of the backup. -``/var/lib/clickhouse/`` - рабочая директория ClickHouse из конфига. -``N`` - инкрементальный номер бэкапа. +``/var/lib/clickhouse/`` - working directory of ClickHouse from config file. +``N`` - incremental number of backup. -Структура директорий внутри бэкапа создаётся такой же, как внутри ``/var/lib/clickhouse/``. -Также делает chmod всех файлов, запрещая запись в них. +The same structure of directories is created inside the backup as inside ``/var/lib/clickhouse/``. +It also performs 'chmod' for all files, forbidding writes to them. -Создание бэкапа происходит почти мгновенно (но сначала дожидается окончания выполняющихся в данный момент запросов к соответствующей таблице). Бэкап изначально не занимает места на диске. При дальнейшей работе системы, бэкап может отнимать место на диске, по мере модификации данных. Если бэкап делается для достаточно старых данных, то он не будет отнимать место на диске. +The backup is created almost instantly (but first it waits for current queries to the corresponding table to finish running). At first, the backup doesn't take any space on the disk. As the system works, the backup can take disk space, as data is modified. If the backup is made for old enough data, it won't take space on the disk. -После создания бэкапа, данные из ``/var/lib/clickhouse/shadow/`` можно скопировать на удалённый сервер и затем удалить на локальном сервере. -Весь процесс бэкапа не требует остановки сервера. +After creating the backup, data from ``/var/lib/clickhouse/shadow/`` can be copied to the remote server and then deleted on the local server. The entire backup process is performed without stopping the server. -Запрос ``ALTER ... FREEZE PARTITION`` не реплицируется. То есть, локальный бэкап создаётся только на локальном сервере. +The ``ALTER ... FREEZE PARTITION`` query is not replicated. A local backup is only created on the local server. -В качестве альтернативного варианта, вы можете скопировать данные из директории ``/var/lib/clickhouse/data/database/table`` вручную. -Но если это делать при запущенном сервере, то возможны race conditions при копировании директории с добавляющимися/изменяющимися файлами, и бэкап может быть неконсистентным. Этот вариант может использоваться, если сервер не запущен - тогда полученные данные будут такими же, как после запроса ``ALTER TABLE t FREEZE PARTITION``. +As an alternative, you can manually copy data from the ``/var/lib/clickhouse/data/database/table directory``. But if you do this while the server is running, race conditions are possible when copying directories with files being added or changed, and the backup may be inconsistent. You can do this if the server isn't running - then the resulting data will be the same as after the ALTER TABLE t FREEZE PARTITION query. -``ALTER TABLE ... FREEZE PARTITION`` копирует только данные, но не метаданные таблицы. Чтобы сделать бэкап метаданных таблицы, скопируйте файл ``/var/lib/clickhouse/metadata/database/table.sql`` +``ALTER TABLE ... FREEZE PARTITION`` only copies data, not table metadata. To make a backup of table metadata, copy the file ``/var/lib/clickhouse/metadata/database/table.sql`` -Для восстановления из бэкапа: - * создайте таблицу, если её нет, с помощью запроса CREATE. Запрос можно взять из .sql файла (замените в нём ``ATTACH`` на ``CREATE``); - * скопируйте данные из директории data/database/table/ внутри бэкапа в директорию ``/var/lib/clickhouse/data/database/table/detached/`` - * выполните запросы ``ALTER TABLE ... ATTACH PARTITION YYYYMM``, где ``YYYYMM`` - месяц, для каждого месяца. +To restore from a backup: +* Use the CREATE query to create the table if it doesn't exist. The query can be taken from an .sql file (replace ATTACH in it with CREATE). +* Copy data from the ``data/database/table/`` directory inside the backup to the ``/var/lib/clickhouse/data/database/table/detached/`` directory. +* Run ``ALTER TABLE ... ATTACH PARTITION YYYYMM``queries where ``YYYYMM`` is the month, for every month. -Таким образом, данные из бэкапа будут добавлены в таблицу. -Восстановление из бэкапа, так же, не требует остановки сервера. +In this way, data from the backup will be added to the table. +Restoring from a backup doesn't require stopping the server. -Бэкапы и репликация +Backups and replication """"""""""""""""""" -Репликация защищает от аппаратных сбоев. В случае, если на одной из реплик у вас исчезли все данные, то восстановление делается по инструкции в разделе "Восстановление после сбоя". +Replication provides protection from device failures. If all data disappeared on one of your replicas, follow the instructions in the "Restoration after failure" section to restore it. -Для защиты от аппаратных сбоев, обязательно используйте репликацию. Подробнее про репликацию написано в разделе "Репликация данных". +For protection from device failures, you must use replication. For more information about replication, see the section "Data replication". -Бэкапы защищают от человеческих ошибок (случайно удалили данные, удалили не те данные или не на том кластере, испортили данные). -Для баз данных большого объёма, бывает затруднительно копировать бэкапы на удалённые серверы. В этих случаях, для защиты от человеческой ошибки, можно держать бэкап на том же сервере (он будет лежать в ``/var/lib/clickhouse/shadow/``). +Backups protect against human error (accidentally deleting data, deleting the wrong data or in the wrong cluster, or corrupting data). For high-volume databases, it can be difficult to copy backups to remote servers. In such cases, to protect from human error, you can keep a backup on the same server (it will reside in /var/lib/clickhouse/shadow/). :: ALTER TABLE [db.]table FETCH PARTITION 'name' FROM 'path-in-zookeeper' -Запрос работает только для реплицируемых таблиц. +This query only works for replicatable tables. -Скачивает указанную партицию с шарда, путь в ``ZooKeeper`` к которому указан в секции ``FROM`` и помещает в директорию ``detached`` указанной таблицы. +It downloads the specified partition from the shard that has its ZooKeeper path specified in the FROM clause, then puts it in the 'detached' directory for the specified table. -Не смотря на то, что запрос называется ``ALTER TABLE``, он не изменяет структуру таблицы, и не изменяет сразу доступные данные в таблице. +Although the query is called ALTER TABLE, it does not change the table structure, and does not immediately change the data available in the table. -Данные помещаются в директорию ``detached``, и их можно прикрепить с помощью запроса ``ALTER TABLE ... ATTACH``. +Data is placed in the 'detached' directory. You can use the ALTER TABLE ... ATTACH query to attach the data. -В секции ``FROM`` указывается путь в ``ZooKeeper``. Например, ``/clickhouse/tables/01-01/visits``. -Перед скачиванием проверяется существование партиции и совпадение структуры таблицы. Автоматически выбирается наиболее актуальная реплика среди живых реплик. +The path to ZooKeeper is specified in the FROM clause. For example, ``/clickhouse/tables/01-01/visits``. +Before downloading, the system checks that the partition exists and the table structure matches. The most appropriate replica is selected automatically from the healthy replicas. -Запрос ``ALTER ... FETCH PARTITION`` не реплицируется. То есть, партиция будет скачана в директорию detached только на локальном сервере. Заметим, что если вы после этого добавите данные в таблицу с помощью запроса ``ALTER TABLE ... ATTACH``, то данные будут добавлены на всех репликах (на одной из реплик будут добавлены из директории detached, а на других - загружены с соседних реплик). +The ALTER ... FETCH PARTITION query is not replicated. The partition will be downloaded to the 'detached' directory only on the local server. Note that if after this you use the ALTER TABLE ... ATTACH query to add data to the table, the data will be added on all replicas (on one of the replicas it will be added from the 'detached' directory, and on the rest it will be loaded from neighboring replicas). -Синхронность запросов ALTER +Synchronicity of ALTER queries """"""""""""""""""""""""""" +For non-replicatable tables, all ALTER queries are performed synchronously. For replicatable tables, the query just adds instructions for the appropriate actions to ZooKeeper, and the actions themselves are performed as soon as possible. However, the query can wait for these actions to be completed on all the replicas. -Для нереплицируемых таблиц, все запросы ``ALTER`` выполняются синхронно. Для реплицируемых таблиц, запрос всего лишь добавляет инструкцию по соответствующим действиям в ``ZooKeeper``, а сами действия осуществляются при первой возможности. Но при этом, запрос может ждать завершения выполнения этих действий на всех репликах. - -Для запросов ``ALTER ... ATTACH|DETACH|DROP`` можно настроить ожидание, с помощью настройки ``replication_alter_partitions_sync``. -Возможные значения: ``0`` - не ждать, ``1`` - ждать выполнения только у себя (по умолчанию), ``2`` - ждать всех. +For ``ALTER ... ATTACH|DETACH|DROP`` queries, you can use the ``'replication_alter_partitions_sync'`` setting to set up waiting. +Possible values: 0 - do not wait, 1 - wait for own completion (default), 2 - wait for all. SHOW DATABASES ~~~~~~~~~~~~~~ @@ -368,10 +364,9 @@ SHOW DATABASES SHOW DATABASES [INTO OUTFILE filename] [FORMAT format] -Выводит список всех баз данных. -Запрос полностью аналогичен запросу ``SELECT name FROM system.databases [INTO OUTFILE filename] [FORMAT format]``. - -Смотрите также раздел "Форматы". +Prints a list of all databases. +This query is identical to the query ``SELECT name FROM system.databases [INTO OUTFILE filename] [FORMAT format]`` +See the section "Formats". SHOW TABLES ~~~~~~~~~~~ @@ -380,12 +375,13 @@ SHOW TABLES SHOW TABLES [FROM db] [LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format] -Выводит список таблиц - * из текущей БД или из БД db, если указано FROM db; - * всех, или имя которых соответствует шаблону pattern, если указано LIKE 'pattern'; +Outputs a list of +* tables from the current database, or from the 'db' database if "FROM db" is specified. +* all tables, or tables whose name matches the pattern, if "LIKE 'pattern'" is specified. -Запрос полностью аналогичен запросу: ``SELECT name FROM system.tables WHERE database = 'db' [AND name LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format]`` -Смотрите также раздел "Оператор LIKE". +The query is identical to the query SELECT name FROM system.tables +WHERE database = 'db' [AND name LIKE 'pattern'] [INTO OUTFILE filename] [FORMAT format] +See the section "LIKE operator". SHOW PROCESSLIST ~~~~~~~~~~~~~~~~ @@ -394,27 +390,27 @@ SHOW PROCESSLIST SHOW PROCESSLIST [INTO OUTFILE filename] [FORMAT format] -Выводит список запросов, выполняющихся в данный момент времени, кроме запросов ``SHOW PROCESSLIST``. +Outputs a list of queries currently being processed, other than SHOW PROCESSLIST queries. -Выдаёт таблицу, содержащую столбцы: +Prints a table containing the columns: -**user** - пользователь, под которым был задан запрос. Следует иметь ввиду, что при распределённой обработке запроса на удалённые серверы запросы отправляются под пользователем default. И SHOW PROCESSLIST показывает имя пользователя для конкретного запроса, а не для запроса, который данный запрос инициировал. +**user** is the user who made the query. Keep in mind that for distributed processing, queries are sent to remote servers under the 'default' user. SHOW PROCESSLIST shows the username for a specific query, not for a query that this query initiated. -**address** - имя хоста, с которого был отправлен запрос. При распределённой обработке запроса на удалённых серверах — это имя хоста-инициатора запроса. Чтобы проследить, откуда был задан распределённый запрос изначально, следует смотреть SHOW PROCESSLIST на сервере-инициаторе запроса. +**address** is the name of the host that the query was sent from. For distributed processing, on remote servers, this is the name of the query requestor host. To track where a distributed query was originally made from, look at SHOW PROCESSLIST on the query requestor server. -**elapsed** - время выполнения запроса, в секундах. Запросы выводятся упорядоченными по убыванию времени выполнения. +**elapsed** - The execution time, in seconds. Queries are output in order of decreasing execution time. -**rows_read**, **bytes_read** - сколько было прочитано строк, байт несжатых данных при обработке запроса. При распределённой обработке запроса суммируются данные со всех удалённых серверов. Именно эти данные используются для ограничений и квот. +**rows_read**, **bytes_read** - How many rows and bytes of uncompressed data were read when processing the query. For distributed processing, data is totaled from all the remote servers. This is the data used for restrictions and quotas. -**memory_usage** - текущее потребление оперативки в байтах. Смотрите настройку max_memory_usage. +**memory_usage** - Current RAM usage in bytes. See the setting 'max_memory_usage'. -**query** - сам запрос. В запросах INSERT данные для вставки не выводятся. +**query** - The query itself. In INSERT queries, the data for insertion is not output. -**query_id** - идентификатор запроса. Непустой, только если был явно задан пользователем. При распределённой обработке запроса идентификатор запроса не передаётся на удалённые серверы. +**query_id** - The query identifier. Non-empty only if it was explicitly defined by the user. For distributed processing, the query ID is not passed to remote servers. -Запрос полностью аналогичен запросу: ``SELECT * FROM system.processes [INTO OUTFILE filename] [FORMAT format]``. +This query is exactly the same as: SELECT * FROM system.processes [INTO OUTFILE filename] [FORMAT format]. -Полезный совет (выполните в консоли): +Tip (execute in the console): ``watch -n1 "clickhouse-client --query='SHOW PROCESSLIST'"`` SHOW CREATE TABLE @@ -424,7 +420,7 @@ SHOW CREATE TABLE SHOW CREATE TABLE [db.]table [INTO OUTFILE filename] [FORMAT format] -Возвращает один столбец statement типа ``String``, содержащий одно значение - запрос ``CREATE``, с помощью которого создана указанная таблица. +Returns a single String-type 'statement' column, which contains a single value - the CREATE query used for creating the specified table. DESCRIBE TABLE ~~~~~~~~~~~~~~ @@ -433,9 +429,9 @@ DESCRIBE TABLE DESC|DESCRIBE TABLE [db.]table [INTO OUTFILE filename] [FORMAT format] -Возвращает два столбца: ``name``, ``type`` типа ``String``, в которых описаны имена и типы столбцов указанной таблицы. +Returns two String-type columns: 'name' and 'type', which indicate the names and types of columns in the specified table. -Вложенные структуры данных выводятся в "развёрнутом" виде. То есть, каждый столбец - по отдельности, с именем через точку. +Nested data structures are output in "expanded" format. Each column is shown separately, with the name after a dot. EXISTS ~~~~~~ @@ -444,7 +440,7 @@ EXISTS EXISTS TABLE [db.]name [INTO OUTFILE filename] [FORMAT format] -Возвращает один столбец типа ``UInt8``, содержащий одно значение - ``0``, если таблицы или БД не существует и ``1``, если таблица в указанной БД существует. +Returns a single UInt8-type column, which contains the single value 0 if the table or database doesn't exist, or 1 if the table exists in the specified database. USE ~~~ @@ -453,9 +449,9 @@ USE USE db -Позволяет установить текущую базу данных для сессии. -Текущая база данных используется для поиска таблиц, если база данных не указана в запросе явно через точку перед именем таблицы. -При использовании HTTP протокола, запрос не может быть выполнен, так как понятия сессии не существует. +Lets you set the current database for the session. +The current database is used for searching for tables if the database is not explicitly defined in the query with a dot before the table name. +This query can't be made when using the HTTP protocol, since there is no concept of a session. SET ~~~ @@ -464,14 +460,13 @@ SET SET [GLOBAL] param = value -Позволяет установить настройку ``param`` в значение ``value``. Также можно одним запросом установить все настройки из заданного профиля настроек - для этого, укажите в качестве имени настройки profile. Подробнее смотри раздел "Настройки". -Настройка устанавливается на сессию, или на сервер (глобально), если указано ``GLOBAL``. -При установке глобальной настройки, настройка на все уже запущенные сессии, включая текущую сессию, не устанавливается, а будет использована только для новых сессий. +Lets you set the 'param' setting to 'value'. You can also make all the settings from the specified settings profile in a single query. To do this, specify 'profile' as the setting name. For more information, see the section "Settings". The setting is made for the session, or for the server (globally) if GLOBAL is specified. +When making a global setting, the setting is not applied to sessions already running, including the current session. It will only be used for new sessions. -Настройки, заданные с помощью ``SET GLOBAL`` имеют меньший приоритет по сравнению с настройками, указанными в профиле пользователя, в конфигурационном файле. То есть, переопределить такие настройки с помощью ``SET GLOBAL`` невозможно. +Settings made using SET GLOBAL have a lower priority compared with settings made in the config file in the user profile. In other words, user settings can't be overridden by SET GLOBAL. -При перезапуске сервера, теряются глобальные настройки, установленные с помощью ``SET GLOBAL``. -Установить настройки, которые переживут перезапуск сервера, можно только с помощью конфигурационного файла сервера. (Это не может быть сделано с помощью запроса ``SET``.) +When the server is restarted, global settings made using SET GLOBAL are lost. +To make settings that persist after a server restart, you can only use the server's config file. (This can't be done using a SET query.) OPTIMIZE ~~~~~~~~ @@ -480,21 +475,21 @@ OPTIMIZE OPTIMIZE TABLE [db.]name [PARTITION partition] [FINAL] -Просит движок таблицы сделать что-нибудь, что может привести к более оптимальной работе. -Поддерживается только движками ``*MergeTree``, в котором выполнение этого запроса инициирует внеочередное слияние кусков данных. -Если указан ``PARTITION``, то оптимизация будет производиться только для указаной партиции. -Если указан ``FINAL``, то оптимизация будет производиться даже когда все данные уже лежат в одном куске. +Asks the table engine to do something for optimization. +Supported only by *MergeTree engines, in which this query initializes a non-scheduled merge of data parts. +If ``PARTITION`` is specified, then only specified partition will be optimized. +If ``FINAL`` is specified, then optimization will be performed even if data inside the partition already optimized (i. e. all data is in single part). INSERT ~~~~~~ -Запрос имеет несколько вариантов. +This query has several variations. .. code-block:: sql INSERT INTO [db.]table [(c1, c2, c3)] VALUES (v11, v12, v13), (v21, v22, v23), ... -Вставляет в таблицу table строчки с перечисленными значениями. -Запрос полностью аналогичен запросу вида: +Inserts rows with the listed values in the 'table' table. +This query is exactly the same as: .. code-block:: sql @@ -504,10 +499,10 @@ INSERT INSERT INTO [db.]table [(c1, c2, c3)] FORMAT format ... -Вставка данных в произвольном указанном формате. -Сами данные идут после format, после всех пробельных символов до первого перевода строки, если он есть, включая его, или после всех пробельных символов, если переводов строки нет. Рекомендуется писать данные начиная со следующей строки (это важно, если данные начинаются с пробельных символов). +Inserts data in any specified format. +The data itself comes after 'format', after all space symbols up to the first line break if there is one and including it, or after all space symbols if there isn't a line break. We recommend writing data starting from the next line (this is important if the data starts with space characters). -Пример: +Example: .. code-block:: sql @@ -515,31 +510,32 @@ INSERT 11 Hello, world! 22 Qwerty -Подробнее про форматы данных смотрите в разделе "Форматы". -В разделе "Интерфейсы" описано, как можно вставлять данные отдельно от запроса, при использовании клиента командной строки или HTTP интерфейса. +For more information about data formats, see the section "Formats". The "Interfaces" section describes how to insert data separately from the query when using the command-line client or the HTTP interface. -В запросе может быть опционально указан список столбцов для вставки. В этом случае, в остальные столбцы записываются значения по умолчанию. -Значения по умолчанию вычисляются из DEFAULT выражений, указанных в определении таблицы, или, если ``DEFAULT`` не прописан явно - используются нули, пустые строки. Если настройка ``strict_insert_defaults`` выставлена в 1, то все столбцы, для которых нет явных DEFAULT-ов, должны быть указаны в запросе. +The query may optionally specify a list of columns for insertion. In this case, the default values are written to the other columns. +Default values are calculated from DEFAULT expressions specified in table definitions, or, if the DEFAULT is not explicitly defined, zeros and empty strings are used. If the 'strict_insert_default' setting is set to 1, all the columns that do not have explicit DEFAULTS must be specified in the query. .. code-block:: sql INSERT INTO [db.]table [(c1, c2, c3)] SELECT ... -Вставка в таблицу результата запроса ``SELECT``. -Имена и типы данных результата выполнения SELECT-а должны точно совпадать со структурой таблицы, в которую вставляются данные, или с указанным списком столбцов. -Для изменения имён столбцов следует использовать синонимы (AS) в запросе ``SELECT``. -Для изменения типов данных следует использовать функции преобразования типов (смотрите раздел "Функции"). +Inserts the result of the SELECT query into a table. +The names and data types of the SELECT result must exactly match the table structure that data is inserted into, or the specified list of columns. +To change column names, use synonyms (AS) in the SELECT query. +To change data types, use type conversion functions (see the section "Functions"). -Ни один из форматов данных не позволяет использовать в качестве значений выражения. -То есть, вы не можете написать ``INSERT INTO t VALUES (now(), 1 + 1, DEFAULT)``. +None of the data formats allows using expressions as values. +In other words, you can't write INSERT INTO t VALUES (now(), 1 + 1, DEFAULT). + +There is no support for other data part modification queries: +UPDATE, DELETE, REPLACE, MERGE, UPSERT, INSERT UPDATE. +However, you can delete old data using ALTER TABLE ... DROP PARTITION. -Не поддерживаются другие запросы на модификацию части данных: ``UPDATE``, ``DELETE``, ``REPLACE``, ``MERGE``, ``UPSERT``, ``INSERT UPDATE``. -Впрочем, вы можете удалять старые данные с помощью запроса ``ALTER TABLE ... DROP PARTITION``. SELECT ~~~~~~ -Его величество, запрос SELECT. +His Highness, the SELECT query. .. code-block:: sql @@ -558,42 +554,42 @@ SELECT [INTO OUTFILE filename] [FORMAT format] -Все секции, кроме списка выражений сразу после SELECT, являются необязательными. -Ниже секции будут описаны в порядке, почти соответствующем конвейеру выполнения запроса. +All the clauses are optional, except for the required list of expressions immediately after SELECT. +The clauses below are described in almost the same order as in the query execution conveyor. -Если в запросе отсутствуют секции ``DISTINCT``, ``GROUP BY``, ``ORDER BY``, подзапросы в ``IN`` и ``JOIN``, то запрос будет обработан полностью потоково, с использованием O(1) количества оперативки. -Иначе запрос может съесть много оперативки, если не указаны подходящие ограничения ``max_memory_usage``, ``max_rows_to_group_by``, ``max_rows_to_sort``, ``max_rows_in_distinct``, ``max_bytes_in_distinct``, ``max_rows_in_set``, ``max_bytes_in_set``, ``max_rows_in_join``, ``max_bytes_in_join``, ``max_bytes_before_external_sort``, ``max_bytes_before_external_group_by``. Подробнее смотрите в разделе "Настройки". Присутствует возможность использовать внешнюю сортировку (с сохранением временных данных на диск) и внешнюю агрегацию. ``Merge join`` в системе нет. +If the query omits the DISTINCT, GROUP BY, and ORDER BY clauses and the IN and JOIN subqueries, the query will be completely stream processed, using O(1) amount of RAM. +Otherwise, the query may consume too much RAM, if appropriate restrictions are not defined (max_memory_usage, max_rows_to_group_by, max_rows_to_sort, max_rows_in_distinct, max_bytes_in_distinct, max_rows_in_set, max_bytes_in_set, max_rows_in_join, max_bytes_in_join, max_bytes_before_external_sort, max_bytes_before_external_group_by). For more information, see the section "Settings". It is possible to use external sorting (saving temporary tables to a disk) and external aggregation. Merge join is not implemented. -Секция FROM +FROM clause """"""""""" -Если секция FROM отсутствует, то данные будут читаться из таблицы ``system.one``. -Таблица system.one содержит ровно одну строку (то есть, эта таблица выполняет такую же роль, как таблица DUAL, которую можно найти в других СУБД). +If the FROM clause is omitted, data will be read from the 'system.one' table. +The 'system.one' table contains exactly one row (this table fulfills the same purpose as the DUAL table found in other DBMSs). -В секции FROM указывается таблица, из которой будут читаться данные, либо подзапрос, либо табличная функция; дополнительно могут присутствовать ARRAY JOIN и обычный JOIN (смотрите ниже). +The FROM clause specifies the table to read data from, or a subquery, or a table function; ARRAY JOIN and the regular JOIN may also be included (see below). -Вместо таблицы, может быть указан подзапрос SELECT в скобках. -В этом случае, конвейер обработки подзапроса будет встроен в конвейер обработки внешнего запроса. -В отличие от стандартного SQL, после подзапроса не нужно указывать его синоним. Для совместимости, присутствует возможность написать AS name после подзапроса, но указанное имя нигде не используется. +Instead of a table, the SELECT subquery may be specified in brackets. In this case, the subquery processing pipeline will be built into the processing pipeline of an external query. +In contrast to standard SQL, a synonym does not need to be specified after a subquery. For compatibility, it is possible to write 'AS name' after a subquery, but the specified name isn't used anywhere. -Вместо таблицы, может быть указана табличная функция. Подробнее смотрите раздел "Табличные функции". +A table function may be specified instead of a table. For more information, see the section "Table functions". -Для выполнения запроса, из соответствующей таблицы, вынимаются все столбцы, перечисленные в запросе. Из подзапросов выкидываются столбцы, не нужные для внешнего запроса. -Если в запросе не перечислено ни одного столбца (например, SELECT count() FROM t), то из таблицы всё равно вынимается один какой-нибудь столбец (предпочитается самый маленький), для того, чтобы можно было хотя бы посчитать количество строк. +To execute a query, all the columns listed in the query are extracted from the appropriate table. Any columns not needed for the external query are thrown out of the subqueries. +If a query does not list any columns (for example, SELECT count() FROM t), some column is extracted from the table anyway (the smallest one is preferred), in order to calculate the number of rows. -Модификатор FINAL может быть использован только при SELECT-е из таблицы типа CollapsingMergeTree. При указании FINAL, данные будут выбираться полностью "сколлапсированными". Стоит учитывать, что использование FINAL приводит к выбору кроме указанных в SELECT-е столбцов также столбцов, относящихся к первичному ключу. Также, запрос будет выполняться в один поток, и при выполнении запроса будет выполняться слияние данных. Это приводит к тому, что при использовании FINAL, запрос выполняется медленнее. В большинстве случаев, следует избегать использования FINAL. Подробнее смотрите раздел "Движок CollapsingMergeTree". +The FINAL modifier can be used only for a SELECT from a CollapsingMergeTree table. When you specify FINAL, data is selected fully "collapsed". Keep in mind that using FINAL leads to a selection that includes columns related to the primary key, in addition to the columns specified in the SELECT. Additionally, the query will be executed in a single stream, and data will be merged during query execution. This means that when using FINAL, the query is processed more slowly. In most cases, you should avoid using FINAL. For more information, see the section "CollapsingMergeTree engine". -Секция SAMPLE +SAMPLE clause """"""""""""" -Секция SAMPLE позволяет выполнить запрос приближённо. Приближённое выполнение запроса поддерживается только таблицами типа MergeTree* и только если при создании таблицы было указано выражение, по которому производится выборка (смотрите раздел "Движок MergeTree"). +The SAMPLE clause allows for approximated query processing. +Approximated query processing is only supported by MergeTree* type tables, and only if the sampling expression was specified during table creation (see the section "MergeTree engine"). -``SAMPLE`` имеет вид ``SAMPLE k``, где ``k`` - дробное число в интервале от 0 до 1, или ``SAMPLE n``, где n - достаточно большое целое число. +SAMPLE has the format ``SAMPLE k``, where 'k' is a decimal number from 0 to 1, or ``SAMPLE n``, where 'n' is a sufficiently large integer. -В первом случае, запрос будет выполнен по k-доле данных. Например, если указано ``SAMPLE 0.1``, то запрос будет выполнен по 10% данных. -Во втором случае, запрос будет выполнен по выборке из не более n строк. Например, если указано ``SAMPLE 10000000``, то запрос будет выполнен по не более чем 10 000 000 строкам. +In the first case, the query will be executed on 'k' percent of data. For example, ``SAMPLE 0.1`` runs the query on 10% of data. +In the second case, the query will be executed on a sample of no more than 'n' rows. For example, ``SAMPLE 10000000`` runs the query on a maximum of 10,000,000 rows. -Пример: +Example: .. code-block:: sql @@ -612,13 +608,13 @@ SELECT GROUP BY Title ORDER BY PageViews DESC LIMIT 1000 -В этом примере, запрос выполняется по выборке из 0.1 (10%) данных. Значения агрегатных функций не корректируются автоматически, поэтому для получения приближённого результата, значение count() вручную домножается на 10. +In this example, the query is executed on a sample from 0.1 (10%) of data. Values of aggregate functions are not corrected automatically, so to get an approximate result, the value 'count()' is manually multiplied by 10. -При использовании варианта вида ``SAMPLE 10000000``, нет информации, какая относительная доля данных была обработана, и на что следует домножить агрегатные функции, поэтому такой способ записи подходит не для всех случаев. +When using something like ``SAMPLE 10000000``, there isn't any information about which relative percent of data was processed or what the aggregate functions should be multiplied by, so this method of writing is not always appropriate to the situation. -Выборка с указанием относительного коэффициента является "согласованной": если рассмотреть все возможные данные, которые могли бы быть в таблице, то выборка (при использовании одного выражения сэмплирования, указанного при создании таблицы), с одинаковым коэффициентом, выбирает всегда одно и то же подмножество этих всевозможных данных. То есть, выборка из разных таблиц, на разных серверах, в разное время, делается одинаковым образом. +A sample with a relative coefficient is "consistent": if we look at all possible data that could be in the table, a sample (when using a single sampling expression specified during table creation) with the same coefficient always selects the same subset of possible data. In other words, a sample from different tables on different servers at different times is made the same way. -Например, выборка по идентификаторам посетителей, выберет из разных таблиц строки с одинаковым подмножеством всех возможных идентификаторов посетителей. Это позволяет использовать выборку в подзапросах в секции IN, а также при ручном сопоставлении результатов разных запросов с выборками. +For example, a sample of user IDs takes rows with the same subset of all the possible user IDs from different tables. This allows using the sample in subqueries in the IN clause, as well as for manually correlating results of different queries with samples. Секция ARRAY JOIN """"""""""""""""" diff --git a/docs/en/query_language/syntax.rst b/docs/en/query_language/syntax.rst index 770333e4d2b..0ed259cd008 100644 --- a/docs/en/query_language/syntax.rst +++ b/docs/en/query_language/syntax.rst @@ -1,102 +1,98 @@ -Синтаксис +Syntax --------- -В системе есть два вида парсеров: полноценный парсер SQL (recursive descent parser) и парсер форматов данных (быстрый потоковый парсер). -Во всех случаях кроме запроса INSERT, используется только полноценный парсер SQL. -В запросе INSERT используется оба парсера: +There are two types of parsers in the system: a full SQL parser (a recursive descent parser), and a data format parser (a fast stream parser). In all cases except the INSERT query, only the full SQL parser is used. +The INSERT query uses both parsers: :: INSERT INTO t VALUES (1, 'Hello, world'), (2, 'abc'), (3, 'def') -Фрагмент ``INSERT INTO t VALUES`` парсится полноценным парсером, а данные ``(1, 'Hello, world'), (2, 'abc'), (3, 'def')`` - быстрым потоковым парсером. -Данные могут иметь любой формат. При получении запроса, сервер заранее считывает в оперативку не более ``max_query_size`` байт запроса (по умолчанию, 1МБ), а всё остальное обрабатывается потоково. -Таким образом, в системе нет проблем с большими INSERT запросами, как в MySQL. +The ``INSERT INTO t VALUES`` fragment is parsed by the full parser, and the data ``(1, 'Hello, world'), (2, 'abc'), (3, 'def')`` is parsed by the fast stream parser. +Data can have any format. When a query is received, the server calculates no more than 'max_query_size' bytes of the request in RAM (by default, 1 MB), and the rest is stream parsed. This means the system doesn't have problems with large INSERT queries, like MySQL does. -При использовании формата Values в INSERT запросе может сложиться иллюзия, что данные парсятся также, как выражения в запросе SELECT, но это не так - формат Values гораздо более ограничен. +When using the Values format in an ``INSERT`` query, it may seem that data is parsed the same as expressions in a SELECT query, but this is not true. The Values format is much more limited. -Далее пойдёт речь о полноценном парсере. О парсерах форматов, смотри раздел "Форматы". +Next we will cover the full parser. For more information about format parsers, see the section "Formats". -Пробелы +Spaces ~~~~~~~ -Между синтаксическими конструкциями (в том числе, в начале и конце запроса) может быть расположено произвольное количество пробельных символов. К пробельным символам относятся пробел, таб, перевод строки, CR, form feed. +There may be any number of space symbols between syntactical constructions (including the beginning and end of a query). Space symbols include the space, tab, line break, CR, and form feed. -Комментарии +Comments ~~~~~~~~~~~ -Поддерживаются комментарии в SQL-стиле и C-стиле. -Комментарии в SQL-стиле: от ``--`` до конца строки. Пробел после ``--`` может не ставиться. -Комментарии в C-стиле: от ``/*`` до ``*/``. Такие комментарии могут быть многострочными. Пробелы тоже не обязательны. +SQL-style and C-style comments are supported. +SQL-style comments: from ``--`` to the end of the line. The space after ``--`` can be omitted. +C-style comments: from ``/*`` to ``*/``. These comments can be multiline. Spaces are not required here, either. -Ключевые слова +Keywords ~~~~~~~~~~~~~~ -Ключевые слова (например, ``SELECT``) регистронезависимы. Всё остальное (имена столбцов, функций и т. п.), в отличие от стандарта SQL, регистрозависимо. Ключевые слова не зарезервированы (а всего лишь парсятся как ключевые слова в соответствующем контексте). +Keywords (such as SELECT) are not case-sensitive. Everything else (column names, functions, and so on), in contrast to standard SQL, is case-sensitive. Keywords are not reserved (they are just parsed as keywords in the corresponding context). -Идентификаторы +Identifiers ~~~~~~~~~~~~~~ -Идентификаторы (имена столбцов, функций, типов данных) могут быть квотированными или не квотированными. -Не квотированные идентификаторы начинаются на букву латинского алфавита или подчёркивание; продолжаются на букву латинского алфавита или подчёркивание или цифру. Короче говоря, должны соответствовать регулярному выражению ``^[a-zA-Z_][0-9a-zA-Z_]*$``. Примеры: ``x, _1, X_y__Z123_.`` -Квотированные идентификаторы расположены в обратных кавычках ```id``` (также, как в MySQL), и могут обозначать произвольный (непустой) набор байт. При этом, внутри записи такого идентификатора, символы (например, символ обратной кавычки) могут экранироваться с помощью обратного слеша. Правила экранирования такие же, как в строковых литералах (см. ниже). -Рекомендуется использовать идентификаторы, которые не нужно квотировать. +Identifiers (column names, functions, and data types) can be quoted or non-quoted. +Non-quoted identifiers start with a Latin letter or underscore, and continue with a Latin letter, underscore, or number. In other words, they must match the regex ``^[a-zA-Z_][0-9a-zA-Z_]*$``. Examples: ``x``, ``_1``, ``X_y__Z123_``. +Quoted identifiers are placed in reversed quotation marks ```id``` (the same as in MySQL), and can indicate any set of bytes (non-empty). In addition, symbols (for example, the reverse quotation mark) inside this type of identifier can be backslash-escaped. Escaping rules are the same as for string literals (see below). +We recommend using identifiers that do not need to be quoted. -Литералы +Literals ~~~~~~~~ -Бывают числовые, строковые и составные литералы. +There are numeric literals, string literals, and compound literals. -Числовые литералы +Numeric literals """"""""""""""""" -Числовой литерал пытается распарситься: -- сначала как 64-битное число без знака, с помощью функции strtoull; -- если не получилось - то как 64-битное число со знаком, с помощью функции strtoll; -- если не получилось - то как число с плавающей запятой, с помощью функции strtod; -- иначе - ошибка. +A numeric literal tries to be parsed: +- first as a 64-bit signed number, using the 'strtoull' function. +- if unsuccessful, as a 64-bit unsigned number, using the 'strtoll' function. +- if unsuccessful, as a floating-point number using the 'strtod' function. +- otherwise, an error is returned. -Соответствующее значение будет иметь тип минимального размера, который вмещает значение. -Например, 1 парсится как UInt8, а 256 - как UInt16. Подробнее смотрите "Типы данных". +The corresponding value will have the smallest type that the value fits in. +For example, 1 is parsed as UInt8, but 256 is parsed as UInt16. For more information, see "Data types". -Примеры: ``1``, ``18446744073709551615``, ``0xDEADBEEF``, ``01``, ``0.1``, ``1e100``, ``-1e-100``, ``inf``, ``nan``. +Examples: ``1``, ``18446744073709551615``, ``0xDEADBEEF``, ``01``, ``0.1``, ``1e100``, ``-1e-100``, ``inf``, ``nan``. -Строковые литералы +String literals """""""""""""""""" -Поддерживаются только строковые литералы в одинарных кавычках. Символы внутри могут быть экранированы с помощью обратного слеша. Следующие escape-последовательности имеют соответствующее специальное значение: ``\b``, ``\f``, ``\r``, ``\n``, ``\t``, ``\0``, ``\a``, ``\v``, ``\xHH``. Во всех остальных случаях, последовательности вида ``\c``, где c - любой символ, преобразуется в c. Таким образом, могут быть использованы последовательности ``\'`` и ``\\``. Значение будет иметь тип String. +Only string literals in single quotes are supported. The enclosed characters can be backslash-escaped. The following escape sequences have special meanings: ``\b``, ``\f``, ``\r``, ``\n``, ``\t``, ``\0``, ``\a``, ``\v``, ``\xHH``. In all other cases, escape sequences like \c, where c is any character, are transformed to c. This means that the sequences ``\'`` and ``\\`` can be used. The value will have the String type. -Минимальный набор символов, которых вам необходимо экранировать в строковых литералах: ``'`` and ``\``. +Minimum set of symbols that must be escaped in string literal is ``'`` and ``\``. -Составные литералы +Compound literals """""""""""""""""" -Поддерживаются конструкции для массивов: ``[1, 2, 3]`` и кортежей: ``(1, 'Hello, world!', 2)``. -На самом деле, это вовсе не литералы, а выражение с оператором создания массива и оператором создания кортежа, соответственно. -Подробнее смотри в разделе "Операторы". -Массив должен состоять хотя бы из одного элемента, а кортеж - хотя бы из двух. -Кортежи носят служебное значение для использования в секции IN запроса SELECT. Кортежи могут быть получены в качестве результата запроса, но не могут быть сохранены в базу (за исключением таблиц типа Memory). +Constructions are supported for arrays: ``[1, 2, 3]`` and tuples: ``(1, 'Hello, world!', 2)``. +Actually, these are not literals, but expressions with the array creation operator and the tuple creation operator, respectively. For more information, see the section "Operators". +An array must consist of at least one item, and a tuple must have at least two items. +Tuples have a special purpose for use in the IN clause of a SELECT query. Tuples can be obtained as the result of a query, but they can't be saved to a database (with the exception of Memory-type tables). - -Функции +Functions ~~~~~~~ -Функции записываются как идентификатор со списком аргументов (возможно, пустым) в скобках. В отличие от стандартного SQL, даже в случае пустого списка аргументов, скобки обязательны. Пример: ``now()``. -Бывают обычные и агрегатные функции (смотрите раздел "Агрегатные функции"). Некоторые агрегатные функции могут содержать два списка аргументов в круглых скобках. Пример: ``quantile(0.9)(x)``. Такие агрегатные функции называются "параметрическими", а первый список аргументов называется "параметрами". Синтаксис агрегатных функций без параметров ничем не отличается от обычных функций. +Functions are written like an identifier with a list of arguments (possibly empty) in brackets. In contrast to standard SQL, the brackets are required, even for an empty arguments list. Example: ``now()``. +There are regular and aggregate functions (see the section "Aggregate functions"). Some aggregate functions can contain two lists of arguments in brackets. Example: ``quantile(0.9)(x)``. These aggregate functions are called "parametric" functions, and the arguments in the first list are called "parameters". The syntax of aggregate functions without parameters is the same as for regular functions. -Операторы +Operators ~~~~~~~~~ -Операторы преобразуются в соответствующие им функции во время парсинга запроса, с учётом их приоритета и ассоциативности. -Например, выражение ``1 + 2 * 3 + 4`` преобразуется в ``plus(plus(1, multiply(2, 3)), 4)``. -Подробнее смотрите раздел "Операторы" ниже. +Operators are converted to their corresponding functions during query parsing, taking their priority and associativity into account. +For example, the expression ``1 + 2 * 3 + 4`` is transformed to ``plus(plus(1, multiply(2, 3)), 4)``. +For more information, see the section "Operators" below. -Типы данных и движки таблиц +Data types and database table engines ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Типы данных и движки таблиц в запросе ``CREATE`` записываются также, как идентификаторы или также как функции. То есть, могут содержать или не содержать список аргументов в круглых скобках. Подробнее смотрите разделы "Типы данных", "Движки таблиц", "CREATE". +Data types and table engines in the ``CREATE`` query are written the same way as identifiers or functions. In other words, they may or may not contain an arguments list in brackets. For more information, see the sections "Data types," "Table engines," and "CREATE". -Синонимы +Synonyms ~~~~~~~~ -В запросе SELECT, в выражениях могут быть указаны синонимы с помощью ключевого слова AS. Слева от AS стоит любое выражение. Справа от AS стоит идентификатор - имя для синонима. В отличие от стандартного SQL, синонимы могут объявляться не только на верхнем уровне выражений: +In the SELECT query, expressions can specify synonyms using the AS keyword. Any expression is placed to the left of AS. The identifier name for the synonym is placed to the right of AS. As opposed to standard SQL, synonyms are not only declared on the top level of expressions: :: SELECT (1 AS n) + 2, n -В отличие от стандартного SQL, синонимы могут использоваться во всех секциях запроса, а не только ``SELECT``. +In contrast to standard SQL, synonyms can be used in all parts of a query, not just ``SELECT``. -Звёздочка +Asterisk ~~~~~~~~~ -В запросе ``SELECT``, вместо выражения может стоять звёздочка. Подробнее смотрите раздел "SELECT". +In a ``SELECT`` query, an asterisk can replace the expression. For more information, see the section "SELECT". -Выражения +Expressions ~~~~~~~~~ -Выражение представляет собой функцию, идентификатор, литерал, применение оператора, выражение в скобках, подзапрос, звёздочку; и может содержать синоним. -Список выражений - одно выражение или несколько выражений через запятую. -Функции и операторы, в свою очередь, в качестве аргументов, могут иметь произвольные выражения. +An expression is a function, identifier, literal, application of an operator, expression in brackets, subquery, or asterisk. It can also contain a synonym. +A list of expressions is one or more expressions separated by commas. +Functions and operators, in turn, can have expressions as arguments.