Как установить clickhouse на centos

Обновлено: 07.07.2024

ClickHouse is an open-source, column-oriented analytics database created by Yandex for OLAP and big data use cases. ClickHouse’s support for real-time query processing makes it suitable for applications that require sub-second analytical results. ClickHouse’s query language is a dialect of SQL that enables powerful declarative querying capabilities while offering familiarity and a smaller learning curve for the end user.

Column-oriented databases store records in blocks grouped by columns instead of rows. By not loading data for columns absent in the query, column-oriented databases spend less time reading data while completing queries. As a result, these databases can compute and return results much faster than traditional row-based systems for certain workloads, such as OLAP.

Online Analytics Processing (OLAP) systems allow for organizing large amounts of data and performing complex queries. They are capable of managing petabytes of data and returning query results quickly. In this way, OLAP is useful for work in areas like data science and business analytics.

In this tutorial, you’ll install the ClickHouse database server and client on your machine. You’ll use the DBMS for typical tasks and optionally enable remote access from another server so that you’ll be able to connect to the database from another machine. Then you’ll test ClickHouse by modeling and querying example website-visit data.

Prerequisites

  • One CentOS 7 server with a sudo enabled non-root user and firewall setup. You can follow the initial server setup tutorial to create the user and this tutorial to set up the firewall.
  • (Optional) A secondary CentOS 7 server with a sudo enabled non-root user and firewall setup. You can follow the initial server setup tutorial and the additional setup tutorial for the firewall.

Step 1 — Installing ClickHouse

In this section, you will install the ClickHouse server and client programs using yum .

First, SSH into your server by running:

Install the base dependencies by executing:

The pygpgme packages is used for adding and verifying GPG signatures while the yum-utils allows easy management of source RPMs.

Altinity, a ClickHouse consulting firm, maintains a YUM repository that has the latest version of ClickHouse. You’ll add the repository’s details to securely download validated ClickHouse packages by creating the file. To check the package contents, you can inspect the sources from which they are built at this Github project.

Create the repository details file by executing:

Next, add the following contents to the file:

Now that you’ve added the repositories, enable them with the following command:

The -q flag tells the command to run in quiet mode. The makecache command makes available the packages specified in the --enablerepo flag.

On execution, you’ll see output similar to the following:

The output confirms it has successfully verified and added the GPG key.

The clickhouse-server and clickhouse-client packages will now be available for installation. Install them with:

You’ve installed the ClickHouse server and client successfully. You’re now ready to start the database service and ensure that it’s running correctly.

Step 2 — Starting the Service

The clickhouse-server package that you installed in the previous section creates a systemd service, which performs actions such as starting, stopping, and restarting the database server. systemd is an init system for Linux to initialize and manage services. In this section you’ll start the service and verify that it is running successfully.

Start the clickhouse-server service by running:

You will see output similar to the following:

To verify that the service is running successfully, execute:

It will print an output similar to the following which denotes that the server is running properly:

You have successfully started the ClickHouse server and will now be able to use the clickhouse-client CLI program to connect to the server.

Step 3 — Creating Databases and Tables

In ClickHouse, you can create and delete databases by executing SQL statements directly in the interactive database prompt. Statements consist of commands following a particular syntax that tell the database server to perform a requested operation along with any data required. You create databases by using the CREATE DATABASE table_name syntax. To create a database, first start a client session by running the following command:

This command will log you into the client prompt where you can run ClickHouse SQL statements to perform actions such as:

Creating, updating, and deleting databases, tables, indexes, partitions, and views.

Executing queries to retrieve data that is optionally filtered and grouped using various conditions.

The --multiline flag tells the CLI to allow entering queries that span multiple lines.

In this step, with the ClickHouse client ready for inserting data, you’re going to create a database and table. For the purposes of this tutorial, you’ll create a database named test , and inside that you’ll create a table named visits that tracks website-visit durations.

Now that you’re inside the ClickHouse command prompt, create your test database by executing:

You’ll see the following output that shows that you have created the database:

A ClickHouse table is similar to tables in other relational databases; it holds a collection of related data in a structured format. You can specify columns along with their types, add rows of data, and execute different kinds of queries on tables.

UInt64 : used for storing integer values in the range 0 to 18446744073709551615.

Float64 : used for storing floating point numbers such as 2039.23, 10.5, etc.

String : used for storing variable length characters. It does not require a max length attribute since it can store arbitrary lengths.

Date : used for storing dates that follow the YYYY-MM-DD format.

DateTime : used for storing dates coupled with time and follows the YYYY-MM-DD HH:MM:SS format.

After the column definitions, you specify the engine used for the table. In ClickHouse, Engines determine the physical structure of the underlying data, the table’s querying capabilities, its concurrent access modes, and support for indexes. Different engine types are suitable for different application requirements. The most commonly used and widely applicable engine type is MergeTree .

Now that you have an overview of table creation, you’ll create a table. Start by confirming the database you’ll be modifying:

You will see the following output showing that you have switched to the test database from the default database:

The remainder of this guide will assume that you are executing statements within this database’s context.

Create your visits table by running this command:

Here’s a breakdown of what the command does. You create a table named visits that has four columns:

id : The primary key column. Similarly to other RDBMS systems, a primary key column in ClickHouse uniquely identifies a row; each row should have a unique value for this column.

duration : A float column used to store the duration of each visit in seconds. float columns can store decimal values such as 12.50.

created : A date and time column that tracks when the visit occurred.

After the column definitions, you specify MergeTree as the storage engine for the table. The MergeTree family of engines is recommended for production databases due to its optimized support for large real-time inserts, overall robustness, and query support. Additionally, MergeTree engines support sorting of rows by primary key, partitioning of rows, and replicating and sampling data.

If you intend to use ClickHouse for archiving data that is not queried often or for storing temporary data, you can use the Log family of engines to optimize for that use-case.

After the column definitions, you’ll define other table-level options. The PRIMARY KEY clause sets id as the primary key column and the ORDER BY clause will store values sorted by the id column. A primary key uniquely identifies a row and is used for efficiently accessing a single row and efficient colocation of rows.

On executing the create statement, you will see the following output:

In this section, you’ve created a database and a table to track website-visits data. In the next step, you’ll insert data into the table, update existing data, and delete that data.

Step 4 — Inserting, Updating, and Deleting Data and Columns

In this step, you’ll use your visits table to insert, update, and delete data. The following command is an example of the syntax for inserting rows into a ClickHouse table:

Now, insert a few rows of example website-visit data into your visits table by running each of the following statements:

You’ll see the following output repeated for each insert statement:

The output for each row shows that you’ve inserted it successfully into the visits table.

Now you’ll add an additional column to the visits table. When adding or deleting columns from existing tables, ClickHouse supports the ALTER syntax.

For example, the basic syntax for adding a column to a table is as follows:

Add a column named location that will store the location of the visits to a website by running the following statement:

You’ll see output similar to the following:

The output shows that you have added the location column successfully.

As of version 19.4.3, ClickHouse doesn’t support updating and deleting individual rows of data due to implementation constraints. ClickHouse has support for bulk updates and deletes, however, and has a distinct SQL syntax for these operations to highlight their non-standard usage.

The following syntax is an example for bulk updating rows:

You’ll run the following statement to update the url column of all rows that have a duration of less than 15. Enter it into the database prompt to execute:

The output of the bulk update statement will be as follows:

The output shows that your update query completed successfully. The 0 rows in set in the output denotes that the query did not return any rows; this will be the case for any update and delete queries.

To test deleting data, run the following statement to remove all rows that have a duration of less than 5:

The output of the bulk delete statement will be similar to:

The output confirms that you have deleted the rows with a duration of less than five seconds.

Delete the location column you added previously by running the following:

The DROP COLUMN output confirming that you have deleted the column will be as follows:

Now that you’ve successfully inserted, updated, and deleted rows and columns in your visits table, you’ll move on to query data in the next step.

Step 5 — Querying Data

ClickHouse’s query language is a custom dialect of SQL with extensions and functions suited for analytics workloads. In this step, you’ll run selection and aggregation queries to retrieve data and results from your visits table.

Selection queries allow you to retrieve rows and columns of data filtered by conditions that you specify, along with options such as the number of rows to return. You can select rows and columns of data using the SELECT syntax. The basic syntax for SELECT queries is:

You will see the following output:

The output has returned two rows that match the conditions you specified. Now that you’ve selected values, you can move to executing aggregation queries.

count : returns the count of rows matching the conditions specified.

sum : returns the sum of selected column values.

avg : returns the average of selected column values.

Some ClickHouse-specific aggregate functions include:

uniq : returns an approximate number of distinct rows matched.

topK : returns an array of the most frequent values of a specific column using an approximation algorithm.

To demonstrate the execution of aggregation queries, you’ll calculate the total duration of visits by running the sum query:

You will see output similar to the following:

Now, calculate the top two URLs by executing:

You will see output similar to the following:

Now that you have successfully queried your visits table, you’ll delete tables and databases in the next step.

Step 6 — Deleting Tables and Databases

In this section, you’ll delete your visits table and test database.

The syntax for deleting tables follows this example:

To delete the visits table, run the following statement:

You will see the following output declaring that you’ve deleted the table successfully:

You can delete databases using the DROP database table_name syntax. To delete the test database, execute the following statement:

The resulting output shows that you’ve deleted the database successfully:

You’ve deleted tables and databases in this step. Now that you’ve created, updated, and deleted databases, tables, and data in your ClickHouse instance, you’ll enable remote access to your database server in the next section.

Step 7 — Setting Up Firewall Rules (Optional)

If you intend to only use ClickHouse locally with applications running on the same server, or do not have a firewall enabled on your server, you don’t need to complete this section. If instead, you’ll be connecting to the ClickHouse database server remotely, you should follow this step.

Currently your server has a firewall enabled that disables your public IP address accessing all ports. You’ll complete the following two steps to allow remote access:

If you are inside the database prompt, exit it by typing CTRL+D .

Edit the configuration file by executing:

Then uncomment the line containing <!-- <listen_host>0.0.0.0</listen_host> --> , like the following file:

Save the file and exit vi . For the new configuration to apply restart the service by running:

You will see the following output from this command:

Add the remote server’s IP to zone called public:

You will see the following output for both commands that shows that you’ve enabled access to both ports:

Now that you have added the rules, reload the firewall for the changes to take effect:

This command will output a success message as well. ClickHouse will now be accessible from the IP that you added. Feel free to add additional IPs such as your local machine’s address if required.

To verify that you can connect to the ClickHouse server from the remote machine, first follow the steps in Step 1 of this tutorial on the second server and ensure that you have the clickhouse-client installed on it.

Now that you have logged into the second server, start a client session by executing:

You will see the following output that shows that you have connected successfully to the server:

In this step, you’ve enabled remote access to your ClickHouse database server by adjusting your firewall rules.

Conclusion

You have successfully set up a ClickHouse database instance on your server and created a database and table, added data, performed queries, and deleted the database. Within ClickHouse’s documentation you can read about their benchmarks against other open-source and commercial analytics databases and general reference documents. Further features ClickHouse offers includes distributed query processing across multiple servers to improve performance and protect against data loss by storing data over different shards.

ClickHouse может работать на любой операционной системе Linux, FreeBSD или Mac OS X с архитектурой процессора x86_64, AArch64 или PowerPC64LE.

Предварительно собранные пакеты компилируются для x86_64 и используют набор инструкций SSE 4.2, поэтому, если не указано иное, его поддержка в используемом процессоре, становится дополнительным требованием к системе. Вот команда, чтобы проверить, поддерживает ли текущий процессор SSE 4.2:

Чтобы запустить ClickHouse на процессорах, которые не поддерживают SSE 4.2, либо имеют архитектуру AArch64 или PowerPC64LE, необходимо самостоятельно собрать ClickHouse из исходного кода с соответствующими настройками конфигурации.

Доступные варианты установки

Из DEB пакетов

Яндекс рекомендует использовать официальные скомпилированные deb пакеты для Debian или Ubuntu. Для установки пакетов выполните:

Чтобы использовать различные версии ClickHouse в зависимости от ваших потребностей, вы можете заменить stable на lts или testing .

Также вы можете вручную скачать и установить пакеты из репозитория.

Пакеты

  • clickhouse-common-static — Устанавливает исполняемые файлы ClickHouse.
  • clickhouse-server — Создает символические ссылки для clickhouse-server и устанавливает конфигурационные файлы.
  • clickhouse-client — Создает символические ссылки для clickhouse-client и других клиентских инструментов и устанавливает конфигурационные файлы clickhouse-client .
  • clickhouse-common-static-dbg — Устанавливает исполняемые файлы ClickHouse собранные с отладочной информацией.

Если вам нужно установить ClickHouse определенной версии, вы должны установить все пакеты одной версии:
sudo apt-get install clickhouse-server=21.8.5.7 clickhouse-client=21.8.5.7 clickhouse-common-static=21.8.5.7

Из RPM пакетов

Команда ClickHouse в Яндексе рекомендует использовать официальные предкомпилированные rpm пакеты для CentOS, RedHat и всех остальных дистрибутивов Linux, основанных на rpm.

Сначала нужно подключить официальный репозиторий:

Для использования наиболее свежих версий нужно заменить stable на testing (рекомендуется для тестовых окружений). Также иногда доступен prestable .

Для, собственно, установки пакетов необходимо выполнить следующие команды:

Из Tgz архивов

Команда ClickHouse в Яндексе рекомендует использовать предкомпилированные бинарники из tgz архивов для всех дистрибутивов, где невозможна установка deb и rpm пакетов.

Из Docker образа

Для запуска ClickHouse в Docker нужно следовать инструкции на Docker Hub. Внутри образов используются официальные deb пакеты.

Из единого бинарного файла

Из исполняемых файлов для нестандартных окружений

Для других операционных систем и архитектуры AArch64 сборки ClickHouse предоставляются в виде кросс-компилированного бинарного файла из последнего коммита ветки master (с задержкой в несколько часов).

После скачивания можно воспользоваться clickhouse client для подключения к серверу или clickhouse local для обработки локальных данных.

Чтобы установить ClickHouse в рамках всей системы (с необходимыми конфигурационными файлами, настройками пользователей и т.д.), выполните sudo ./clickhouse install . Затем выполните команды clickhouse start (чтобы запустить сервер) и clickhouse-client (чтобы подключиться к нему).

Данные сборки не рекомендуются для использования в рабочей среде, так как они недостаточно тщательно протестированы. Также в них присутствуют не все возможности ClickHouse.

Из исходного кода

Для компиляции ClickHouse вручную, используйте инструкцию для Linux или Mac OS X.

Можно скомпилировать пакеты и установить их, либо использовать программы без установки пакетов. Также при ручой сборке можно отключить необходимость поддержки набора инструкций SSE 4.2 или собрать под процессоры архитектуры AArch64.

Для работы собранного вручную сервера необходимо создать директории для данных и метаданных, а также сделать их chown для желаемого пользователя. Пути к этим директориям могут быть изменены в конфигурационном файле сервера (src/programs/server/config.xml), по умолчанию используются следующие:

На Gentoo для установки ClickHouse из исходного кода можно использовать просто emerge clickhouse .

Запуск

Для запуска сервера в качестве демона, выполните:

Смотрите логи в директории /var/log/clickhouse-server/ .

Если сервер не стартует, проверьте корректность конфигурации в файле /etc/clickhouse-server/config.xml

Также можно запустить сервер вручную из консоли:

При этом, лог будет выводиться в консоль, что удобно для разработки.
Если конфигурационный файл лежит в текущей директории, то указывать параметр --config-file не требуется, по умолчанию будет использован файл ./config.xml .

После запуска сервера, соединиться с ним можно с помощью клиента командной строки:

По умолчанию он соединяется с localhost:9000, от имени пользователя default без пароля. Также клиент может быть использован для соединения с удалённым сервером с помощью аргумента --host .

Терминал должен использовать кодировку UTF-8.

Более подробная информация о клиенте располагается в разделе «Клиент командной строки».

Пример проверки работоспособности системы:

Поздравляем, система работает!

Для дальнейших экспериментов можно попробовать загрузить один из тестовых наборов данных или пройти пошаговое руководство для начинающих.

ClickHouse can run on any Linux, FreeBSD, or Mac OS X with x86_64, AArch64, or PowerPC64LE CPU architecture.

Official pre-built binaries are typically compiled for x86_64 and leverage SSE 4.2 instruction set, so unless otherwise stated usage of CPU that supports it becomes an additional system requirement. Here’s the command to check if current CPU has support for SSE 4.2:

To run ClickHouse on processors that do not support SSE 4.2 or have AArch64 or PowerPC64LE architecture, you should build ClickHouse from sources with proper configuration adjustments.

Available Installation Options

From DEB Packages

It is recommended to use official pre-compiled deb packages for Debian or Ubuntu. Run these commands to install packages:

You can replace stable with lts or testing to use different release trains based on your needs.

You can also download and install packages manually from here.

Packages

  • clickhouse-common-static — Installs ClickHouse compiled binary files.
  • clickhouse-server — Creates a symbolic link for clickhouse-server and installs the default server configuration.
  • clickhouse-client — Creates a symbolic link for clickhouse-client and other client-related tools. and installs client configuration files.
  • clickhouse-common-static-dbg — Installs ClickHouse compiled binary files with debug info.

If you need to install specific version of ClickHouse you have to install all packages with the same version:
sudo apt-get install clickhouse-server=21.8.5.7 clickhouse-client=21.8.5.7 clickhouse-common-static=21.8.5.7

From RPM Packages

It is recommended to use official pre-compiled rpm packages for CentOS, RedHat, and all other rpm-based Linux distributions.

First, you need to add the official repository:

If you want to use the most recent version, replace stable with testing (this is recommended for your testing environments). prestable is sometimes also available.

Then run these commands to install packages:

You can also download and install packages manually from here.

From Tgz Archives

It is recommended to use official pre-compiled tgz archives for all Linux distributions, where installation of deb or rpm packages is not possible.

From Docker Image

To run ClickHouse inside Docker follow the guide on Docker Hub. Those images use official deb packages inside.

Single Binary

From Precompiled Binaries for Non-Standard Environments

For non-Linux operating systems and for AArch64 CPU arhitecture, ClickHouse builds are provided as a cross-compiled binary from the latest commit of the master branch (with a few hours delay).

After downloading, you can use the clickhouse client to connect to the server, or clickhouse local to process local data.

Run sudo ./clickhouse install if you want to install clickhouse system-wide (also with needed configuration files, configuring users etc.). After that run clickhouse start commands to start the clickhouse-server and clickhouse-client to connect to it.

These builds are not recommended for use in production environments because they are less thoroughly tested, but you can do so on your own risk. They also have only a subset of ClickHouse features available.

From Sources

To manually compile ClickHouse, follow the instructions for Linux or Mac OS X.

You can compile packages and install them or use programs without installing packages. Also by building manually you can disable SSE 4.2 requirement or build for AArch64 CPUs.

On Gentoo, you can just use emerge clickhouse to install ClickHouse from sources.

Launch

To start the server as a daemon, run:

If you do not have service command, run as

See the logs in the /var/log/clickhouse-server/ directory.

If the server does not start, check the configurations in the file /etc/clickhouse-server/config.xml .

You can also manually launch the server from the console:

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 do not need to specify the --config-file parameter. By default, it uses ./config.xml .

ClickHouse supports access restriction settings. They are located in the users.xml file (next to config.xml ).
By default, access is allowed from anywhere for the default user, without a password. See user/default/networks .
For more information, see the section “Configuration Files”.

After launching server, you can use the command-line client to connect to it:

By default, it connects to localhost:9000 on behalf of the user default without a password. It can also be used to connect to a remote server using --host argument.

The terminal must use UTF-8 encoding.
For more information, see the section “Command-line client”.

Congratulations, the system works!

To continue experimenting, you can download one of the test data sets or go through tutorial.

Сборка ClickHouse поддерживается на Linux, FreeBSD, Mac OS X.

Если вы используете Windows

Если вы используете 32-битную систему

ClickHouse не работает и не собирается на 32-битных системах. Получите доступ к 64-битной системе и продолжайте.

Создание репозитория на GitHub

Для работы с репозиторием ClickHouse, вам потребуется аккаунт на GitHub. Наверное, он у вас уже есть.

Для работы с git репозиториями, установите git .

В Ubuntu выполните в терминале:

Клонирование репозитория на рабочую машину

Затем вам потребуется загрузить исходники для работы на свой компьютер. Это называется «клонирование репозитория», потому что создаёт на вашем компьютере локальную копию репозитория, с которой вы будете работать.

Выполните в терминале:

Замените первое вхождение слова ClickHouse в команде для git на имя вашего аккаунта на GitHub.

Эта команда создаст директорию ClickHouse, содержащую рабочую копию проекта.

Необходимо, чтобы путь к рабочей копии не содержал пробелы в именах директорий. Это может привести к проблемам в работе системы сборки.

Обратите внимание, что репозиторий ClickHouse использует submodules. Так называются ссылки на дополнительные репозитории (например, внешние библиотеки, от которых зависит проект). Это значит, что при клонировании репозитория, следует указывать ключ --recursive , как в примере выше. Если репозиторий был клонирован без submodules, то для их скачивания, необходимо выполнить:

Проверить наличие submodules можно с помощью команды git submodule status .

Как правило это означает, что отсутствуют ssh ключи для соединения с GitHub. Ключи расположены в директории

/.ssh . В интерфейсе GitHub, в настройках, необходимо загрузить публичные ключи, чтобы он их понимал.

Этот вариант не подходит для отправки изменений на сервер. Вы можете временно его использовать, а затем добавить ssh ключи и заменить адрес репозитория с помощью команды git remote .

Вы можете также добавить для своего локального репозитория адрес оригинального репозитория Яндекса, чтобы притягивать оттуда обновления:

После этого, вы сможете добавлять в свой репозиторий обновления из репозитория Яндекса с помощью команды git pull upstream master .

Работа с сабмодулями Git

Работа с сабмодулями git может быть достаточно болезненной. Следующие команды позволят содержать их в порядке:

Следующие команды помогут сбросить все сабмодули в изначальное состояние (!ВНИМАНИЕ! - все изменения в сабмодулях будут утеряны):

Система сборки

ClickHouse использует систему сборки CMake и Ninja.

CMake - генератор задач сборки.
Ninja - система запуска сборочных задач.

Для установки на Ubuntu или Debian, Mint, выполните sudo apt install cmake ninja-build .

Для установки на CentOS, RedHat, выполните sudo yum install cmake ninja-build .

Если у вас Arch или Gentoo, то вы сами знаете, как установить CMake.

Для установки CMake и Ninja на Mac OS X, сначала установите Homebrew, а затем, с помощью него, установите всё остальное.

Необязательные внешние библиотеки

ClickHouse использует для сборки некоторое количество внешних библиотек. Но ни одну из них не требуется отдельно устанавливать, так как они собираются вместе с ClickHouse, из исходников, которые расположены в submodules. Посмотреть набор этих библиотек можно в директории contrib.

Компилятор C++

В качестве компилятора C++ поддерживается Clang начиная с версии 11.

Впрочем, наша среда continuous integration проверяет около десятка вариантов сборки, включая gcc, но сборка с помощью gcc непригодна для использования в продакшене.

На Ubuntu и Debian вы можете использовать скрипт для автоматической установки (см. официальный сайт)

Сборка под Mac OS X поддерживается только для компилятора Clang. Чтобы установить его выполните brew install llvm

Процесс сборки

Теперь вы готовы к сборке ClickHouse. Для размещения собранных файлов, рекомендуется создать отдельную директорию build внутри директории ClickHouse:

Вы можете иметь несколько разных директорий (build_release, build_debug) для разных вариантов сборки.

Находясь в директории build, выполните конфигурацию сборки с помощью CMake.
Перед первым запуском необходимо выставить переменные окружения, отвечающие за выбор компилятора.

Переменная CC отвечает за компилятор C (сокращение от слов C Compiler), переменная CXX отвечает за выбор компилятора C++ (символ X - это как плюс, но положенный набок, ради того, чтобы превратить его в букву). При получении ошибки типа Could not find compiler set in environment variable CC: clang необходимо указать в значениях для переменных CC и CXX явную версию компилятора, например, clang-12 и clang++-12 .

Для более быстрой сборки, можно использовать debug вариант - сборку без оптимизаций. Для этого, укажите параметр -D CMAKE_BUILD_TYPE=Debug :

В случае использования на разработческой машине старого HDD или SSD, а также при желании использовать меньше места для артефактов сборки можно использовать следующую команду:

При этом надо учесть, что получаемые в результате сборки исполнимые файлы будут динамически слинкованы с библиотеками, и поэтому фактически станут непереносимыми на другие компьютеры (либо для этого нужно будет предпринять значительно больше усилий по сравнению со статической сборкой). Плюсом же в данном случае является значительно меньшее время сборки (это проявляется не на первой сборке, а на последующих, после внесения изменений в исходный код - тратится меньшее время на линковку по сравнению со статической сборкой) и значительно меньшее использование места на жёстком диске (экономия более, чем в 3 раза по сравнению со статической сборкой). Для целей разработки, когда планируются только отладочные запуски на том же компьютере, где осуществлялась сборка, это может быть наиболее удобным вариантом.

Вы можете изменить вариант сборки, выполнив новую команду в директории build.

Запустите ninja для сборки:

В этом примере собираются только нужные в первую очередь программы.

Если вы хотите собрать все программы (утилиты и тесты), то запустите ninja без параметров:

Для полной сборки требуется около 30 GB свободного места на диске или 15 GB для сборки только основных программ.

При наличии небольшого количества оперативной памяти на компьютере, следует ограничить количество параллельных задач с помощью параметра -j :

На машинах с 4 GB памяти, рекомендуется указывать значение 1, а если памяти до 8 GB, укажите значение 2.

В случае успешного запуска, вы увидите прогресс сборки - количество обработанных задач и общее количество задач.

В случае получения ошибок вида error: variable 'y' set but not used [-Werror,-Wunused-but-set-variable] ножно попробовать использовать другую версию компилятора сlang. Например, на момент написания данного текста описанная выше команда по установке clang для Ubuntu 20.04 по-умолчанию устанавливает clang-13, с которым возникает эта ошибка. Для решения проблемы можно установить clang-12 с помощью команд:

И далее использовать именно его, указав соответствующую версию при установке переменных окружения CC и CXX перед вызовом cmake.

При успешной сборке, вы получите готовый исполняемый файл ClickHouse/build/programs/clickhouse :

Запуск собранной версии ClickHouse

Для запуска сервера из под текущего пользователя, с выводом логов в терминал и с использованием примеров конфигурационных файлов, расположенных в исходниках, перейдите в директорию ClickHouse/programs/server/ (эта директория находится не в директории build) и выполните:

В этом случае, ClickHouse будет использовать конфигурационные файлы, расположенные в текущей директории. Вы можете запустить clickhouse server из любой директории, передав ему путь к конфигурационному файлу в аргументе командной строки --config-file .

Для подключения к ClickHouse с помощью clickhouse-client, в соседнем терминале, зайдите в директорию ClickHouse/build/programs/ и выполните ./clickhouse client .

Вы можете заменить собранным вами ClickHouse продакшен версию, установленную в системе. Для этого, установите ClickHouse на свою машину по инструкции с официального сайта. Затем выполните:

Обратите внимание, что clickhouse-client , clickhouse-server и другие, являеются симлинками на общий бинарник clickhouse .

Также вы можете запустить собранный вами ClickHouse с конфигурационным файлом системного ClickHouse:

Среда разработки

Если вы не знаете, какую среду разработки использовать, то рекомендуется использовать CLion. CLion является платным ПО, но его можно использовать бесплатно в течение пробного периода. Также он бесплатен для учащихся. CLion можно использовать как под Linux, так и под Mac OS X.

Также в качестве среды разработки, вы можете использовать KDevelop или QTCreator. KDevelop - очень удобная, но нестабильная среда разработки. Если KDevelop вылетает через небольшое время после открытия проекта, вам следует нажать на кнопку «Stop All» как только он открыл список файлов проекта. После этого, KDevelop можно будет использовать.

В качестве простых редакторов кода можно использовать Sublime Text или Visual Studio Code или Kate (все варианты доступны под Linux).

На всякий случай заметим, что CLion самостоятельно создаёт свою build директорию, самостоятельно выбирает тип сборки debug по-умолчанию, для конфигурации использует встроенную в CLion версию CMake вместо установленного вами, а для запуска задач использует make вместо ninja (но при желании начиная с версии CLion 2019.3 EAP можно настроить использование ninja, см. подробнее тут). Это нормально, просто имейте это ввиду, чтобы не возникало путаницы.

Написание кода

Тестовые данные

Разработка ClickHouse часто требует загрузки реалистичных наборов данных. Особенно это важно для тестирования производительности. Специально для вас мы подготовили набор данных, представляющий собой анонимизированные данные Яндекс.Метрики. Загрузка этих данных потребует ещё 3 GB места на диске. Для выполнения большинства задач разработки, загружать эти данные не обязательно.

Создание Pull Request

Откройте свой форк репозитория в интерфейсе GitHub. Если вы вели разработку в бранче, выберите этот бранч. На странице будет доступна кнопка «Pull request». По сути, это означает «создать заявку на принятие моих изменений в основной репозиторий».

Pull request можно создать, даже если работа над задачей ещё не завершена. В этом случае, добавьте в его название слово «WIP» (work in progress). Название можно будет изменить позже. Это полезно для совместного просмотра и обсуждения изменений, а также для запуска всех имеющихся тестов. Введите краткое описание изменений - впоследствии, оно будет использовано для релизных changelog.

Тесты будут запущены, как только сотрудники Яндекса поставят для pull request тег «Can be tested». Результаты первых проверок (стиль кода) появятся уже через несколько минут. Результаты сборки появятся примерно через пол часа. Результаты основного набора тестов будут доступны в пределах часа.

Система подготовит сборки ClickHouse специально для вашего pull request. Для их получения, нажмите на ссылку «Details» у проверки «Clickhouse build check». Там вы сможете найти прямые ссылки на собранные .deb пакеты ClickHouse, которые, при желании, вы даже сможете установить на свои продакшен серверы (если не страшно).

Вероятнее всего, часть сборок не будет успешной с первого раза. Ведь мы проверяем сборку кода и gcc и clang, а при сборке с помощью clang включаются почти все существующие в природе warnings (всегда с флагом -Werror ). На той же странице, вы сможете найти логи сборки - вам не обязательно самому собирать ClickHouse всеми возможными способами.

Читайте также: