Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
Appearance settings
The premise
With the development of current services, the amount of data in several business systems began to expand dramatically. Before, I used relational database MySQL to conduct a data warehouse modeling, and found that after the amount of data came up, a large number of JOIN operations were still a little unbearable after improving the configuration of cloud MySQL. In addition, I developed a label service based on relational database design. Daily full label data (unavoidable Cartesian product) single table exceeds 5000W. At present, the user ID-based segmentation with multi-process processing method has temporarily delayed the deterioration of performance, but considering the near future, we still need to build a small data platform. The system of Hadoop is too large, with too many components and high learning costs of hardware and software, which cannot be mastered overnight by all members of a small team. With all these factors in mind, ClickHouse is a dark technology that needs to be invoked to see if it can get out of the way.
Software version
ClickHouse is not covered here, but is fully documented at https://clickhouse.tech. In Windows10, you can install Docker directly and run ClickHouse images directly using hyper-V features. The software required for setting up the development environment is listed below:
software | version | note |
---|---|---|
Windows |
10 |
Make sure you use itWindows10 And turn it onHyper-V In order to useDocker |
Docker Desktop |
any | Docker theWindows The desktop version |
ClickHouse Server |
X 20.3. |
Direct pulllatest The mirror image of |
ClickHouse Client |
X 20.3. |
Direct pulllatest The mirror image of |
Cmder |
The latest version | Optional, used to replace the unusable console that comes with it |
In Windows10, you can enable the Hyper-V feature by running the following command: Control Panel -> Programs -> Enable or Disable Windows Features -> Hyper-V
Then the Docker official site https://www.docker.com/get-started child pages can find Docker Desktop download entry:
After installation, Docker Desktop will automatically start with the system, and the software interface is as follows:
Install and use ClickHouse
Note that you need to have a preliminary understanding of ClickHouse’s core directory before starting the container installation.
Mirror pull and core directory
Download the images of ClickHouse Server and ClickHouse Client:
docker pull yandex/clickhouse-server
docker pull yandex/clickhouse-client
Copy the code
After downloading, the following prompt will be displayed:
Check this out with Docker Images:
λ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
yandex/clickhouse-server latest c85f84ea6550 10 days ago 515MB
yandex/clickhouse-client latest f94470cc9cd9 10 days ago 488MB
Copy the code
Both images are actually wrapped in a tiny Ubuntu system, so the container can be used as if it were a Linux system. The core directory portion of ClickHouse Server in the container is as follows:
/etc/clickhouse-server
This is:ClickHouse Server
Default configuration file directory, including global configurationconfig.xml
And user configurationusers.xml
And so on./var/lib/clickhouse
This is:ClickHouse Server
Default data storage directory./var/log/clickhouse-server
This is:ClickHouse Server
Default log output directory.
In order to facilitate configuration management, data viewing and log searching, the above three directories can be directly mapped to the specific directory of the host computer. The author has done the following mapping in this development machine:
Docker container directory | Host directory |
---|---|
/etc/clickhouse-server |
E:/Docker/images/clickhouse-server/single/conf |
/var/lib/clickhouse |
E:/Docker/images/clickhouse-server/single/data |
/var/log/clickhouse-server |
E:/Docker/images/clickhouse-server/single/log |
A few points to note before starting ClickHouse Server:
ClickHouse Server
The service itself depends on three ports, whose default value is9000
(TCP
Protocol),8123
(HTTP
Agreement) and9009
(Cluster data replication), the mapping to the host should be one-to-one, so you need to ensure that the three ports on the host are not occupied and can be usedDocker
The parameters of the-p
Specifies the port mapping between the container and the host.ClickHouse Server
The number of file handles in the container system needs to be modifiedulimit nofile
, you can useDocker
parameter--ulimit nofile=262144:262144
Specifies the number of file handles.- There’s a technique that you can use. Use
Docker
the--rm
Parameter to create a temporary container, obtained first/etc/clickhouse-server
Directory configuration file, passDocker cp container directory Host directory
Command to copy the container configuration file to the host directory. After the container is stopped, it will be deleted directly, so that the host configuration file template can be retained.
Temporary container copy configuration
Docker run –rm -d –name=temp-clickhouse-server Yandex /clickhouse-server After success, copy the container’s config. XML and users. XML files to the host using the following command:
docker cp temp-clickhouse-server:/etc/clickhouse-server/config.xml E:/Docker/images/clickhouse-server/single/conf/config.xml
docker cp temp-clickhouse-server:/etc/clickhouse-server/users.xml E:/Docker/images/clickhouse-server/single/conf/users.xml
After these two commands are executed, you can see that config.xml and users.xml have been generated in the host’s disk directory. Then you need to do a few configurations:
- create
default
Password of the account. - Create a new one
root
Account. - Open client listening
Host
, avoid later useJDBC
Client orClickHouse Client
Cannot connect whenClickHouse Server
.
Docker exec-it temp-clickhouse-server /bin/bash:
PASSWORD=$(base64 < /dev/urandom | head -c8); echo "default"; echo -n "default" | sha256sum | tr -d '-'
PASSWORD=$(base64 < /dev/urandom | head -c8); echo "root"; echo -n "root" | sha256sum | tr -d '-'
root@607c5abcc132:/# PASSWORD=$(base64 < /dev/urandom | head -c8); echo "default"; echo -n "default" | sha256sum | tr -d '-'
default
37a8eec1ce19687d132fe29051dca629d164e2c4958ba141d5f4133a33f0688f
root@607c5abcc132:/# PASSWORD=$(base64 < /dev/urandom | head -c8); echo "root"; echo -n "root" | sha256sum | tr -d '-'
root
4813494d137e1631bba301d5acab6e7bb7aa74ce1185d456565ef51d737677b2
Copy the code
This gives you the SHA256 digest of the passwords for the default:default and root:root accounts. Modify the users.xml file on the host:
Then modify the config.xml file on the host:
Finally, the temporary container is stopped and destroyed with the Docker Stop temp-clickhouse-server.
Run the ClickHouse service
Then create and run an instance of the ClickHouse Server container using the following command (make sure config.xml and users.xml already exist) :
Name and container name: docker run -d --name=single-clickhouse-server Port mapping: -p 8123:8123 -p 9000:9000 -p 9009:9009 Number of file handles: - the ulimit nofiles = 262144-262144 data directory mapping: - v E: / Docker/images/clickhouse - server/use/data: / var/lib/clickhouse: rw configuration directory mapping: - v E: / Docker/images/clickhouse - server/use/conf: / etc/clickhouse - server: rw log directory mapping: - v E: / Docker/images/clickhouse - server/use/log: / var/log/clickhouse - server: rw mirror: another dual/clickhouse - serverCopy the code
Docker run -d –name=single-clickhouse-server -p 8123:8123 -p 9000:9000 -p 9009:9009 –ulimit nofile=262144:262144 -v E:/Docker/images/clickhouse-server/single/data:/var/lib/clickhouse:rw -v E:/Docker/images/clickhouse-server/single/conf:/etc/clickhouse-server:rw -v E: / Docker/images/clickhouse – server/use/log: / var/log/clickhouse – server: rw another dual/clickhouse – server.
After executing the command above, the Docker Desktop will have several pop-ups confirming whether to share the host directory. Simply press the Share it button.
Finally, the native command line Client, ClickHouse Client, is used to connect. Use the docker run-it –rm –link single-clickhouse-server:clickhouse-server yandex/ clickhouse-client-uroot –password command Root – host clickhouse – server:
λ docker run-it --rm --link single-clickhouse-server:clickhouse-server yandex/ clickhouse-client-uroot --password root -- Host Clickhouse-server Clickhouse Client Version 20.10.3.30 (Official build). Connecting to Clickhouse-server :9000 AS Connected to ClickHouse server version 20.10.3 revision 54441.f5abc88ff7e4 :) select 1; SELECT 1 ┌ ─ ─ 1 ┐ │ │ 1 └ ─ ─ ─ ┘ 1 rows in the set. The Elapsed: 0.004 SEC.Copy the code
The next time your computer restarts the ClickHouse Server container and the container does not start, simply use the command docker (re)start single-clickhouse-server to pull up the container instance.
Connect to the ClickHouse service using JDBC
ClickHouse currently has three JDBC drivers:
clickhouse-jdbc
(Official) : The address ishttps://github.com/ClickHouse/clickhouse-jdbc
, the current version is based onApache Http Client
The implementation.ClickHouse-Native-JDBC
(Third party) : The address ishttps://github.com/housepower/ClickHouse-Native-JDBC
Based on theSocket
The implementation.clickhouse4j
(Third party) : The address ishttps://github.com/blynkkk/clickhouse4j
Lighter than the official driver.
To be honest, it is a little embarrassing that the official driver package does not connect with TCP private protocol stack, but uses HTTP protocol for interaction. I do not know how much performance will be reduced, but based on the thinking of “official is better”, I still choose the official driver package for Demo demonstration. Introducing clickHouse-JDBC dependencies:
<dependency>
<groupId>ru.yandex.clickhouse</groupId>
<artifactId>clickhouse-jdbc</artifactId>
<version>0.2.4</version>
</dependency>
Copy the code
Write a test class:
public class ClickHouseTest {
@Test
public void testCh(a) throws Exception {
ClickHouseProperties props = new ClickHouseProperties();
props.setUser("root");
props.setPassword("root");
// There is a global default database when no database is created
ClickHouseDataSource dataSource = new ClickHouseDataSource("jdbc:clickhouse://localhost:8123/default", props);
ClickHouseConnection connection = dataSource.getConnection();
ClickHouseStatement statement = connection.createStatement();
// Create a table. The table engine is Memory. This type of table will be deleted automatically after the service restarts
boolean execute = statement.execute("CREATE TABLE IF NOT EXISTS t_test(id UInt64,name String) ENGINE = Memory");
if (execute) {
System.out.println(Table default.t_test created successfully);
} else {
System.out.println(Table default.t_test already exists);
}
ResultSet rs = statement.executeQuery("SHOW TABLES");
List<String> tables = Lists.newArrayList();
while (rs.next()) {
tables.add(rs.getString(1));
}
System.out.println("Table in default database :" + tables);
PreparedStatement ps = connection.prepareStatement("INSERT INTO t_test(*) VALUES (? ,?) . (? ,?) ");
ps.setLong(1.1L);
ps.setString(2."throwable");
ps.setLong(3.2L);
ps.setString(4."doge");
ps.execute();
statement = connection.createStatement();
rs = statement.executeQuery("SELECT * FROM t_test");
while (rs.next()) {
System.out.println(String.format("Result,id:%s,name:%s", rs.getLong("id"), rs.getString("name"))); }}}Copy the code
The result is as follows:
Table default.t_test already exists # < Default Table in the database :[t_test] Query result,id:1,name:throwable query result, ID :2,name:dogeCopy the code
summary
After the ClickHouse development environment is set up, you will learn the basic syntax of ClickHouse, the features and usage scenarios of the various engines, and clustering (sharding and multiple copies).
References:
https://clickhouse.tech
remind
After a direct power outage, I found that the ClickHouse service in Docker was successfully restarted, but the error log output File not found, causing all clients to fail to connect to the service. The initial judgment is that metadata and actual stored data caused by the “power failure” caused by inconsistency. So proposal in a development environment to turn it off before you enter the container calls the service clickhouse – stop server, and then in the host machine call docker stop container name | containers ID stop to shut down, Otherwise, you need to recursively delete all the files in the Store directory in the data directory to restart ClickHouse Server and use it properly (this is a very rude method and has a high chance of directly causing data loss, so be careful).
(C-2-D E-A-20201108)
Personal blog
- Throwable’s Blog
Уровень сложностиСредний
Время на прочтение9 мин
Количество просмотров20K
Базы данных — один из важнейших инструментов в арсенале аналитика. А ClickHouse — это высокопроизводительная аналитическая СУБД, которая заточена на то, чтобы переваривать огромные массивы данных. Поэтому полезно будет разобраться, как самостоятельно установить ClickHouse в Yandex Cloud или на VDS-сервере, как создать пользователей и активировать веб-интерфейс и доступ по сети. Этим и займемся в статье.
Дисклеймер: Я Женя Кузнецов, увлеченный диджитал-стратег, который любит копаться в данных и визуализировать их. Но я не инженер данных, поэтому могу вольно интерпретировать некоторые понятия — хотя факты стараюсь проверять.
Зачем мне впервые понадобилась база данных?
Дело в том, как устроена Яндекс Метрика и коннекторы к ней из Yandex DataLens.
В Logs API Яндекс Метрики данные о достижении целей собраны в несколько массивов:
-
ym:s:goalsID
— номера целей, достигнутых за данный визит; -
ym:s:goalsSerialNumber
— порядковые номера достижений цели с конкретным идентификатором; -
ym:s:goalsDateTime
— время достижения каждой цели (в часовом поясе UTC+3).
А в коннекторе DataLens к Яндекс Метрике доступны только:
-
общее количество достижений любой цели,
-
конверсия в достижение любой цели,
-
текстовое поле с названием достигнутой цели.
И если при построении чарта сделать фильтрацию по этому тексту (т. е. попытаться вывести количество достижений цели и отфильтровать их по названию достигнутой цели) — то данные с метрикой разойдутся, причем значительно.
Также не получится посчитать и производные метрики вроде конверсии. Данные по отдельным целям доступны только в Logs Api Яндекс Метрики.
Есть лайфхак, как обойти это, не выгружая данные, но он работает, только если нужно отслеживать какую-то одну макроконверсию. Об этом я расскажу в отдельном материале.
Почему ClickHouse?
ClickHouse — это высокопроизводительная аналитическая система управления базами данных (СУБД) с открытым исходным кодом. Яндекс разработал ее для решения задач веб-аналитики в Яндекс Метрике.
Что важно, на мой взгляд:
-
система быстрая и заточена под работу с большими массивами данных,
-
используется в крупных продуктовых командах, поэтому уметь в ней работать — плюс к резюме,
-
она опенсорсная.
К тому же ClickHouse использует собственный диалект SQL, близкий к стандартному, но содержащий различные расширения: массивы и вложенные структуры данных, функции высшего порядка, вероятностные структуры, функции для работы с URI.
Подробнее про особенности ClickHouse можно почитать в официальной документации.
Итак, есть проблема, мы выбрали инструмент. Осталось только разобраться, как им пользоваться. И тут нам доступны варианты:
-
Простой: развернуть ClickHouse в Yandex Cloud. За простоту придется платить, причем около 5 тысяч рублей в месяц в минимальной конфигурации. Но зато все можно сделать в простом и наглядном веб-интерфейсе.
-
Продвинутый: развернуть ClickHouse на собственной виртуальной машине (VDS).
Мне в работе нужно обращаться к базе извне, поэтому вариант, как развернуть ClickHouse локально, я не рассматриваю.
ClickHouse в облаке
Кратко процедура создания ClickHouse в облаке описана в кейсе «Веб-аналитика с расчетом воронок и когорт на данных Яндекс Метрики», но там не хватает скриншотов — поэтому кратко пробегусь по процессу настройки.
1. Переходим в Managed Service for ClickHouse и выбираем «Создать кластер ClickHouse».
2. Выбираем конфигурацию сервера. Под простенькие задачи хватит и минимальной.
3. Важно сделать кластер публичным — в блоке «Хосты» нажимаем на карандаш и включаем опцию «Публичный доступ».
4. В блоке «Настройки СУБД» можно выключить управление пользователями через SQL, указать имя пользователя, пароль и имя базы данных.
5. В блоке «Сервисные настройки» нужно включить опции: «Доступ из DataLens», «Доступ из консоли управления», «Доступ из Метрики и AppMetrica», «Доступ из Serverless».
В течение нескольких минут кластер ClickHouse будет создан.
ClickHouse на своем сервере
Этот путь делится на два шага: покупку VDS и собственно установку ClickHouse.
Покупка VDS
1. Для покупки виртуальной машины нужно определиться с хостингом — я выбрал NetAngels.
Обратите внимание на минимальные требования из документации — не менее 4 ГБ оперативной памяти. Я пробовал запускать на 2 ГБ — машина зависала во время выполнения даже несложных SQL-запросов.
2. После выбора через нескольких минут создастся виртуальная машина, а на почту придут реквизиты для доступа по SSH. Я выбрал сборку от NetAngels на базе Debian 11.
3. Переходим в терминал и выполняем все шаги установки.
Я не заморачивался и сделал всё в веб-версии.
Установка ClickHouse
1. Устанавливаем или проверяем, установлены ли следующие пакеты:
-
apt-transport-https — для возможности взаимодействовать с репозиториями по https;
-
ca-certificates — набор корневых сертификатов;
-
dirmngr — для управления сетевыми сертификатами.
sudo apt-get install -y apt-transport-https ca-certificates dirmngr
В моем случае пакеты уже установлены.
2. Настраиваем ключи.
GNUPGHOME=$(mktemp -d)
sudo GNUPGHOME="$GNUPGHOME" gpg --no-default-keyring --keyring /usr/share/keyrings/clickhouse-keyring.gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 8919F6BD2B48D754
sudo rm -rf "$GNUPGHOME"
sudo chmod +r /usr/share/keyrings/clickhouse-keyring.gpg
3. Указываем репозиторий.
echo "deb [signed-by=/usr/share/keyrings/clickhouse-keyring.gpg] https://packages.clickhouse.com/deb stable main" | sudo tee \
/etc/apt/sources.list.d/clickhouse.list
4. Обновляем кэш.
sudo apt-get update
5. Запускаем установку сервера и клиента. Тут возможны разные варианты.
-
Быстрая установка без лишних вопросов (команда -y говорит отвечать YES во всех вопросах). Для пользователя default не будет установлен пароль, но, с другой стороны, мы скоро его деактивируем.
sudo apt-get install -y clickhouse-server clickhouse-client
-
Установка без пропуска вопросов — нам будет предложено задать пароль для пользователя default.
sudo apt-get install clickhouse-server clickhouse-client
-
Также мы можем задать специфическую версию при установке. Первый раз я ставил именно так, поскольку без принудительного указания ставились достаточно старые версии (что-то из серии 19.1.*)
sudo apt-get install clickhouse-server=24.1.5.6 clickhouse-client=24.1.5.6 clickhouse-common-static=24.1.5.6
Список всех версий можно найти на GitHub.
Все, ClickHouse установлен!
Подробная справка по установке — в официальной документации ClickHouse.
Запуск сервера и авторизация
Тут же нам подсказывают две основные команды — для запуска сервера и для подключения как пользователь default.
1. Запускаем сервер.
sudo clickhouse start
2. Авторизуемся как пользователь default (понадобится заданный ранее пароль).
clickhouse-client
3. Выполняем SQL-запрос, чтобы убедиться, что все работает.
SELECT 1
Конфигурация сервера
Файлы конфигурации в формате .xml лежат в папке /etc/clickhouse-server/
. Причем можно либо напрямую править основной файл конфигурации, либо создать подпапку config.d
по адресу etc/clickhouse-server/config.d/
и в нее положить свой файл конфигурации. Эти файлы будут объединены до того, как конфигурация вступит в силу.
Важно не забывать, что после изменения настроек нужно перезапускать сервер. Для этого могут быть использованы команды:
# Перезагрузка конфигурации сервера
sudo service clickhouse-server reload
# Полная перезагрузка сервера
sudo service clickhouse-server restart
Подробнее о конфигурации — в официальной справке.
Создание пользователей
Теперь наша задача создать пользователей, из-под которых мы будем выполнять все SQL-запросы. Для этого нужно пройти несколько шагов.
1. Включаем SQL User Mode для пользователя Default. Когда мы задали пароль при установке — в папке users.d создался файл default-password.xml с паролем пользователя. Необходимо добавить в него команды:
<clickhouse>
<users>
<default>
<password remove='1' />
<password_sha256_hex>65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5</password_sha256_hex>
<access_management>1</access_management>
<named_collection_control>1</named_collection_control>
<show_named_collections>1</show_named_collections>
<show_named_collections_secrets>1</show_named_collections_secrets>
</default>
</users>
</clickhouse>
2. Перезапускаем сервер, чтобы настройки применились.
sudo service clickhouse-server restart
Создание администратора для базы данных
1. Входим как пользователь default, чтобы создать администратора для базы данных, который сможет создавать базы, таблицы и пользователей, а также выдавать доступы.
CREATE USER clickhouse_admin IDENTIFIED BY 'qwerty';
2. Выдаем этому пользователю права на все базы и таблицы.
GRANT ALL ON *.* TO clickhouse_admin WITH GRANT OPTION;
Подробнее про SQL-пользователей и роли — в справке ClickHouse.
Проверка администратора и создание базы данных
1. Перезайдем под новым пользователем и проверим, что все работает.
clickhouse-client --user clickhouse_admin --password qwerty
2. Создадим базу данных и пользователя для нее.
CREATE DATABASE test_database;
Создадим таблицу.
CREATE TABLE test_database.test_table (
id UInt64,
column1 String,
column2 String
)
ENGINE MergeTree
ORDER BY id;
3. Заполним таблицу данными.
INSERT INTO test_database.test_table
(id, column1, column2)
VALUES
(1, 'A', 'abc'),
(2, 'A', 'def'),
(3, 'B', 'abc'),
(4, 'B', 'def');
4. Посмотрим содержимое таблицы.
SELECT *
FROM test_database.test_table
Создание и проверка пользователя
1. Создадим отдельного пользователя с правами только к созданной базе.
CREATE USER clickhouse_user IDENTIFIED BY 'password';
GRANT ALL ON test_database.* TO clickhouse_user WITH GRANT OPTION;
Подробнее про выдачу прав пользователям — в справке ClickHouse.
2. Проверим пользователя. Для этого сначала авторизуемся.
clickhouse-client --user clickhouse_user --password password
А затем выполним запрос к нашей базе.
SELECT *
FROM test_database.test_table
На этом мы закончили с созданием пользователей:
-
создали админа, из-под которого мы можем создавать пользователей и базы данных,
-
создали пользователя с доступом только к созданной базе test_database.
Отключение SQL User Mode и ограничение прав пользователя default
Чтобы отозвать права на управление у пользователя default
, изменим настройки в файле default-password.xml
.
<clickhouse>
<users>
<default>
<password remove='1' />
<password_sha256_hex>65e84be33532fb784c48129675f9eff3a682b27168c0ea744b2cf58ee02337c5</password_sha256_hex>
<profile>readonly</profile>
<access_management>0</access_management>
<!--
<named_collection_control>1</named_collection_control>
<show_named_collections>1</show_named_collections>
<show_named_collections_secrets>1</show_named_collections_secrets>
-->
</default>
</users>
</clickhouse>
Справка по управлению доступом в ClickHouse.
Также мы можем полностью отключить пользователя default. Для этого достаточно скорректировать открывающий тег.
<default remove="remove">
</default>
Активация возможности подключаться по сети
По умолчанию ClickHouse слушает запросы на локальной петле и не принимает запросов по сети. Для решения задачи нам нужно разрешить обработку сетевых запросов.
1. В папке etc/clickhouse-server/config.d/ создадим файл default-config.xml и добавим в него следующие строки.
<clickhouse>
<listen_host>::</listen_host>
</clickhouse>
2. Перезагрузим сервер.
sudo service clickhouse-server restart
Теперь ClickHouse доступен по IP-адресу сервера через порт 8123. Безопасное соединение через https я не настраивал.
В моем случае это:
http://213.189.220.34:8123/
Активация веб-интерфейса Tabix
Если мы хотим иметь веб-интерфейс по адресу нашего сервера, необходимо активировать Tabix (опенсорсный визуальный интерфейс для ClickHouse).
1. Скорректируем наш файл конфигурации default-config.xml.
<clickhouse>
<listen_host>::</listen_host>
<http_server_default_response><![CDATA[<html ng-app="SMI2"><head><base href="http://ui.tabix.io/"></head><body><div ui-view="" class="content-ui"></div><script src="http://loader.tabix.io/master.js"></script></body></html>]]></http_server_default_response>
</clickhouse>
2. Перезапустим сервер.
sudo service clickhouse-server restart
Теперь веб-интерфейс доступен по ссылке — осталось только ввести логин и пароль.
Авторизация пользователя в Tabix
При попытке авторизоваться как пользователь я столкнулся с ошибкой в консоли разработчика — Tabix ругался на права к таблице system.dictionaries
.
Code: 497. DB::Exception: clickhouse_user: Not enough privileges. To execute this query, it's necessary to have the grant SELECT(name, `attribute.names`, `attribute.types`, key) ON system.dictionaries. (ACCESS_DENIED) (version 24.1.5.6 (official build))
Для решения этой ошибки надо зайти под админом и выдать пользователю права на соответствующую таблицу.
GRANT SELECT ON system.dictionaries TO clickhouse_user WITH GRANT OPTION;
После авторизации можно полноценно пользоваться базой данных.
Подключение к серверу
Проверим подключение с помощью Python. Для этого импортируем библиотеку clickhouse_connect.
import clickhouse_connect
Укажем реквизиты сервера, попробуем подключиться и узнать версию базы данных.
client = clickhouse_connect.get_client(
host='213.189.220.34',
port=8123,
username='clickhouse_user',
password='password'
)
client.server_version
Подробнее про clickhouse_connect — в официальной справке ClickHouse.
Вместо заключения
Мы используем ClickHouse в своем стеке технологий, чтобы:
-
строить дашборды на данных Метрики, рекламных систем и CRM (для нас и для заказчиков),
-
визуализировать спрос (про это читайте другую мою статью DIY-маркетинг: как проанализировать спрос на рынке с помощью KeyCollector, Python и DataLens),
-
собирать SEO-дашборды на данных API панелей вебмастеров,
-
исследовать модели атрибуции (строить отчет в разных моделях).
В общем, если хотите работать с данными, нужна база, в которой можно их собирать, хранить и исследовать. Не всегда под рукой есть девопс, который все сам сделает. Не всегда есть 5 тысяч в месяц на базу в Яндекс Облаке, чтобы все было в визуальном интерфейсе и без сложностей. Поэтому стоит научиться разворачивать базу для себя.
Причем ClickHouse — не единственный вариант, есть куча других БД, которые можно использовать. Но именно ClickHouse справляется даже с огромными массивами данных о крупных продуктах, так что опыт работы с ним будет очень полезен.
Если после прочтения моей статьи вам захотелось узнать больше подробностей о том, как развернуть ClickHouse для своих нужд, — вы можете пройти мини-курсы Яндекса:
-
Витрина данных для веб‑аналитики в ClickHouse®,
-
Managed Service for ClickHouse®.
Если эта публикация вас вдохновила и вы хотите поддержать автора — не стесняйтесь нажать на кнопку
Introduction
We started working on creating a build for ClickHouse on WSL with the aim of becoming more familiar with ClickHouse. As an organization focusing on ClickHouse optimization at every level, this is obviously a necessity for us as well. And so the endeavour began.
The machine I was working on is a laptop with 8GB memory and AMD Ryzen 3 processor, running Windows 10. The WSL system was Ubuntu 20.04. The instructions for creating the build which I followed can be found at this link.
The instructions and commands to be followed are listed in the article given above, and I followed them to the letter. So it would be no surprise to the reader that I chose not to use GCC and went ahead with using Clang for the build, since the article recommends strongly against using it. But there was another reason why I didn’t bother using GCC, which was simply that GCC did not come pre-installed on my WSL Ubuntu. I could have installed it with a simple “sudo apt install”, but getting the specific version required for building ClickHouse (GCC 11 or above) might still be hard to get. If I ran out of all other options, I’d have to build GCC from source also, which was something I didn’t fancy wasting my time on when a huge task such as building ClickHouse was at hand.
Runbook to Build ClickHouse on Windows
You need the following tools for building ClickHouse from source:
- The latest version of
Clang
Git
Cmake
Python
Ninja-build
All of the above except for Clang can be downloaded with the following command:
sudo apt-get install git cmake python ninja-build
To download Clang, you can use the following command on Ubuntu and Debian WSL images (This might work for other Debian-based Linux distributions also, but that needs to be verified):
sudo bash -c "$(wget -O -)"
https://apt.llvm.org/llvm.sh
This downloads the Clang compiler into your system, and you can set the default Clang version to be used in the terminal as follows:
export CC=clang-14 export CXX=clang++-14
We need to use Clang-14 or above for creating this build, since it is required by ClickHouse.
The next step is to clone the ClickHouse source code onto your machine. Take care to clone the repo recursively, if you are typing it out by hand, so that all the dependencies can be cloned along with the repository. This command achieves that:
git clone --recursive git@github.com:ClickHouse/ClickHouse.git
Alternatively, you could also use HTTPS to fetch the repository, with a minor change to the above command:
git clone --recursive
https://github.com/ClickHouse/ClickHouse.git
It could take you a comparatively long time to clone the ClickHouse repo and its dependencies. On my machine with its humble configuration, it took nearly an entire day.
Once you have cloned the ClickHouse repository, run the following commands one-after-the-other for the build to start:
First you go to the ClickHouse source directory:
cd ClickHouse
Next you create a build directory in the ClickHouse source root directory and enter it:
mkdir build && cd build
Then run CMake to create the build files in their appropriate locations:
cmake ..
Finally you can build the ClickHouse source with Ninja build:
ninja
Once you execute these commands, the build will be ready. Be warned, it could take a long time! Happy coding.
Conclusion
Building ClickHouse on Windows via WSL offers a valuable learning opportunity despite potential challenges. By following a step-by-step process with tools like Clang, Git, CMake, Python, and Ninja-build, developers can gain insights into ClickHouse’s architecture and optimization potential.
To know more about getting started with ClickHouse, do visit the following articles:
- ClickHouse Installation: Cluster Setup and Configuration
- Introduction to ClickHouse C++ Client
- Running ClickHouse with Docker: Part 1
- Setting up QtCreator IDE for ClickHouse Development
- ClickHouse Integration: Connecting Airbyte with ClickHouse
Public user contributions licensed under
cc-wiki license with attribution required