提交 38c0442e 编写于 作者: B BayoNet

Changes in accordance with comments from the developers.

上级 1b0d7361
......@@ -59,7 +59,13 @@ For elements in a nested data structure, the function checks for the existence o
Allows building a unicode-art diagram.
`bar (x, min, max, width)` – Draws a band with a width proportional to (x - min) and equal to 'width' characters when x == max.`min, max` – Integer constants. The value must fit in Int64.`width` – Constant, positive number, may be a fraction.
`bar (x, min, max, width)` draws a band with a width proportional to `(x - min)` and equal to `width` characters when `x = max`.
Parameters:
- `x` – Value to display.
- `min, max` – Integer constants. The value must fit in Int64.
- `width` – Constant, positive number, may be a fraction.
The band is drawn with accuracy to one eighth of a symbol.
......
......@@ -5,14 +5,16 @@ The search substring or regular expression must be a constant in all these funct
## position(haystack, needle)
Search for the 'needle' substring in the 'haystack' string.
Search for the `needle` substring in the `haystack` string.
Returns the position (in bytes) of the found substring, starting from 1, or returns 0 if the substring was not found.
It has also chimpanzees.
For case-insensitive search use `positionCaseInsensitive` function.
## positionUTF8(haystack, needle)
The same as 'position', but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
There is also a positionCaseInsensitiveUTF8 function.
The same as `position`, but the position is returned in Unicode code points. Works under the assumption that the string contains a set of bytes representing a UTF-8 encoded text. If this assumption is not met, it returns some result (it doesn't throw an exception).
For case-insensitive search use `positionCaseInsensitiveUTF8` function.
## match(haystack, pattern)
......@@ -49,4 +51,3 @@ For other regular expressions, the code is the same as for the 'match' function.
## notLike(haystack, pattern), haystack NOT LIKE pattern operator
The same thing as 'like', but negative.
......@@ -20,5 +20,7 @@ CREATE TABLE wikistat
Loading data:
```bash
for i in {2007..2016}; do for j in {01..12}; do echo $i-$j >&2; curl -sSL "http://dumps.wikimedia.org/other/pagecounts-raw/$i/$i-$j/" | grep -oE 'pagecounts-[0-9]+-[0-9]+\.gz'; done; done | sort | uniq | tee links.txtcat links.txt | while read link; do wget http://dumps.wikimedia.org/other/pagecounts-raw/$(echo $link | sed -r 's/pagecounts-([0-9]{4})([0-9]{2})[0-9]{2}-[0-9]+\.gz/\1/')/$(echo $link | sed -r 's/pagecounts-([0-9]{4})([0-9]{2})[0-9]{2}-[0-9]+\.gz/\1-\2/')/$link; donels -1 /opt/wikistat/ | grep gz | while read i; do echo $i; gzip -cd /opt/wikistat/$i | ./wikistat-loader --time="$(echo -n $i | sed -r 's/pagecounts-([0-9]{4})([0-9]{2})([0-9]{2})-([0-9]{2})([0-9]{2})([0-9]{2})\.gz/\1-\2-\3 \4-00-00/')" | clickhouse-client --query="INSERT INTO wikistat FORMAT TabSeparated"; done
for i in {2007..2016}; do for j in {01..12}; do echo $i-$j >&2; curl -sSL "http://dumps.wikimedia.org/other/pagecounts-raw/$i/$i-$j/" | grep -oE 'pagecounts-[0-9]+-[0-9]+\.gz'; done; done | sort | uniq | tee links.txt
cat links.txt | while read link; do wget http://dumps.wikimedia.org/other/pagecounts-raw/$(echo $link | sed -r 's/pagecounts-([0-9]{4})([0-9]{2})[0-9]{2}-[0-9]+\.gz/\1/')/$(echo $link | sed -r 's/pagecounts-([0-9]{4})([0-9]{2})[0-9]{2}-[0-9]+\.gz/\1-\2/')/$link; done
ls -1 /opt/wikistat/ | grep gz | while read i; do echo $i; gzip -cd /opt/wikistat/$i | ./wikistat-loader --time="$(echo -n $i | sed -r 's/pagecounts-([0-9]{4})([0-9]{2})([0-9]{2})-([0-9]{2})([0-9]{2})([0-9]{2})\.gz/\1-\2-\3 \4-00-00/')" | clickhouse-client --query="INSERT INTO wikistat FORMAT TabSeparated"; done
```
......@@ -51,7 +51,7 @@ The maximum amount of RAM to use for running a user's queries on a single server
Default values are defined in [Settings.h](https://github.com/yandex/ClickHouse/blob/master/dbms/src/Interpreters/Settings.h#L244). By default, the amount is not restricted (`max_memory_usage_for_user = 0`).
See also the descriptions of [max_memory_usage]( and #settings_max_memory_usage).
See also the description of [max_memory_usage](#settings_max_memory_usage).
## max_memory_usage_for_all_queries
......@@ -59,7 +59,7 @@ The maximum amount of RAM to use for running all queries on a single server.
Default values are defined in [Settings.h](https://github.com/yandex/ClickHouse/blob/master/dbms/src/Interpreters/Settings.h#L245). By default, the amount is not restricted (`max_memory_usage_for_all_queries = 0`).
See also the descriptions of [max_memory_usage]( and #settings_max_memory_usage).
See also the description of [max_memory_usage](#settings_max_memory_usage).
## max_rows_to_read
......@@ -193,4 +193,3 @@ Maximum number of bytes (uncompressed data) that can be passed to a remote serve
## transfer_overflow_mode
What to do when the amount of data exceeds one of the limits: 'throw' or 'break'. By default, throw.
# Settings profiles
A settings profile is a collection of settings grouped under the same name. Each ClickHouse user has a profile.
To apply all the settings in a profile, set 'profile'. Example:
To apply all the settings in a profile, set `profile`.
Example:
Setting `web` profile.
```sql
SET profile = 'web'
```
- Load the 'web' profile. In other words, set all the options that belong to the 'web' profile.
Settings profiles are declared in the user config file. This is usually `users.xml`.
Example:
```xml
<!-- Settings profiles -->
<profiles>
<!Default settings -->
<!-- Default settings -->
<default>
<!-- The maximum number of threads when running a single query. --> <max_threads>8</max_threads> </default> <!-- Settings for queries from the user interface -->
<web>
......@@ -50,7 +53,6 @@ Example:
</profiles>
```
The example specifies two profiles: `default` and `web`. The `default` profile has a special purpose: it must always be present and is applied when starting the server. In other words, the 'default' profile contains default settings. The 'web' profile is a regular profile that can be set using the SET query or using a URL parameter in an HTTP query.
Settings profiles can inherit from each other. To use inheritance, indicate the 'profile' setting before the other settings that are listed in the profile.
The example specifies two profiles: `default` and `web`. The `default` profile has a special purpose: it must always be present and is applied when starting the server. In other words, the `default` profile contains default settings. The `web` profile is a regular profile that can be set using the `SET` query or using a URL parameter in an HTTP query.
Settings profiles can inherit from each other. To use inheritance, indicate the `profile` setting before the other settings that are listed in the profile.
......@@ -312,10 +312,10 @@ Data directory: `/var/lib/clickhouse/data/database/table/`,where `/var/lib/click
```bash
$ ls -l /var/lib/clickhouse/data/test/visits/
total 48
drwxrwxrwx 2 clickhouse clickhouse 20480 may 13 02:58 20140317_20140323_2_2_0
drwxrwxrwx 2 clickhouse clickhouse 20480 may 13 02:58 20140317_20140323_4_4_0
drwxrwxrwx 2 clickhouse clickhouse 4096 may 13 02:55 detached
-rw-rw-rw- 1 clickhouse clickhouse 2 may 13 02:58 increment.txt
drwxrwxrwx 2 clickhouse clickhouse 20480 May 5 02:58 20140317_20140323_2_2_0
drwxrwxrwx 2 clickhouse clickhouse 20480 May 5 02:58 20140317_20140323_4_4_0
drwxrwxrwx 2 clickhouse clickhouse 4096 May 5 02:55 detached
-rw-rw-rw- 1 clickhouse clickhouse 2 May 5 02:58 increment.txt
```
Here, `20140317_20140323_2_2_0` and ` 20140317_20140323_4_4_0` are the directories of data parts.
......
......@@ -8,8 +8,7 @@ The table engine (type of table) determines:
- Use of indexes, if present.
- Whether multithreaded request execution is possible.
- Data replication.
- When reading data, the engine is only required to extract the necessary set of columns.
However, in some cases, the query may be partially processed inside the table engine.
Note that for most serious tasks, you should use engines from the MergeTree family.
When reading data, the engine is only required to extract the necessary set of columns. However, in some cases, the query may be partially processed inside the table engine.
Note that for most serious tasks, you should use engines from the `MergeTree` family.
......@@ -2,9 +2,11 @@
The Merge engine (not to be confused with `MergeTree`) does not store data itself, but allows reading from any number of other tables simultaneously.
Reading is automatically parallelized. Writing to a table is not supported. When reading, the indexes of tables that are actually being read are used, if they exist.
The Merge engine accepts parameters: the database name and a regular expression for tables. Example.
The Merge engine accepts parameters: the database name and a regular expression for tables.
```text
Example:
```
Merge(hits, '^WatchLog')
```
......@@ -35,4 +37,3 @@ Virtual columns differ from normal columns in the following ways:
A Merge type table contains a virtual _table column with the String type. (If the table already has a _table column, the virtual column is named _table1, and if it already has _table1, it is named _table2, and so on.) It contains the name of the table that data was read from.
If the WHERE or PREWHERE clause contains conditions for the '_table' column that do not depend on other table columns (as one of the conjunction elements, or as an entire expression), these conditions are used as an index. The conditions are performed on a data set of table names to read data from, and the read operation will be performed from only those tables that the condition was triggered on.
......@@ -48,9 +48,13 @@
Позволяет построить unicode-art диаграмму.
`bar(x, min, max, width)` - рисует полосу ширины пропорциональной (x - min) и равной width символов при x == max.
`min, max` - целочисленные константы, значение должно помещаться в Int64.
`width` - константа, положительное число, может быть дробным.
`bar(x, min, max, width)` рисует полосу ширины пропорциональной `(x - min)` и равной `width` символов при `x = max`.
Параметры:
- `x` — Величина для отображения.
- `min, max` — Целочисленные константы, значение должно помещаться в `Int64`.
- `width` — Константа, положительное число, может быть дробным.
Полоса рисуется с точностью до одной восьмой символа.
......
......@@ -4,13 +4,15 @@
Во всех функциях, подстрока для поиска или регулярное выражение, должно быть константой.
## position(haystack, needle)
Поиск подстроки needle в строке haystack.
Поиск подстроки `needle` в строке `haystack`.
Возвращает позицию (в байтах) найденной подстроки, начиная с 1, или 0, если подстрока не найдена.
Есть также функция positionCaseInsensitive.
Для поиска без учета регистра используйте функцию `positionCaseInsensitive`.
## positionUTF8(haystack, needle)
Так же, как position, но позиция возвращается в кодовых точках Unicode. Работает при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8. Если допущение не выполнено - то возвращает какой-нибудь результат (не кидает исключение).
Есть также функция positionCaseInsensitiveUTF8.
Так же, как `position`, но позиция возвращается в кодовых точках Unicode. Работает при допущении, что строка содержит набор байт, представляющий текст в кодировке UTF-8. Если допущение не выполнено - то возвращает какой-нибудь результат (не кидает исключение).
Для поиска без учета регистра используйте функцию `positionCaseInsensitiveUTF8`.
## match(haystack, pattern)
Проверка строки на соответствие регулярному выражению pattern. Регулярное выражение re2.
......
# Профили настроек
Профили настроек - это множество настроек, сгруппированных под одним именем. Для каждого пользователя ClickHouse указывается некоторый профиль.
Все настройки профиля можно применить, установив настройку с именем profile. Пример:
Все настройки профиля можно применить, установив настройку `profile`.
Пример:
Установить профиль `web`.
```sql
SET profile = 'web'
```
- установить профиль web - то есть, установить все настройки, относящиеся к профилю web.
Профили настроек объявляются в конфигурационном файле пользователей. Обычно это - `users.xml`.
Профили настроек объявляются в конфигурационном файле пользователей. Обычно это `users.xml`.
Пример:
```xml
......@@ -54,6 +56,6 @@ SET profile = 'web'
</profiles>
```
В примере задано два профиля: `default` и `web`. Профиль `default` имеет специальное значение - он всегда обязан присутствовать и применяется при запуске сервера. То есть, профиль default содержит настройки по умолчанию. Профиль web - обычный профиль, который может быть установлен с помощью запроса SET или с помощью параметра URL при запросе по HTTP.
В примере задано два профиля: `default` и `web`. Профиль `default` имеет специальное значение - он всегда обязан присутствовать и применяется при запуске сервера. То есть, профиль `default` содержит настройки по умолчанию. Профиль `web` - обычный профиль, который может быть установлен с помощью запроса `SET` или с помощью параметра URL при запросе по HTTP.
Профили настроек могут наследоваться от друг-друга - это реализуется указанием настройки profile перед остальными настройками, перечисленными в профиле.
Профили настроек могут наследоваться от друг-друга - это реализуется указанием настройки `profile` перед остальными настройками, перечисленными в профиле.
......@@ -308,10 +308,10 @@ SELECT * FROM system.parts WHERE active
```bash
$ ls -l /var/lib/clickhouse/data/test/visits/
total 48
drwxrwxrwx 2 clickhouse clickhouse 20480 may 13 02:58 20140317_20140323_2_2_0
drwxrwxrwx 2 clickhouse clickhouse 20480 may 13 02:58 20140317_20140323_4_4_0
drwxrwxrwx 2 clickhouse clickhouse 4096 may 13 02:55 detached
-rw-rw-rw- 1 clickhouse clickhouse 2 may 13 02:58 increment.txt
drwxrwxrwx 2 clickhouse clickhouse 20480 May 5 02:58 20140317_20140323_2_2_0
drwxrwxrwx 2 clickhouse clickhouse 20480 May 5 02:58 20140317_20140323_4_4_0
drwxrwxrwx 2 clickhouse clickhouse 4096 May 5 02:55 detached
-rw-rw-rw- 1 clickhouse clickhouse 2 May 5 02:58 increment.txt
```
Здесь `20140317_20140323_2_2_0`, `20140317_20140323_4_4_0` - директории кусков.
......
......@@ -2,13 +2,13 @@
Движок таблицы (тип таблицы) определяет:
- как и где хранятся данные - куда их писать и откуда читать;
- какие запросы поддерживаются, и каким образом;
- конкуррентный доступ к данным;
- использование индексов, если есть;
- возможно ли многопоточное выполнение запроса;
- репликацию данных;
- при чтении, движок обязан лишь достать нужный набор столбцов;
но в некоторых случаях, запрос может быть частично обработан в рамках движка таблицы.
Забегая вперёд, заметим, что для большинства серьёзных задач, следует использовать движки семейства MergeTree.
- Как и где хранятся данные, куда их писать и откуда читать.
- Какие запросы поддерживаются и каким образом.
- Конкурентный доступ к данным.
- Использование индексов, если есть.
- Возможно ли многопоточное выполнение запроса.
- Параметры репликации данных.
При чтении, движок обязан лишь выдать запрошенные столбцы, но в некоторых случаях движок может частично обрабатывать данные при ответе на запрос.
Для большинства серьёзных задач, следует использовать движки семейства `MergeTree`.
# Merge
Движок Merge (не путайте с движком `MergeTree`) не хранит данные самостоятельно, а позволяет читать одновременно из произвольного количества других таблиц.
Движок `Merge` (не путайте с движком `MergeTree`) не хранит данные самостоятельно, а позволяет читать одновременно из произвольного количества других таблиц.
Чтение автоматически распараллеливается. Запись в таблицу не поддерживается. При чтении будут использованы индексы тех таблиц, из которых реально идёт чтение, если они существуют.
Движок Merge принимает параметры: имя базы данных и регулярное выражение для таблиц. Пример.
Движок `Merge` принимает параметры: имя базы данных и регулярное выражение для таблиц.
```text
Пример:
```
Merge(hits, '^WatchLog')
```
Данные будут читаться из таблиц в базе hits, имена которых соответствуют регулярному выражению '`^WatchLog`'.
Данные будут читаться из таблиц в базе `hits`, имена которых соответствуют регулярному выражению '`^WatchLog`'.
Вместо имени базы данных может использоваться константное выражение, возвращающее строку. Например, `currentDatabase()`.
Регулярные выражения — [re2](https://github.com/google/re2) (поддерживает подмножество PCRE), регистрозависимые.
Смотрите замечание об экранировании в регулярных выражениях в разделе "match".
При выборе таблиц для чтения, сама Merge-таблица не будет выбрана, даже если попадает под регулярное выражение, чтобы не возникло циклов.
Впрочем, вы можете создать две Merge-таблицы, которые будут пытаться бесконечно читать данные друг друга, но делать этого не нужно.
При выборе таблиц для чтения, сама `Merge`-таблица не будет выбрана, даже если попадает под регулярное выражение, чтобы не возникло циклов.
Впрочем, вы можете создать две `Merge`-таблицы, которые будут пытаться бесконечно читать данные друг друга, но делать этого не нужно.
Типичный способ использования движка Merge — работа с большим количеством таблиц типа TinyLog, как с одной.
Типичный способ использования движка `Merge` — работа с большим количеством таблиц типа `TinyLog`, как с одной.
## Виртуальные столбцы
Виртуальные столбцы — столбцы, предоставляемые движком таблиц независимо от определения таблицы. То есть, такие столбцы не указываются в CREATE TABLE, но доступны для SELECT-а.
Виртуальные столбцы — столбцы, предоставляемые движком таблиц независимо от определения таблицы. То есть, такие столбцы не указываются в `CREATE TABLE`, но доступны для `SELECT`.
Виртуальные столбцы отличаются от обычных следующими особенностями:
- они не указываются в определении таблицы;
- в них нельзя вставить данные при INSERT-е;
- при INSERT-е без указания списка столбцов виртуальные столбцы не учитываются;
- в них нельзя вставить данные при `INSERT`;
- при `INSERT` без указания списка столбцов виртуальные столбцы не учитываются;
- они не выбираются при использовании звёздочки (`SELECT *`);
- виртуальные столбцы не показываются в запросах `SHOW CREATE TABLE` и `DESC TABLE`;
Таблица типа Merge содержит виртуальный столбец _table типа String. (Если в таблице уже есть столбец _table, то виртуальный столбец называется _table1; если уже есть _table1, то _table2 и т. п.) Он содержит имя таблицы, из которой были прочитаны данные.
Таблица типа `Merge` содержит виртуальный столбец `_table` типа `String`. (Если в таблице уже есть столбец `_table`, то виртуальный столбец называется `_table1`; если уже есть `_table1`, то `_table2` и т. п.) Он содержит имя таблицы, из которой были прочитаны данные.
Если секция WHERE/PREWHERE содержит (в качестве одного из элементов конъюнкции или в качестве всего выражения) условия на столбец _table, не зависящие от других столбцов таблицы, то эти условия используются как индекс: условия выполняются над множеством имён таблиц, из которых нужно читать данные, и чтение будет производиться только из тех таблиц, для которых условия сработали.
Если секция `WHERE/PREWHERE` содержит (в качестве одного из элементов конъюнкции или в качестве всего выражения) условия на столбец `_table`, не зависящие от других столбцов таблицы, то эти условия используются как индекс: условия выполняются над множеством имён таблиц, из которых нужно читать данные, и чтение будет производиться только из тех таблиц, для которых условия сработали.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册