Merge branch 'master' of github.com:yandex/ClickHouse

This commit is contained in:
BayoNet 2018-12-05 14:26:46 +03:00
commit c2308bd854
34 changed files with 386 additions and 256 deletions

View File

@ -1,3 +1,14 @@
## ClickHouse release 18.14.18, 2018-12-04
### Bug fixes:
* Fixed error in `dictGet...` function for dictionaries of type `range`, if one of the arguments is constant and other is not. [#3751](https://github.com/yandex/ClickHouse/pull/3751)
* Fixed error that caused messages `netlink: '...': attribute type 1 has an invalid length` to be printed in Linux kernel log, that was happening only on fresh enough versions of Linux kernel. [#3749](https://github.com/yandex/ClickHouse/pull/3749)
* Fixed segfault in function `empty` for argument of `FixedString` type. [#3703](https://github.com/yandex/ClickHouse/pull/3703)
* Fixed excessive memory allocation when using large value of `max_query_size` setting (a memory chunk of `max_query_size` bytes was preallocated at once). [#3720](https://github.com/yandex/ClickHouse/pull/3720)
### Build changes:
* Fixed build with LLVM/Clang libraries of version 7 from the OS packages (these libraries are used for runtime query compilation). [#3582](https://github.com/yandex/ClickHouse/pull/3582)
## ClickHouse release 18.14.17, 2018-11-30
### Bug fixes:

View File

@ -1,3 +1,14 @@
## ClickHouse release 18.14.18, 2018-12-04
### Исправления ошибок:
* Исправлена ошибка в функции `dictGet...` для словарей типа `range`, если один из аргументов константный, а другой - нет. [#3751](https://github.com/yandex/ClickHouse/pull/3751)
* Исправлена ошибка, приводящая к выводу сообщений `netlink: '...': attribute type 1 has an invalid length` в логе ядра Linux, проявляющаяся на достаточно новых ядрах Linux. [#3749](https://github.com/yandex/ClickHouse/pull/3749)
* Исправлен segfault при выполнении функции `empty` от аргумента типа `FixedString`. [#3703](https://github.com/yandex/ClickHouse/pull/3703)
* Исправлена избыточная аллокация памяти при большом значении настройки `max_query_size` (кусок памяти размера `max_query_size` выделялся сразу). [#3720](https://github.com/yandex/ClickHouse/pull/3720)
### Улучшения процесса сборки ClickHouse:
* Исправлена сборка с использованием библиотек LLVM/Clang версии 7 из пакетов ОС (эти библиотеки используются для динамической компиляции запросов). [#3582](https://github.com/yandex/ClickHouse/pull/3582)
## ClickHouse release 18.14.17, 2018-11-30
### Исправления ошибок:

View File

@ -170,6 +170,7 @@ endif ()
if (USE_INTERNAL_LLVM_LIBRARY)
file(GENERATE OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/empty.cpp CONTENT " ")
add_library(LLVM0 ${CMAKE_CURRENT_BINARY_DIR}/empty.cpp) # silly cmake bug fix
add_library(LLVMOFF ${CMAKE_CURRENT_BINARY_DIR}/empty.cpp)
# ld: unknown option: --color-diagnostics
if (APPLE)
set (LINKER_SUPPORTS_COLOR_DIAGNOSTICS 0 CACHE INTERNAL "")

View File

@ -84,7 +84,7 @@ public:
}
/// If column stores integers, it returns n-th element transformed to UInt64 using static_cast.
/// If column stores floting point numbers, bits of n-th elements are copied to lower bits of UInt64, the remaining bits are zeros.
/// If column stores floating point numbers, bits of n-th elements are copied to lower bits of UInt64, the remaining bits are zeros.
/// Is used to optimize some computations (in aggregation, for example).
virtual UInt64 get64(size_t /*n*/) const
{

View File

@ -155,7 +155,7 @@ NetlinkMessage query(
request.generic_header.version = 1;
request.payload.attribute.header.nla_type = attribute_type;
request.payload.attribute.header.nla_len = attribute_size + 1 + NLA_HDRLEN;
request.payload.attribute.header.nla_len = attribute_size + NLA_HDRLEN;
memcpy(&request.payload.attribute.payload, attribute_data, attribute_size);

View File

@ -354,7 +354,9 @@ void RangeHashedDictionary::getItemsImpl(
out[i] = static_cast<OutputType>(val_it != std::end(ranges_and_values) ? val_it->value : null_value);
}
else
{
out[i] = static_cast<OutputType>(null_value);
}
}
query_count.fetch_add(ids.size(), std::memory_order_relaxed);

View File

@ -1683,20 +1683,21 @@ private:
template <typename T>
static const PaddedPODArray<T> & getColumnDataAsPaddedPODArray(const IColumn & column, PaddedPODArray<T> & backup_storage)
{
if (const auto vector_col = checkAndGetColumn<ColumnVector<T>>(&column))
if (!column.isColumnConst())
{
return vector_col->getData();
}
if (const auto const_col = checkAndGetColumnConstData<ColumnVector<T>>(&column))
{
return const_col->getData();
if (const auto vector_col = checkAndGetColumn<ColumnVector<T>>(&column))
{
return vector_col->getData();
}
}
// With type conversion, need to use backup storage here
const auto size = column.size();
const auto full_column = column.isColumnConst() ? column.convertToFullColumnIfConst() : column.getPtr();
// With type conversion and const columns we need to use backup storage here
const auto size = full_column->size();
backup_storage.resize(size);
for (size_t i = 0; i < size; ++i)
backup_storage[i] = column.getUInt(i);
backup_storage[i] = full_column->getUInt(i);
return backup_storage;
}

View File

@ -2,35 +2,29 @@
## System Requirements
Installation from the official repository requires Linux with x86_64 architecture and support for the SSE 4.2 instruction set.
ClickHouse can run on any Linux, FreeBSD or Mac OS X with x86\_64 CPU architecture.
To check for SSE 4.2:
Though pre-built binaries are typically compiled to 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:
```bash
grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not supported"
``` bash
$ grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not supported"
```
We recommend using Ubuntu or Debian. The terminal must use UTF-8 encoding.
For rpm-based systems, you can use 3rd-party packages: https://packagecloud.io/altinity/clickhouse or install debian packages.
ClickHouse also works on FreeBSD and Mac OS X. It can be compiled for x86_64 processors without SSE 4.2 support, and for AArch64 CPUs.
## Installation
For testing and development, the system can be installed on a single server or on a desktop computer.
### From DEB Packages
### Installing from Packages for Debian/Ubuntu
Yandex ClickHouse team recommends using official pre-compiled `deb` packages for Debian or Ubuntu.
In `/etc/apt/sources.list` (or in a separate `/etc/apt/sources.list.d/clickhouse.list` file), add the repository:
To install official packages add the Yandex repository in `/etc/apt/sources.list` or in a separate `/etc/apt/sources.list.d/clickhouse.list` file:
```
deb http://repo.yandex.ru/clickhouse/deb/stable/ main/
```
If you want to use the most recent test version, replace 'stable' with 'testing'.
If you want to use the most recent version, replace `stable` with `testing` (this is not recommended for production environments).
Then run:
Then run these commands to actually install packages:
```bash
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv E0C56BD4 # optional
@ -40,82 +34,77 @@ sudo apt-get install clickhouse-client clickhouse-server
You can also download and install packages manually from here: <https://repo.yandex.ru/clickhouse/deb/stable/main/>.
ClickHouse contains 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".
### From RPM Packages
### Installing from Sources
Yandex does not run ClickHouse on `rpm` based Linux distributions and `rpm` packages are not as thoroughly tested. So use them at your own risk, but there are many other companies that do successfully run them in production without any major issues.
To compile, follow the instructions: build.md
For CentOS, RHEL or Fedora there are the following options:
* Packages from <https://repo.yandex.ru/clickhouse/rpm/stable/x86_64/> are generated from official `deb` packages by Yandex and have byte-identical binaries.
* Packages from <https://github.com/Altinity/clickhouse-rpm-install> are built by independent company Altinity, but are used widely without any complaints.
* Or you can use Docker (see below).
You can compile packages and install them.
You can also use programs without installing packages.
### From Docker Image
To run ClickHouse inside Docker follow the guide on [Docker Hub](https://hub.docker.com/r/yandex/clickhouse-server/). Those images use official `deb` packages inside.
### From Sources
To manually compile ClickHouse, follow the instructions for [Linux](../development/build.md) or [Mac OS X](../development/build_osx.md).
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.
```
Client: dbms/programs/clickhouse-client
Server: dbms/programs/clickhouse-server
```
For the server, create a catalog with data, such as:
You'll need to create a data and metadata folders and `chown` them for the desired user. Their paths can be changed in server config (src/dbms/programs/server/config.xml), by default they are:
```
/opt/clickhouse/data/default/
/opt/clickhouse/metadata/default/
```
(Configurable in the server config.)
Run 'chown' for the desired user.
Note the path to logs in the server config (src/dbms/programs/server/config.xml).
### Other Installation Methods
Docker image: <https://hub.docker.com/r/yandex/clickhouse-server/>
RPM packages for CentOS or RHEL: <https://github.com/Altinity/clickhouse-rpm-install>
Gentoo: `emerge clickhouse`
On Gentoo you can just use `emerge clickhouse` to install ClickHouse from sources.
## Launch
To start the server (as a daemon), run:
To start the server as a daemon, run:
```bash
sudo service clickhouse-server start
``` bash
$ sudo service clickhouse-server start
```
See the logs in the `/var/log/clickhouse-server/ directory.`
See the logs in the `/var/log/clickhouse-server/` directory.
If the server doesn't start, check the configurations in the file `/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:
You can also manually launch the server from the console:
```bash
clickhouse-server --config-file=/etc/clickhouse-server/config.xml
``` bash
$ clickhouse-server --config-file=/etc/clickhouse-server/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'.
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 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"](../operations/configuration_files.md).
```bash
clickhouse-client
After launching server, you can use the command-line client to connect to it:
``` bash
$ clickhouse-client
```
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. Example:
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.
```bash
clickhouse-client --host=example.com
```
The terminal must use UTF-8 encoding.
For more information, see the section ["Command-line client"](../interfaces/cli.md).
For more information, see the section "Command-line client".
Checking the system:
```bash
milovidov@hostname:~/work/metrica/src/dbms/src/Client$ ./clickhouse-client
Example:
``` bash
$ ./clickhouse-client
ClickHouse client version 0.0.18749.
Connecting to localhost:9000.
Connected to ClickHouse server version 0.0.18749.
@ -135,7 +124,7 @@ SELECT 1
**Congratulations, the system works!**
To continue experimenting, you can try to download from the test data sets.
To continue experimenting, you can download one of test data sets or go through [tutorial](https://clickhouse.yandex/tutorial.html).
[Original article](https://clickhouse.yandex/docs/en/getting_started/) <!--hide-->

View File

@ -2,20 +2,20 @@
# Permissions for queries
Queries in ClickHouse can be divided into several groups:
Queries in ClickHouse can be divided into several types:
1. Read data queries: `SELECT`, `SHOW`, `DESCRIBE`, `EXISTS`.
1. Write data queries: `INSERT`, `OPTIMIZE`.
1. Change settings queries: `SET`, `USE`.
1. [DDL](https://en.wikipedia.org/wiki/Data_definition_language) queries: `CREATE`, `ALTER`, `RENAME`, `ATTACH`, `DETACH`, `DROP` `TRUNCATE`.
1. Particular queries: `KILL QUERY`.
1. `KILL QUERY`.
The following settings regulate user permissions for the groups of queries:
The following settings regulate user permissions by the type of query:
- [readonly](#settings_readonly) — Restricts permissions for all groups of queries excepting DDL.
- [readonly](#settings_readonly) — Restricts permissions for all types of queries except DDL queries.
- [allow_ddl](#settings_allow_ddl) — Restricts permissions for DDL queries.
`KILL QUERY` performs with any settings.
`KILL QUERY` can be performed with any settings.
<a name="settings_readonly"></a>
@ -23,17 +23,21 @@ The following settings regulate user permissions for the groups of queries:
Restricts permissions for read data, write data and change settings queries.
See [above](#permissions_for_queries) for the division of queries into groups.
See how the queries are divided into types [above](#permissions_for_queries).
**Possible values**
- 0 — All queries are allowed. Default value.
- 1 — Read data queries only are allowed.
- 0 — All queries are allowed.
- 1 — Only read data queries are allowed.
- 2 — Read data and change settings queries are allowed.
After setting `readonly = 1`, a user can't change `readonly` and `allow_ddl` settings in the current session.
After setting `readonly = 1`, the user can't change `readonly` and `allow_ddl` settings in the current session.
When using the `GET` method in the [HTTP interface](../../interfaces/http.md#http_interface), `readonly = 1` is set automatically. To modify data use the `POST` method.
When using the `GET` method in the [HTTP interface](../../interfaces/http.md#http_interface), `readonly = 1` is set automatically. To modify data, use the `POST` method.
**Default value**
0
<a name="settings_allow_ddl"></a>
@ -41,13 +45,17 @@ When using the `GET` method in the [HTTP interface](../../interfaces/http.md#htt
Allows/denies [DDL](https://en.wikipedia.org/wiki/Data_definition_language) queries.
See [above](#permissions_for_queries) for the division of queries into groups.
See how the queries are divided into types [above](#permissions_for_queries).
**Possible values**
- 0 — DDL queries are not allowed.
- 1 — DDL queries are allowed. Default value.
- 1 — DDL queries are allowed.
You can not execute `SET allow_ddl = 1` if `allow_ddl = 0` for current session.
You cannot execute `SET allow_ddl = 1` if `allow_ddl = 0` for the current session.
**Default value**
1
[Original article](https://clickhouse.yandex/docs/en/operations/settings/permissions_for_queries/) <!--hide-->

View File

@ -2,7 +2,7 @@
# AggregatingMergeTree
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree), altering the logic for data parts merging. ClickHouse replaces all rows with the same primary key with a single row (within a one data part) that stores a combination of states of aggregate functions.
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree), altering the logic for data parts merging. ClickHouse replaces all rows with the same primary key (or more accurately, with the same [sorting key](mergetree.md#table_engines-mergetree-sorting_key)) with a single row (within a one data part) that stores a combination of states of aggregate functions.
You can use `AggregatingMergeTree` tables for incremental data aggregation, including for aggregated materialized views.

View File

@ -40,6 +40,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
) ENGINE = MergeTree()
[PARTITION BY expr]
[ORDER BY expr]
[PRIMARY KEY expr]
[SAMPLE BY expr]
[SETTINGS name=value, ...]
```
@ -50,11 +51,13 @@ For a description of request parameters, see [request description](../../query_l
- `ENGINE` - Name and parameters of the engine. `ENGINE = MergeTree()`. `MergeTree` engine does not have parameters.
- `ORDER BY` — Primary key.
- `ORDER BY` — Primary key (or sorting key if the separate `PRIMARY KEY` clause is present).
A tuple of columns or arbitrary expressions. Example: `ORDER BY (CounterID, EventDate)`.
If a sampling expression is used, the primary key must contain it. Example: `ORDER BY (CounterID, EventDate, intHash32(UserID))`.
- `PRIMARY KEY` - Primary key if it differs from the [sorting key](mergetree.md#table_engines-mergetree-sorting_key) (the sorting key in this case is specified by the `ORDER BY` clause).
- `PARTITION BY` — The [partitioning key](custom_partitioning_key.md#table_engines-custom_partitioning_key).
For partitioning by month, use the `toYYYYMM(date_column)` expression, where `date_column` is a column with a date of the type [Date](../../data_types/date.md#data_type-date). The partition names here have the `"YYYYMM"` format.
@ -161,10 +164,33 @@ The number of columns in the primary key is not explicitly limited. Depending on
- Provide additional logic when data parts merging in the [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) and [SummingMergeTree](summingmergetree.md#table_engine-summingmergetree) engines.
You may need many fields in the primary key even if they are not necessary for the previous steps.
If you need this, it makes sense to specify the *sorting key* that is distinct from the primary key.
A long primary key will negatively affect the insert performance and memory consumption, but extra columns in the primary key do not affect ClickHouse performance during `SELECT` queries.
<a name="table_engines-mergetree-sorting_key"></a>
### Choosing the Sorting Key that is distinct from the Primary Key
It is possible to specify the sorting key (the expression for sorting the rows in data parts) that is distinct
from the primary key (the expression, values of which are written into the index file for each mark). In this
case primary key expression tuple must be a prefix of the sorting key expression tuple.
This feature is helpful when using the [SummingMergeTree](summingmergetree.md) and
[AggregatingMergeTree](aggregatingmergetree.md) table engines. In a common case when using these engines the
table has two types of columns: *dimensions* and *measures*. Typical queries aggregate values of measure
columns with arbitrary `GROUP BY` and filtering by dimensions. As SummingMergeTree and AggregatingMergeTree
aggregate rows with the same value of the sorting key, it is natural to add all dimensions to it. As a result
the key expression consists of a long list of columns and this list must be frequently updated with newly
added dimensions.
In this case it makes sense to leave only a few columns in the primary key that will provide efficient
range scans and add the remaining dimension columns to the sorting key tuple.
[ALTER of the sorting key](../../query_language/alter.md#query_language-queries-alter-key_alters) is a
lightweight operation because when a new column is simultaneously added to the table and to the sorting key
data parts need not be changed (they remain sorted by the new sorting key expression).
### Use of Indexes and Partitions in Queries
For`SELECT` queries, ClickHouse analyzes whether an index can be used. An index can be used if the `WHERE/PREWHERE` clause has an expression (as one of the conjunction elements, or entirely) that represents an equality or inequality comparison operation, or if it has `IN` or `LIKE` with a fixed prefix on columns or expressions that are in the primary key or partitioning key, or on certain partially repetitive functions of these columns, or logical relationships of these expressions.

View File

@ -1,6 +1,6 @@
# ReplacingMergeTree
The engine differs from [MergeTree](mergetree.md#table_engines-mergetree) in that it removes duplicate entries with the same primary key value.
The engine differs from [MergeTree](mergetree.md#table_engines-mergetree) in that it removes duplicate entries with the same primary key value (or more accurately, with the same [sorting key](mergetree.md#table_engines-mergetree-sorting_key) value).
Data deduplication occurs only during a merge. Merging occurs in the background at an unknown time, so you can't plan for it. Some of the data may remain unprocessed. Although you can run an unscheduled merge using the `OPTIMIZE` query, don't count on using it, because the `OPTIMIZE` query will read and write a large amount of data.

View File

@ -2,7 +2,7 @@
# SummingMergeTree
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree). The difference is that when merging data parts for `SummingMergeTree` tables ClickHouse replaces all the rows with the same primary key with one row which contains summarized values for the columns with the numeric data type. If the primary key is composed in a way that a single key value corresponds to large number of rows, this significantly reduces storage volume and speeds up data selection.
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree). The difference is that when merging data parts for `SummingMergeTree` tables ClickHouse replaces all the rows with the same primary key (or more accurately, with the same [sorting key](mergetree.md#table_engines-mergetree-sorting_key)) with one row which contains summarized values for the columns with the numeric data type. If the sorting key is composed in a way that a single key value corresponds to large number of rows, this significantly reduces storage volume and speeds up data selection.
We recommend to use the engine together with `MergeTree`. Store complete data in `MergeTree` table, and use `SummingMergeTree` for aggregated data storing, for example, when preparing reports. Such an approach will prevent you from losing valuable data due to an incorrectly composed primary key.

View File

@ -68,9 +68,28 @@ For tables that don't store data themselves (such as `Merge` and `Distributed`),
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.
<a name="query_language-queries-alter-key_alters"></a>
### Manipulations With Key Expressions
The following command is supported:
``` sql
MODIFY ORDER BY new_expression
```
It only works for tables in the `MergeTree` family (including replicated tables). The command changes the
[sorting key](../operations/table_engines/mergetree.md#table_engines-mergetree-sorting_key) of the table
to `new_expression` (an expression or a tuple of expressions). Primary key remains the same.
The command is lightweight in a sense that it only changes metadata. To keep the property that data part
rows are sorted by the sorting key expression you cannot add expressions containing existing columns
to the sorting key (only columns added by the `ADD COLUMN` command in the same `ALTER` query).
### Manipulations With Partitions and Parts
It only works for tables in the `MergeTree` family. The following operations are available:
It only works for tables in the `MergeTree` family (including replicated tables). The following operations
are available:
- `DETACH PARTITION` Move a partition to the 'detached' directory and forget it.
- `DROP PARTITION` Delete a partition.

View File

@ -461,7 +461,7 @@ If indexes are supported by the database table engine, the expression is evaluat
This clause has the same meaning as the WHERE clause. The difference is in which data is read from the table.
When using PREWHERE, first only the columns necessary for executing PREWHERE are read. Then the other columns are read that are needed for running the query, but only those blocks where the PREWHERE expression is true.
It makes sense to use PREWHERE if there are filtration conditions that are not suitable for indexes that are used by a minority of the columns in the query, but that provide strong data filtration. This reduces the volume of data to read.
It makes sense to use PREWHERE if there are filtration conditions that are used by a minority of the columns in the query, but that provide strong data filtration. This reduces the volume of data to read.
For example, it is useful to write PREWHERE for queries that extract a large number of columns, but that only have filtration for a few columns.
@ -469,8 +469,6 @@ PREWHERE is only supported by tables from the `*MergeTree` family.
A query may simultaneously specify PREWHERE and WHERE. In this case, PREWHERE precedes WHERE.
Keep in mind that it does not make much sense for PREWHERE to only specify those columns that have an index, because when using an index, only the data blocks that match the index are read.
If the 'optimize_move_to_prewhere' setting is set to 1 and PREWHERE is omitted, the system uses heuristics to automatically move parts of expressions from WHERE to PREWHERE.
### GROUP BY Clause

View File

@ -4,7 +4,7 @@
## نیازمندی های سیستم
این یک سیستم چند سکویی (Cross-Platform) نمی باشد. این ابزار نیاز به Linux Ubuntu Precise (12.04) یا جدیدتر، با معماری x86_64 و پشتیبانی از SSE 4.2 می باشد. برای چک کردن SSE 4.2 خروجی دستور زیر را بررسی کنید:
این یک سیستم چند سکویی (Cross-Platform) نمی باشد. این ابزار نیاز به Linux Ubuntu Precise (12.04) یا جدیدتر، با معماری x86\_64 و پشتیبانی از SSE 4.2 می باشد. برای چک کردن SSE 4.2 خروجی دستور زیر را بررسی کنید:
</div>
@ -18,8 +18,6 @@ grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not su
## نصب
برای تست و توسعه، ClickHouse می تواند در یک سرور یا در یک کامپیوتر desktop نصب شود.
### نصب از طریق پکیج های Debian/Ubuntu
در فایل `/etc/apt/sources.list` (یا در یک فایل جدا `/etc/apt/sources.list.d/clickhouse.list`)، Repo زیر را اضافه کنید:
@ -100,7 +98,7 @@ sudo service clickhouse-server start
<div dir="rtl" markdown="1">
لاگ های دایرکتوری `/var/log/clickhouse-server/ directory.` را مشاهده کنید.
لاگ های دایرکتوری `/var/log/clickhouse-server/` directory. را مشاهده کنید.
اگر سرور استارت نشد، فایل تنظیمات را بررسی کنید `/etc/clickhouse-server/config.xml.`

View File

@ -2,35 +2,29 @@
## Системные требования
Для установки из официального репозитория требуется ОС Linux; архитектура x86_64 с поддержкой набора инструкций SSE 4.2.
ClickHouse может работать на любом Linux, FreeBSD или Mac OS X с архитектурой процессора x86\_64.
Для проверки наличия SSE 4.2, выполните:
Хотя предсобранные релизы обычно компилируются с использованием набора инструкций SSE 4.2, что добавляет использование поддерживающего его процессора в список системных требований. Команда для п проверки наличия поддержки инструкций SSE 4.2 на текущем процессоре:
```bash
grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not supported"
$ grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not supported"
```
Рекомендуется использовать Ubuntu или Debian. Терминал должен работать в кодировке UTF-8.
Для rpm-based систем вы можете использовать 3rd-party пакеты: https://packagecloud.io/altinity/clickhouse либо установить debian пакеты.
ClickHouse также работает на FreeBSD и Mac OS X; может быть собран для процессоров x86_64 без поддержки SSE 4.2, и для процессоров AArch64.
## Установка
В целях тестирования и разработки, система может быть установлена на один сервер или на рабочий компьютер.
### Из DEB пакетов
### Установка из пакетов для Debian/Ubuntu
Яндекс рекомендует использовать официальные скомпилированные `deb` пакеты для Debian или Ubuntu.
Пропишите в `/etc/apt/sources.list` (или в отдельный файл `/etc/apt/sources.list.d/clickhouse.list`) репозитории:
Чтобы установить официальные пакеты, пропишите репозиторий Яндекса в `/etc/apt/sources.list` или в отдельный файл `/etc/apt/sources.list.d/clickhouse.list`:
```
deb http://repo.yandex.ru/clickhouse/deb/stable/ main/
```
Если вы хотите использовать наиболее свежую тестовую версию, замените stable на testing.
Если вы хотите использовать наиболее свежую тестовую, замените `stable` на `testing` (не рекомендуется для production окружений).
Затем выполните:
Затем для самой установки пакетов выполните:
```bash
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv E0C56BD4 # optional
@ -38,84 +32,78 @@ sudo apt-get update
sudo apt-get install clickhouse-client clickhouse-server
```
Также можно скачать и установить пакеты вручную, отсюда: <https://repo.yandex.ru/clickhouse/deb/stable/main/>.
Также эти пакеты можно скачать и установить вручную отсюда: <https://repo.yandex.ru/clickhouse/deb/stable/main/>.
ClickHouse содержит настройки ограничения доступа. Они расположены в файле users.xml (рядом с config.xml).
По умолчанию, разрешён доступ отовсюду для пользователя default без пароля. См. секцию users/default/networks.
Подробнее смотрите в разделе "конфигурационные файлы".
### Из RPM пакетов
### Установка из исходников
Яндекс не использует ClickHouse на поддерживающих `rpm` дистрибутивах Linux, а также `rpm` пакеты менее тщательно тестируются. Таким образом, использовать их стоит на свой страх и риск, но, тем не менее, многие другие компании успешно работают на них в production без каких-либо серьезных проблем.
Для сборки воспользуйтесь инструкцией: build.md
Для CentOS, RHEL и Fedora возможны следующие варианты:
* Пакеты из <https://repo.yandex.ru/clickhouse/rpm/stable/x86_64/> генерируются на основе официальных `deb` пакетов от Яндекса и содержат в точности тот же исполняемый файл.
* Пакеты из <https://github.com/Altinity/clickhouse-rpm-install> собираются независимой компанией Altinity, но широко используются без каких-либо нареканий.
* Либо можно использовать Docker (см. ниже).
Вы можете собрать пакеты и установить их.
Также вы можете использовать программы без установки пакетов.
### Из Docker образа
Для запуска ClickHouse в Docker нужно следовать инструкции на [Docker Hub](https://hub.docker.com/r/yandex/clickhouse-server/). Внутри образов используются официальные `deb` пакеты.
### Из исходникого кода
Для компиляции ClickHouse вручную, испольщуйте инструкцию для [Linux](../development/build.md) или [Mac OS X](../development/build_osx.md).
Можно скомпилировать пакеты и установить их, либо использовать программы без установки пакетов. Также при ручой сборке можно отключить необходимость поддержки набора инструкций SSE 4.2 или собрать под процессоры архитектуры AArch64.
```
Client: dbms/programs/clickhouse-client
Server: dbms/programs/clickhouse-server
```
Для сервера создаёте директории с данными, например:
Для работы собранного вручную сервера необходимо создать директории для данных и метаданных, а также сделать их `chown` для желаемого пользователя. Пути к этим директориям могут быть изменены в конфигурационном файле сервера (src/dbms/programs/server/config.xml), по умолчанию используются следующие:
```
/opt/clickhouse/data/default/
/opt/clickhouse/metadata/default/
```
(Настраивается в конфиге сервера.)
Сделайте chown под нужного пользователя.
Обратите внимание на путь к логам в конфиге сервера (src/dbms/programs/server/config.xml).
### Другие методы установки
Docker образ: <https://hub.docker.com/r/yandex/clickhouse-server/>
RPM пакеты для CentOS, RHEL: <https://github.com/Altinity/clickhouse-rpm-install>
Gentoo: `emerge clickhouse`
На Gentoo для установки ClickHouse из исходного кода можно использовать просто `emerge clickhouse`.
## Запуск
Для запуска сервера (в качестве демона), выполните:
Для запуска сервера в качестве демона, выполните:
```bash
sudo service clickhouse-server start
``` bash
% sudo service clickhouse-server start
```
Смотрите логи в директории `/var/log/clickhouse-server/`
Смотрите логи в директории `/var/log/clickhouse-server/`.
Если сервер не стартует - проверьте правильность конфигурации в файле `/etc/clickhouse-server/config.xml`
Если сервер не стартует, проверьте корректность конфигурации в файле `/etc/clickhouse-server/config.xml`
Также можно запустить сервер из консоли:
Также можно запустить сервер вручную из консоли:
```bash
clickhouse-server --config-file=/etc/clickhouse-server/config.xml
``` bash
$ clickhouse-server --config-file=/etc/clickhouse-server/config.xml
```
При этом, лог будет выводиться в консоль - удобно для разработки.
Если конфигурационный файл лежит в текущей директории, то указывать параметр --config-file не требуется - по умолчанию будет использован файл ./config.xml
При этом, лог будет выводиться в консоль, что удобно для разработки.
Если конфигурационный файл лежит в текущей директории, то указывать параметр `--config-file` не требуется, по умолчанию будет использован файл `./config.xml`.
Соединиться с сервером можно с помощью клиента командной строки:
После запуска сервера, соединиться с ним можно с помощью клиента командной строки:
```bash
clickhouse-client
``` bash
$ clickhouse-client
```
Параметры по умолчанию обозначают - соединяться с localhost:9000, от имени пользователя default без пароля.
Клиент может быть использован для соединения с удалённым сервером. Пример:
По умолчанию он соединяется с localhost:9000, от имени пользователя `default` без пароля. Также клиент может быть использован для соединения с удалённым сервером с помощью аргемента `--host`.
```bash
clickhouse-client --host=example.com
```
Терминал должен использлвать кодировку UTF-8.
Подробнее смотри раздел "Клиент командной строки".
Более подробная информация о клиенте располагается в разделе [«Клиент командной строки»](../interfaces/cli.md).
Проверим работоспособность системы:
Пример проверки работоспособности системы:
```bash
milovidov@hostname:~/work/metrica/src/dbms/src/Client$ ./clickhouse-client
``` bash
$ ./clickhouse-client
ClickHouse client version 0.0.18749.
Connecting to localhost:9000.
Connected to ClickHouse server version 0.0.18749.
@ -135,6 +123,6 @@ SELECT 1
**Поздравляем, система работает!**
Для дальнейших экспериментов можно попробовать загрузить из тестовых наборов данных.
Для дальнейших экспериментов можно попробовать загрузить один из тестовых наборов данных или пройти [пошаговое руководство для начинающих](https://clickhouse.yandex/tutorial.html).
[Оригинальная статья](https://clickhouse.yandex/docs/ru/getting_started/) <!--hide-->

View File

@ -1,3 +1,5 @@
<a name="http_interface"></a>
# HTTP-интерфейс
HTTP интерфейс позволяет использовать ClickHouse на любой платформе, из любого языка программирования. У нас он используется для работы из Java и Perl, а также из shell-скриптов. В других отделах, HTTP интерфейс используется из Perl, Python и Go. HTTP интерфейс более ограничен по сравнению с родным интерфейсом, но является более совместимым.

View File

@ -1,5 +1,5 @@
# ODBC-драйвер
- [Официальный драйвер](https://github.com/yandex/clickhouse-jdbc).
- [Официальный драйвер](https://github.com/yandex/clickhouse-odbc).
[Оригинальная статья](https://clickhouse.yandex/docs/ru/interfaces/odbc/) <!--hide-->

View File

@ -1 +0,0 @@
../../../en/operations/settings/permissions_for_queries.md

View File

@ -0,0 +1,61 @@
<a name="permissions_for_queries"></a>
# Разрешения для запросов
Запросы в ClickHouse можно разделить на несколько типов:
1. Запросы на чтение данных: `SELECT`, `SHOW`, `DESCRIBE`, `EXISTS`.
1. Запросы за запись данных: `INSERT`, `OPTIMIZE`.
1. Запросы на изменение настроек: `SET`, `USE`.
1. [Запросы DDL](https://ru.wikipedia.org/wiki/Data_Definition_Language): `CREATE`, `ALTER`, `RENAME`, `ATTACH`, `DETACH`, `DROP` `TRUNCATE`.
1. `KILL QUERY`.
Разрешения пользователя по типу запроса регулируются параметрами:
- [readonly](#settings_readonly) — ограничивает разрешения для всех типов запросов, кроме DDL.
- [allow_ddl](#settings_allow_ddl) — ограничивает разрешения для DDL запросов.
`KILL QUERY` выполняется с любыми настройками.
<a name="settings_readonly"></a>
## readonly
Ограничивает разрешения для запросов на чтение данных, запись данных и изменение параметров.
Разделение запросов по типам смотрите по тексту [выше](#permissions_for_queries) по тексту.
**Возможные значения**
- 0 — разрешены все запросы.
- 1 — разрешены только запросы на чтение данных.
- 2 — разрешены запросы на чтение данных и изменение настроек.
После установки `readonly = 1`пользователь не может изменить настройки `readonly` и `allow_ddl` в текущей сессии.
При использовании метода `GET` в [HTTP интерфейсе](../../interfaces/http.md#http_interface), `readonly = 1` устанавливается автоматически. Для изменения данных используйте метод `POST`.
**Значение по умолчанию**
0
<a name="settings_allow_ddl"></a>
## allow_ddl
Разрешает/запрещает [DDL](https://ru.wikipedia.org/wiki/Data_Definition_Language) запросы.
Разделение запросов по типам смотрите по тексту [выше](#permissions_for_queries) по тексту.
**Возможные значения**
- 0 — DDL запросы не разрешены.
- 1 — DDL запросы разрешены.
Если `allow_ddl = 0`, то невозможно выполнить `SET allow_ddl = 1` для текущей сессии.
**Значение по умолчанию**
1
[Оригинальная статья](https://clickhouse.yandex/docs/ru/operations/settings/permissions_for_queries/) <!--hide-->

View File

@ -17,18 +17,6 @@
`any (только для group_by_overflow_mode)` - продолжить агрегацию по ключам, которые успели войти в набор, но не добавлять новые ключи в набор.
<a name="query_complexity_readonly"></a>
## readonly
При значении 0 можно выполнять любые запросы.
При значении 1 можно выполнять только запросы на чтение (например, SELECT и SHOW). Запросы на запись и изменение настроек (INSERT, SET) запрещены.
При значении 2 можно выполнять запросы на чтение (SELECT, SHOW) и изменение настроек (SET).
Включив режим readonly, вы уже не сможете выключить его в текущей сессии.
При использовании метода GET HTTP интерфейса, автоматически выставляется readonly = 1. То есть, для запросов, модифицирующие данные, можно использовать только метод POST. Сам запрос при этом можно отправлять как в теле POST-а, так и в параметре URL.
<a name="settings_max_memory_usage"></a>
## max_memory_usage

View File

@ -2,7 +2,7 @@
# AggregatingMergeTree
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree), изменяя логику слияния кусков данных. Все строки с одинаковым первичным ключом ClickHouse заменяет на одну (в пределах одного куска данных), которая хранит объединение состояний агрегатных функций.
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree), изменяя логику слияния кусков данных. Все строки с одинаковым первичным ключом (точнее, с одинаковым [ключом сортировки](mergetree.md#table_engines-mergetree-sorting_key)) ClickHouse заменяет на одну (в пределах одного куска данных), которая хранит объединение состояний агрегатных функций.
Таблицы типа `AggregatingMergeTree` могут использоваться для инкрементальной агрегации данных, в том числе, для агрегирующих материализованных представлений.

View File

@ -38,6 +38,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
) ENGINE = MergeTree()
[PARTITION BY expr]
[ORDER BY expr]
[PRIMARY KEY expr]
[SAMPLE BY expr]
[SETTINGS name=value, ...]
```
@ -48,11 +49,13 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
- `ENGINE` — Имя и параметры движка. `ENGINE = MergeTree()`. Движок `MergeTree` не имеет параметров.
- `ORDER BY` — первичный ключ.
- `ORDER BY` — первичный ключ (если не указана отдельная секция `PRIMARY KEY`).
Кортеж столбцов или произвольных выражений. Пример: `ORDER BY (CounerID, EventDate)`.
Если используется выражение для сэмплирования, то первичный ключ должен содержать его. Пример: `ORDER BY (CounerID, EventDate, intHash32(UserID))`.
- `PRIMARY KEY` - первичный ключ, если он отличается от [ключа сортировки](mergetree.md#table_engines-mergetree-sorting_key) (который в этом случае задаёт секция `ORDER BY`).
- `PARTITION BY` — [ключ партиционирования](custom_partitioning_key.md#table_engines-custom_partitioning_key).
Для партиционирования по месяцам используйте выражение `toYYYYMM(date_column)`, где `date_column` — столбец с датой типа [Date](../../data_types/date.md#data_type-date). В этом случае имена партиций имеют формат `"YYYYMM"`.
@ -161,10 +164,34 @@ ClickHouse не требует уникального первичного кл
- Обеспечить дополнительную логику при слиянии кусков данных в движках [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) и [SummingMergeTree](summingmergetree.md#table_engine-summingmergetree).
Может потребоваться много полей в первичном ключе, даже если они не нужны для выполнения предыдущих пунктов.
Для этого имеет смысл задать отдельный *ключ сортировки*, отличающийся от первичного ключа.
Длинный первичный ключ будет негативно влиять на производительность вставки и потребление памяти, однако на производительность ClickHouse при запросах `SELECT` лишние столбцы в первичном ключе не влияют.
<a name="table_engines-mergetree-sorting_key"></a>
### Ключ сортировки, отличный от первичного ключа
Существует возможность задать ключ сортировки (выражение, по которому будут упорядочены строки в кусках
данных), отличающийся от первичного ключа (выражения, значения которого будут записаны в индексный файл для
каждой засечки). Кортеж выражения первичного ключа при этом должен быть префиксом кортежа выражения ключа
сортировки.
Данная возможность особенно полезна при использовании движков [SummingMergeTree](summingmergetree.md)
и [AggregatingMergeTree](aggregatingmergetree.md). В типичном сценарии использования этих движков таблица
содержит столбцы двух типов: *измерения* (dimensions) и *меры* (measures). Типичные запросы агрегируют
значения столбцов-мер с произвольной группировкой и фильтрацией по измерениям. Так как SummingMergeTree
и AggregatingMergeTree производят фоновую агрегацию строк с одинаковым значением ключа сортировки, приходится
добавлять в него все столбцы-измерения. В результате выражение ключа содержит большой список столбцов,
который приходится постоянно расширять при добавлении новых измерений.
В этом сценарии имеет смысл оставить в первичном ключе всего несколько столбцов, которые обеспечат эффективную
фильтрацию по индексу, а остальные столбцы-измерения добавить в выражение ключа сортировки.
[ALTER ключа сортировки](../../query_language/alter.md#query_language-queries-alter-key_alters) - легкая
операция, так как при одновременном добавлении нового столбца в таблицу и ключ сортировки не нужно изменять
данные кусков (они остаются упорядоченными и по новому выражению ключа).
### Использование индексов и партиций в запросах
Для запросов `SELECT` ClickHouse анализирует возможность использования индекса. Индекс может использоваться, если в секции `WHERE/PREWHERE`, в качестве одного из элементов конъюнкции, или целиком, есть выражение, представляющее операции сравнения на равенства, неравенства, а также `IN` или `LIKE` с фиксированным префиксом, над столбцами или выражениями, входящими в первичный ключ или ключ партиционирования, либо над некоторыми частично монотонными функциями от этих столбцов, а также логические связки над такими выражениями.
@ -199,7 +226,6 @@ SELECT count() FROM table WHERE CounterID = 34 OR URL LIKE '%upyachka%'
Ключ партиционирования по месяцам обеспечивает чтение только тех блоков данных, которые содержат даты из нужного диапазона. При этом блок данных может содержать данные за многие даты (до целого месяца). В пределах одного блока данные упорядочены по первичному ключу, который может не содержать дату в качестве первого столбца. В связи с этим, при использовании запроса с указанием условия только на дату, но не на префикс первичного ключа, будет читаться данных больше, чем за одну дату.
## Конкурентный доступ к данным
Для конкурентного доступа к таблице используется мультиверсионность. То есть, при одновременном чтении и обновлении таблицы, данные будут читаться из набора кусочков, актуального на момент запроса. Длинных блокировок нет. Вставки никак не мешают чтениям.

View File

@ -1,6 +1,6 @@
# ReplacingMergeTree
Движок отличается от [MergeTree](mergetree.md#table_engines-mergetree) тем, что выполняет удаление дублирующихся записей с одинаковым значением первичного ключа.
Движок отличается от [MergeTree](mergetree.md#table_engines-mergetree) тем, что выполняет удаление дублирующихся записей с одинаковым значением первичного ключа (точнее, с одинаковым значением [ключа сортировки](mergetree.md#table_engines-mergetree-sorting_key)).
Дедупликация данных производится лишь во время слияний. Слияние происходят в фоне в неизвестный момент времени, на который вы не можете ориентироваться. Некоторая часть данных может остаться необработанной. Хотя вы можете вызвать внеочередное слияние с помощью запроса `OPTIMIZE`, на это не стоит рассчитывать, так как запрос `OPTIMIZE` приводит к чтению и записи большого объёма данных.

View File

@ -2,7 +2,7 @@
# SummingMergeTree
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree). Отличие заключается в том, что для таблиц `SummingMergeTree` при слиянии кусков данных ClickHouse все строки с одинаковым первичным ключом заменяет на одну, которая хранит только суммы значений из столбцов с цифровым типом данных. Если первичный ключ подобран таким образом, что одному значению ключа соответствует много строк, это значительно уменьшает объем хранения и ускоряет последующую выборку данных.
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree). Отличие заключается в том, что для таблиц `SummingMergeTree` при слиянии кусков данных ClickHouse все строки с одинаковым первичным ключом (точнее, с одинаковым [ключом сортировки](mergetree.md#table_engines-mergetree-sorting_key)) заменяет на одну, которая хранит только суммы значений из столбцов с цифровым типом данных. Если ключ сортировки подобран таким образом, что одному значению ключа соответствует много строк, это значительно уменьшает объем хранения и ускоряет последующую выборку данных.
Мы рекомендуем использовать движок в паре с `MergeTree`. В `MergeTree` храните полные данные, а `SummingMergeTree` используйте для хранения агрегированных данных, например, при подготовке отчетов. Такой подход позволит не утратить ценные данные из-за неправильно выбранного первичного ключа.

View File

@ -66,9 +66,28 @@ MODIFY COLUMN name [type] [default_expr]
Запрос `ALTER` на изменение столбцов реплицируется. Соответствующие инструкции сохраняются в ZooKeeper, и затем каждая реплика их применяет. Все запросы `ALTER` выполняются в одном и том же порядке. Запрос ждёт выполнения соответствующих действий на всех репликах. Но при этом, запрос на изменение столбцов в реплицируемой таблице можно прервать, и все действия будут осуществлены асинхронно.
<a name="query_language-queries-alter-key_alters"></a>
### Манипуляции с ключевыми выражениями таблиц
Поддерживается операция:
``` sql
MODIFY ORDER BY new_expression
```
Работает только для таблиц семейства `MergeTree` (в том числе реплицированных). После выполнения запроса
[ключ сортировки](../operations/table_engines/mergetree.md#table_engines-mergetree-sorting_key) таблицы
заменяется на `new_expression` (выражение или кортеж выражений). Первичный ключ при этом остаётся прежним.
Операция затрагивает только метаданные. Чтобы сохранить свойство упорядоченности кусков данных по ключу
сортировки, разрешено добавлять в ключ только новые столбцы (т.е. столбцы, добавляемые командой `ADD COLUMN`
в том же запросе `ALTER`), у которых нет выражения по умолчанию.
### Манипуляции с партициями и кусками
Работает только для таблиц семейства `MergeTree`. Существуют следующие виды операций:
Работает только для таблиц семейства `MergeTree` (в том числе реплицированных). Существуют следующие виды
операций:
- `DETACH PARTITION` - перенести партицию в директорию detached и забыть про неё.
- `DROP PARTITION` - удалить партицию.

View File

@ -477,7 +477,7 @@ WHERE isNull(y)
Имеет такой же смысл, как и секция [WHERE](#query_language-queries-where). Отличие состоит в том, какие данные читаются из таблицы.
При использовании `PREWHERE`, из таблицы сначала читаются только столбцы, необходимые для выполнения `PREWHERE`. Затем читаются остальные столбцы, нужные для выполнения запроса, но из них только те блоки, в которых выражение в `PREWHERE` истинное.
`PREWHERE` имеет смысл использовать, если есть условия фильтрации, не подходящие под индексы, которые использует меньшинство столбцов из тех, что есть в запросе, но достаточно сильно фильтрует данные. Таким образом, сокращается количество читаемых данных.
`PREWHERE` имеет смысл использовать, если есть условия фильтрации, которые использует меньшинство столбцов из тех, что есть в запросе, но достаточно сильно фильтрует данные. Таким образом, сокращается количество читаемых данных.
Например, полезно писать `PREWHERE` для запросов, которые вынимают много столбцов, но в которых фильтрация производится лишь по нескольким столбцам.
@ -485,8 +485,6 @@ WHERE isNull(y)
В запросе могут быть одновременно указаны секции `PREWHERE` и `WHERE`. В этом случае, `PREWHERE` идёт перед `WHERE`.
Следует иметь ввиду, что указывать в `PREWHERE` только столбцы, по которым существует индекс, имеет мало смысла, так как при использовании индекса и так читаются лишь блоки данных, соответствующие индексу.
Если настройка `optimize_move_to_prewhere` выставлена в `1`, то при отсутствии `PREWHERE`, система будет автоматически переносить части выражений из `WHERE` в `PREWHERE` согласно некоторой эвристике.
### Секция GROUP BY

View File

@ -2,7 +2,7 @@
## 系统要求
如果从官方仓库安装需要确保您使用的是x86_64处理器构架的Linux并且支持SSE 4.2指令集
如果从官方仓库安装需要确保您使用的是x86\_64处理器构架的Linux并且支持SSE 4.2指令集
检查是否支持SSE 4.2
@ -14,12 +14,10 @@ grep -q sse4_2 /proc/cpuinfo && echo "SSE 4.2 supported" || echo "SSE 4.2 not su
基于rpm的系统,你可以使用第三方的安装包https://packagecloud.io/altinity/clickhouse 或者直接安装debian安装包。
ClickHouse还可以在FreeBSD与Mac OS X上工作。同时它可以在不支持SSE 4.2的x86_64构架和AArch64 CPUs上编译。
ClickHouse还可以在FreeBSD与Mac OS X上工作。同时它可以在不支持SSE 4.2的x86\_64构架和AArch64 CPUs上编译。
## 安装
为了测试和开发系统可以安装在单个服务器或普通PC机上。
### 为Debian/Ubuntu安装
在`/etc/apt/sources.list` (或创建`/etc/apt/sources.list.d/clickhouse.list`文件)中添加仓库:
@ -54,7 +52,7 @@ ClickHouse包含访问控制配置它们位于`users.xml`文件中(与'config
```text
Client: dbms/programs/clickhouse-client
Server: dbms/programs/clickhouse-server
```
```
在服务器中为数据创建如下目录:

View File

@ -1,5 +1,5 @@
# ODBC 驱动
- ClickHouse官方有 JDBC 的驱动。 见[这里](https://github.com/yandex/clickhouse-jdbc)。
- ClickHouse官方有 ODBC 的驱动。 见[这里](https://github.com/yandex/clickhouse-odbc)。
[来源文章](https://clickhouse.yandex/docs/zh/interfaces/odbc/) <!--hide-->

View File

@ -1,56 +1,56 @@
# Buffer
Buffers the data to write in RAM, periodically flushing it to another table. During the read operation, data is read from the buffer and the other table simultaneously.
缓冲数据写入 RAM 中,周期性地将数据刷新到另一个表。在读取操作时,同时从缓冲区和另一个表读取数据。
```
Buffer(database, table, num_layers, min_time, max_time, min_rows, max_rows, min_bytes, max_bytes)
```
Engine parameters:database, table The table to flush data to. Instead of the database name, you can use a constant expression that returns a string.num_layers Parallelism layer. Physically, the table will be represented as 'num_layers' of independent buffers. Recommended value: 16.min_time, max_time, min_rows, max_rows, min_bytes, and max_bytes are conditions for flushing data from the buffer.
引擎的参数databasetable - 要刷新数据的表。可以使用返回字符串的常量表达式而不是数据库名称。 num_layers - 并行层数。在物理上,该表将表示为 num_layers 个独立缓冲区。建议值为16。min_timemax_timemin_rowsmax_rowsmin_bytesmax_bytes - 从缓冲区刷新数据的条件。
Data is flushed from the buffer and written to the destination table if all the 'min' conditions or at least one 'max' condition are met.min_time, max_time Condition for the time in seconds from the moment of the first write to the buffer.min_rows, max_rows Condition for the number of rows in the buffer.min_bytes, max_bytes Condition for the number of bytes in the buffer.
如果满足所有 "min" 条件或至少一个 "max" 条件则从缓冲区刷新数据并将其写入目标表。min_timemax_time — 从第一次写入缓冲区时起以秒为单位的时间条件。min_rowsmax_rows - 缓冲区中行数的条件。min_bytesmax_bytes - 缓冲区中字节数的条件。
During the write operation, data is inserted to a 'num_layers' number of random buffers. Or, if the data part to insert is large enough (greater than 'max_rows' or 'max_bytes'), it is written directly to the destination table, omitting the buffer.
写入时,数据从 num_layers 个缓冲区中随机插入。或者,如果插入数据的大小足够大(大于 max_rows 或 max_bytes ),则会绕过缓冲区将其写入目标表。
The conditions for flushing the data are calculated separately for each of the 'num_layers' buffers. For example, if num_layers = 16 and max_bytes = 100000000, the maximum RAM consumption is 1.6 GB.
每个 "num_layers" 缓冲区刷新数据的条件是分别计算。例如,如果 num_layers = 16 且 max_bytes = 100000000则最大RAM消耗将为1.6 GB。
Example:
示例:
``` sql
CREATE TABLE merge.hits_buffer AS merge.hits ENGINE = Buffer(merge, hits, 16, 10, 100, 10000, 1000000, 10000000, 100000000)
```
Creating a 'merge.hits_buffer' table with the same structure as 'merge.hits' and using the Buffer engine. When writing to this table, data is buffered in RAM and later written to the 'merge.hits' table. 16 buffers are created. The data in each of them is flushed if either 100 seconds have passed, or one million rows have been written, or 100 MB of data have been written; or if simultaneously 10 seconds have passed and 10,000 rows and 10 MB of data have been written. For example, if just one row has been written, after 100 seconds it will be flushed, no matter what. But if many rows have been written, the data will be flushed sooner.
创建一个 "merge.hits_buffer" 表,其结构与 "merge.hits" 相同,并使用 Buffer 引擎。写入此表时,数据缓冲在 RAM 中,然后写入 "merge.hits" 表。创建了16个缓冲区。如果已经过了100秒或者已写入100万行或者已写入100 MB数据则刷新每个缓冲区的数据或者如果同时已经过了10秒并且已经写入了10,000行和10 MB的数据。例如如果只写了一行那么在100秒之后都会被刷新。但是如果写了很多行数据将会更快地刷新。
When the server is stopped, with DROP TABLE or DETACH TABLE, buffer data is also flushed to the destination table.
当服务器停止时,使用 DROP TABLE 或 DETACH TABLE缓冲区数据也会刷新到目标表。
You can set empty strings in single quotation marks for the database and table name. This indicates the absence of a destination table. In this case, when the data flush conditions are reached, the buffer is simply cleared. This may be useful for keeping a window of data in memory.
可以为数据库和表名在单个引号中设置空字符串。这表示没有目的地表。在这种情况下,当达到数据刷新条件时,缓冲器被简单地清除。这可能对于保持数据窗口在内存中是有用的。
When reading from a Buffer table, data is processed both from the buffer and from the destination table (if there is one).
Note that the Buffer tables does not support an index. In other words, data in the buffer is fully scanned, which might be slow for large buffers. (For data in a subordinate table, the index that it supports will be used.)
从 Buffer 表读取时,将从缓冲区和目标表(如果有)处理数据。
请注意Buffer 表不支持索引。换句话说,缓冲区中的数据被完全扫描,对于大缓冲区来说可能很慢。(对于目标表中的数据,将使用它支持的索引。)
If the set of columns in the Buffer table doesn't match the set of columns in a subordinate table, a subset of columns that exist in both tables is inserted.
如果 Buffer 表中的列集与目标表中的列集不匹配,则会插入两个表中存在的列的子集。
If the types don't match for one of the columns in the Buffer table and a subordinate table, an error message is entered in the server log and the buffer is cleared.
The same thing happens if the subordinate table doesn't exist when the buffer is flushed.
如果类型与 Buffer 表和目标表中的某列不匹配,则会在服务器日志中输入错误消息并清除缓冲区。
如果在刷新缓冲区时目标表不存在,则会发生同样的情况。
If you need to run ALTER for a subordinate table and the Buffer table, we recommend first deleting the Buffer table, running ALTER for the subordinate table, then creating the Buffer table again.
如果需要为目标表和 Buffer 表运行 ALTER我们建议先删除 Buffer 表,为目标表运行 ALTER然后再次创建 Buffer 表。
If the server is restarted abnormally, the data in the buffer is lost.
如果服务器异常重启,缓冲区中的数据将丢失。
PREWHERE, FINAL and SAMPLE do not work correctly for Buffer tables. These conditions are passed to the destination table, but are not used for processing data in the buffer. Because of this, we recommend only using the Buffer table for writing, while reading from the destination table.
PREWHEREFINAL 和 SAMPLE 对缓冲表不起作用。这些条件将传递到目标表但不用于处理缓冲区中的数据。因此我们建议只使用Buffer表进行写入同时从目标表进行读取。
When adding data to a Buffer, one of the buffers is locked. This causes delays if a read operation is simultaneously being performed from the table.
将数据添加到缓冲区时,其中一个缓冲区被锁定。如果同时从表执行读操作,则会导致延迟。
Data that is inserted to a Buffer table may end up in the subordinate table in a different order and in different blocks. Because of this, a Buffer table is difficult to use for writing to a CollapsingMergeTree correctly. To avoid problems, you can set 'num_layers' to 1.
插入到 Buffer 表中的数据可能以不同的顺序和不同的块写入目标表中。因此Buffer 表很难用于正确写入 CollapsingMergeTree。为避免出现问题您可以将 "num_layers" 设置为1。
If the destination table is replicated, some expected characteristics of replicated tables are lost when writing to a Buffer table. The random changes to the order of rows and sizes of data parts cause data deduplication to quit working, which means it is not possible to have a reliable 'exactly once' write to replicated tables.
如果目标表是复制表,则在写入 Buffer 表时会丢失复制表的某些预期特征。数据部分的行次序和大小的随机变化导致数据不能去重,这意味着无法对复制表进行可靠的 "exactly once" 写入。
Due to these disadvantages, we can only recommend using a Buffer table in rare cases.
由于这些缺点,我们只建议在极少数情况下使用 Buffer 表。
A Buffer table is used when too many INSERTs are received from a large number of servers over a unit of time and data can't be buffered before insertion, which means the INSERTs can't run fast enough.
当在单位时间内从大量服务器接收到太多 INSERTs 并且在插入之前无法缓冲数据时使用 Buffer 表,这意味着这些 INSERTs 不能足够快地执行。
Note that it doesn't make sense to insert data one row at a time, even for Buffer tables. This will only produce a speed of a few thousand rows per second, while inserting larger blocks of data can produce over a million rows per second (see the section "Performance").
请注意,一次插入一行数据是没有意义的,即使对于 Buffer 表也是如此。这将只产生每秒几千行的速度,而插入更大的数据块每秒可以产生超过一百万行(参见 "性能" 部分)。
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/buffer/) <!--hide-->
[Original article](https://clickhouse.yandex/docs/zh/operations/table_engines/buffer/) <!--hide-->

View File

@ -1,36 +1,34 @@
<a name="external-data"></a>
# External Data for Query Processing
ClickHouse allows sending a server the data that is needed for processing a query, together with a SELECT query. This data is put in a temporary table (see the section "Temporary tables") and can be used in the query (for example, in IN operators).
ClickHouse 允许向服务器发送处理查询所需的数据以及 SELECT 查询。这些数据放在一个临时表中(请参阅 "临时表" 一节),可以在查询中使用(例如,在 IN 操作符中)。
For example, if you have a text file with important user identifiers, you can upload it to the server along with a query that uses filtration by this list.
例如,如果您有一个包含重要用户标识符的文本文件,则可以将其与使用此列表过滤的查询一起上传到服务器。
If you need to run more than one query with a large volume of external data, don't use this feature. It is better to upload the data to the DB ahead of time.
如果需要使用大量外部数据运行多个查询,请不要使用该特性。最好提前把数据上传到数据库。
External data can be uploaded using the command-line client (in non-interactive mode), or using the HTTP interface.
可以使用命令行客户端(在非交互模式下)或使用 HTTP 接口上传外部数据。
In the command-line client, you can specify a parameters section in the format
在命令行客户端中,您可以指定格式的参数部分
```bash
--external --file=... [--name=...] [--format=...] [--types=...|--structure=...]
```
You may have multiple sections like this, for the number of tables being transmitted.
对于传输的表的数量,可能有多个这样的部分。
**--external** Marks the beginning of a clause.
**--file** Path to the file with the table dump, or -, which refers to stdin.
Only a single table can be retrieved from stdin.
**--external** 标记子句的开始。
**--file** 带有表存储的文件的路径或者它指的是STDIN。
只能从 stdin 中检索单个表。
The following parameters are optional: **--name** Name of the table. If omitted, _data is used.
**--format** Data format in the file. If omitted, TabSeparated is used.
以下的参数是可选的:**--name** 表的名称,如果省略,则采用 _data。
**--format** 文件中的数据格式。 如果省略,则使用 TabSeparated。
One of the following parameters is required:**--types** A list of comma-separated column types. For example: `UInt64,String`. The columns will be named _1, _2, ...
**--structure** The table structure in the format`UserID UInt64`, `URL String`. Defines the column names and types.
以下的参数必选一个:**--types** 逗号分隔列类型的列表。例如:`UInt64,String`。列将被命名为 _1_2...
**--structure** 表结构的格式 `UserID UInt64``URL String`。定义列的名字以及类型。
The files specified in 'file' will be parsed by the format specified in 'format', using the data types specified in 'types' or 'structure'. The table will be uploaded to the server and accessible there as a temporary table with the name in 'name'.
在 "file" 中指定的文件将由 "format" 中指定的格式解析,使用在 "types" 或 "structure" 中指定的数据类型。该表将被上传到服务器,并在作为名称为 "name"临时表。
Examples:
示例:
```bash
echo -ne "1\n2\n3\n" | clickhouse-client --query="SELECT count() FROM test.visits WHERE TraficSourceID IN _data" --external --file=- --types=Int8
@ -43,9 +41,9 @@ cat /etc/passwd | sed 's/:/\t/g' | clickhouse-client --query="SELECT shell, coun
/bin/sync 1
```
When using the HTTP interface, external data is passed in the multipart/form-data format. Each table is transmitted as a separate file. The table name is taken from the file name. The 'query_string' is passed the parameters 'name_format', 'name_types', and 'name_structure', where 'name' is the name of the table that these parameters correspond to. The meaning of the parameters is the same as when using the command-line client.
当使用HTTP接口时外部数据以 multipart/form-data 格式传递。每个表作为一个单独的文件传输。表名取自文件名。"query_string" 传递参数 "name_format"、"name_types"和"name_structure",其中 "name" 是这些参数对应的表的名称。参数的含义与使用命令行客户端时的含义相同。
Example:
示例:
```bash
cat /etc/passwd | sed 's/:/\t/g' > passwd.tsv
@ -58,7 +56,7 @@ curl -F 'passwd=@passwd.tsv;' 'http://localhost:8123/?query=SELECT+shell,+count(
/bin/sync 1
```
For distributed query processing, the temporary tables are sent to all the remote servers.
对于分布式查询,将临时表发送到所有远程服务器。
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/external_data/) <!--hide-->
[Original article](https://clickhouse.yandex/docs/zh/operations/table_engines/external_data/) <!--hide-->

View File

@ -1,8 +1,7 @@
# Log
Log differs from TinyLog in that a small file of "marks" resides with the column files. These marks are written on every data block and contain offsets that indicate where to start reading the file in order to skip the specified number of rows. This makes it possible to read table data in multiple threads.
For concurrent data access, the read operations can be performed simultaneously, while write operations block reads and each other.
The Log engine does not support indexes. Similarly, if writing to a table failed, the table is broken, and reading from it returns an error. The Log engine is appropriate for temporary data, write-once tables, and for testing or demonstration purposes.
日志与 TinyLog 的不同之处在于,"标记" 的小文件与列文件存在一起。这些标记写在每个数据块上并且包含偏移量这些偏移量指示从哪里开始读取文件以便跳过指定的行数。这使得可以在多个线程中读取表数据。对于并发数据访问可以同时执行读取操作而写入操作则阻塞读取和其它写入。Log 引擎不支持索引。同样如果写入表失败则该表将被破坏并且从该表读取将返回错误。Log 引擎适用于临时数据write-once 表以及测试或演示目的。
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/log/) <!--hide-->
[Original article](https://clickhouse.yandex/docs/zh/operations/table_engines/log/) <!--hide-->

View File

@ -1,13 +1,9 @@
# Memory
The Memory engine stores data in RAM, in uncompressed form. Data is stored in exactly the same form as it is received when read. In other words, reading from this table is completely free.
Concurrent data access is synchronized. Locks are short: read and write operations don't block each other.
Indexes are not supported. Reading is parallelized.
Maximal productivity (over 10 GB/sec) is reached on simple queries, because there is no reading from the disk, decompressing, or deserializing data. (We should note that in many cases, the productivity of the MergeTree engine is almost as high.)
When restarting a server, data disappears from the table and the table becomes empty.
Normally, using this table engine is not justified. However, it can be used for tests, and for tasks where maximum speed is required on a relatively small number of rows (up to approximately 100,000,000).
Memory 引擎以未压缩的形式将数据存储在 RAM 中。数据完全以读取时获得的形式存储。换句话说从这张表中读取是很轻松的。并发数据访问是同步的。锁范围小读写操作不会相互阻塞。不支持索引。阅读是并行化的。在简单查询上达到最大生产率超过10 GB /秒),因为没有磁盘读取,不需要解压缩或反序列化数据。(值得注意的是,在许多情况下,与 MergeTree 引擎的性能几乎一样高。重新启动服务器时表中的数据消失表将变为空。通常使用此表引擎是不合理的。但是它可用于测试以及在相对较少的行最多约100,000,000上需要最高性能的查询。
The Memory engine is used by the system for temporary tables with external query data (see the section "External data for processing a query"), and for implementing GLOBAL IN (see the section "IN operators").
Memory 引擎是由系统用于临时表进行外部数据的查询(请参阅 "外部数据用于请求处理" 部分),以及用于实现 `GLOBAL IN`(请参见 "IN 运算符" 部分)。
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/memory/) <!--hide-->
[Original article](https://clickhouse.yandex/docs/zh/operations/table_engines/memory/) <!--hide-->

View File

@ -1,21 +1,15 @@
# TinyLog
The simplest table engine, which stores data on a disk.
Each column is stored in a separate compressed file.
When writing, data is appended to the end of files.
最简单的表引擎,用于将数据存储在磁盘上。每列都存储在单独的压缩文件中。写入时,数据将附加到文件末尾。
Concurrent data access is not restricted in any way:
并发数据访问不受任何限制:
- 如果同时从表中读取并在不同的查询中写入,则读取操作将抛出异常
- 如果同时写入多个查询中的表,则数据将被破坏。
- If you are simultaneously reading from a table and writing to it in a different query, the read operation will complete with an error.
- If you are writing to a table in multiple queries simultaneously, the data will be broken.
这种表引擎的典型用法是 write-once首先只写入一次数据然后根据需要多次读取。查询在单个流中执行。换句话说此引擎适用于相对较小的表建议最多1,000,000行。如果您有许多小表则使用此表引擎是适合的因为它比Log引擎更简单需要打开的文件更少。当您拥有大量小表时可能会导致性能低下但在可能已经在其它 DBMS 时使用过,则您可能会发现切换使用 TinyLog 类型的表更容易。**不支持索引**。
The typical way to use this table is write-once: first just write the data one time, then read it as many times as needed.
Queries are executed in a single stream. In other words, this engine is intended for relatively small tables (recommended up to 1,000,000 rows).
It makes sense to use this table engine if you have many small tables, since it is simpler than the Log engine (fewer files need to be opened).
The situation when you have a large number of small tables guarantees poor productivity, but may already be used when working with another DBMS, and you may find it easier to switch to using TinyLog types of tables.
**Indexes are not supported.**
In Yandex.Metrica, TinyLog tables are used for intermediary data that is processed in small batches.
在 Yandex.Metrica 中TinyLog 表用于小批量处理的中间数据。
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/tinylog/) <!--hide-->
[Original article](https://clickhouse.yandex/docs/zh/operations/table_engines/tinylog/) <!--hide-->