提交 5182b600 编写于 作者: A Alexey Milovidov

Fixed newlines in .rst files before code blocks [#CLICKHOUSE-2].

for i in $(find . -name '*.rst'); do grep -F -q '.. code-block:: ' $i && cat $i | sed -r -e 's/$/<NEWLINE>/' | tr -d '\n' | sed -r -e 's/([^>])<NEWLINE>.. code-block::/\1<NEWLINE><NEWLINE>.. code-block::/g' | sed -r -e 's/<NEWLINE>/\n/g' > ${i}.tmp && mv ${i}.tmp ${i}; done
上级 91b55994
......@@ -253,6 +253,7 @@ ip_trie
The table stores IP prefixes for each key (IP address), which makes it possible to map IP addresses to metadata such as ASN or threat score.
Example: in the table there are prefixes matches to AS number and country:
.. code-block:: text
prefix asn cca2
......
......@@ -10,6 +10,7 @@ If you need to run more than one query with a large volume of external data, don
External data can be uploaded using the command-line client (in non-interactive mode), or using the HTTP interface.
In the command-line client, you can specify a parameters section in the format
.. code-block:: bash
--external --file=... [--name=...] [--format=...] [--types=...|--structure=...]
......@@ -31,6 +32,7 @@ One of the following parameters is required:
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 ``name``.
Examples:
.. code-block:: bash
echo -ne "1\n2\n3\n" | clickhouse-client --query="SELECT count() FROM test.visits WHERE TraficSourceID IN _data" --external --file=- --types=Int8
......@@ -45,6 +47,7 @@ Examples:
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' passes 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.
Example:
.. code-block:: bash
cat /etc/passwd | sed 's/:/\t/g' > passwd.tsv
......
......@@ -2,6 +2,7 @@ TSKV
----
Similar to TabSeparated, but displays data in name=value format. Names are displayed just as in TabSeparated. Additionally, a ``=`` symbol is displayed.
.. code-block:: text
SearchPhrase= count()=8267016
......
......@@ -33,6 +33,7 @@ visitParamExtractRaw(params, name)
Returns the value of a field, including separators.
Examples:
.. code-block:: text
visitParamExtractRaw('{"abc":"\\n\\u0000"}', 'abc') = '"\\n\\u0000"'
......@@ -43,6 +44,7 @@ visitParamExtractString(params, name)
Parses the string in double quotes. The value is unescaped. If unescaping failed, it returns an empty string.
Examples:
.. code-block:: text
visitParamExtractString('{"abc":"\\n\\u0000"}', 'abc') = '\n\0'
......
......@@ -53,11 +53,13 @@ To do transformations on DateTime in given time zone, pass second argument with
└─────────────────────┴─────────────────────┘
To format DateTime in given time zone:
.. code-block:: text
toString(now(), 'Asia/Yekaterinburg')
To get unix timestamp for string with datetime in specified time zone:
.. code-block:: text
toUnixTimestamp('2000-01-01 00:00:00', 'Asia/Yekaterinburg')
......
......@@ -73,6 +73,7 @@ URLPathHierarchy(URL)
"""""""""""""""""""""
The same thing, but without the protocol and host in the result. The / element (root) is not included. Example:
This function is used for implementing tree-view reports by URL in Yandex.Metrica.
.. code-block:: text
URLPathHierarchy('https://example.com/browse/CONV-6788') =
......
......@@ -23,6 +23,7 @@ Installing from packages
~~~~~~~~~~~~~~~~~~~~~~~~
In `/etc/apt/sources.list` (or in a separate `/etc/apt/sources.list.d/clickhouse.list` file), add the repository:
.. code-block:: text
deb http://repo.yandex.ru/clickhouse/trusty stable main
......@@ -30,6 +31,7 @@ In `/etc/apt/sources.list` (or in a separate `/etc/apt/sources.list.d/clickhouse
For other Ubuntu versions, replace `trusty` to `xenial` or `precise`.
Then run:
.. code-block:: bash
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv E0C56BD4 # optional
......@@ -49,12 +51,14 @@ Installing from source
To build, follow the instructions in build.md (for Linux) or in build_osx.md (for Mac OS X).
You can compile packages and install them. You can also use programs without installing packages.
.. code-block:: text
Client: dbms/src/Client/
Server: dbms/src/Server/
For the server, create a catalog with data, such as:
.. code-block:: text
/opt/clickhouse/data/default/
......@@ -76,6 +80,7 @@ Launch
------
To start the server (as a daemon), run:
.. code-block:: bash
sudo service clickhouse-server start
......@@ -85,6 +90,7 @@ View the logs in the catalog `/var/log/clickhouse-server/`
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:
.. code-block:: bash
clickhouse-server --config-file=/etc/clickhouse-server/config.xml
......@@ -92,12 +98,14 @@ You can also launch the server from the console:
In this case, the log will be printed to the console, which is convenient during development. If the configuration file is in the current directory, you 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:
.. code-block:: 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. For example:
.. code-block:: bash
clickhouse-client --host=example.com
......@@ -105,6 +113,7 @@ The client can be used for connecting to a remote server. For example:
For more information, see the section "Command-line client".
Checking the system:
.. code-block:: bash
milovidov@hostname:~/work/metrica/src/dbms/src/Client$ ./clickhouse-client
......
Command-line client
-------------------
To work for command line you can use ``clickhouse-client``:
.. code-block:: bash
$ clickhouse-client
......@@ -38,6 +39,7 @@ Only works in non-interactive mode.
``--stacktrace`` - If specified, also prints the stack trace if an exception occurs.
``--config-file`` - Name of the configuration file that has additional settings or changed defaults for the settings listed above.
By default, files are searched for in this order:
.. code-block:: text
./clickhouse-client.xml
......@@ -53,6 +55,7 @@ To use batch mode, specify the 'query' parameter, or send data to 'stdin' (it ve
Similar to the HTTP interface, when using the 'query' parameter and sending data to 'stdin', the request is a concatenation of the 'query' parameter, a line break, and the data in 'stdin'. This is convenient for large INSERT queries.
Examples for insert data via clickhouse-client:
.. code-block:: bash
echo -ne "1, 'some text', '2016-08-14 00:00:00'\n2, 'some more text', '2016-08-14 00:00:01'" | clickhouse-client --database=test --query="INSERT INTO test FORMAT CSV";
......
......@@ -161,16 +161,19 @@ By default, the database that is registered in the server settings is used as th
The username and password can be indicated in one of two ways:
1. Using HTTP Basic Authentication. Example:
.. code-block:: bash
echo 'SELECT 1' | curl 'http://user:password@localhost:8123/' -d @-
2. In the 'user' and 'password' URL parameters. Example:
.. code-block:: bash
echo 'SELECT 1' | curl 'http://localhost:8123/?user=user&password=password' -d @-
3. Using 'X-ClickHouse-User' and 'X-ClickHouse-Key' headers. Example:
.. code-block:: bash
echo 'SELECT 1' | curl -H "X-ClickHouse-User: user" -H "X-ClickHouse-Key: password" 'http://localhost:8123/' -d @-
......
......@@ -4,6 +4,7 @@ What is ClickHouse?
ClickHouse is a columnar DBMS for OLAP.
In a "normal" row-oriented DBMS, data is stored in this order:
.. code-block:: text
5123456789123456789 1 Eurobasket - Greece - Bosnia and Herzegovina - example.com 1 2011-09-01 01:03:02 6274717 1294101174 11409 612345678912345678 0 33 6 http://www.example.com/basketball/team/123/match/456789.html http://www.example.com/basketball/team/123/match/987654.html 0 1366 768 32 10 3183 0 0 13 0\0 1 1 0 0 2011142 -1 0 0 01321 613 660 2011-09-01 08:01:17 0 0 0 0 utf-8 1466 0 0 0 5678901234567890123 277789954 0 0 0 0 0
......@@ -14,6 +15,7 @@ In a "normal" row-oriented DBMS, data is stored in this order:
In other words, all the values related to a row are stored next to each other. Examples of a row-oriented DBMS are MySQL, Postgres, MS SQL Server, and others.
In a column-oriented DBMS, data is stored like this:
.. code-block:: text
WatchID: 5385521489354350662 5385521490329509958 5385521489953706054 5385521490476781638 5385521490583269446 5385521490218868806 5385521491437850694 5385521491090174022 5385521490792669254 5385521490420695110 5385521491532181574 5385521491559694406 5385521491459625030 5385521492275175494 5385521492781318214 5385521492710027334 5385521492955615302 5385521493708759110 5385521494506434630 5385521493104611398
......@@ -60,6 +62,7 @@ Columnar-oriented databases are better suited to OLAP scenarios (at least 100 ti
For example, the query "count the number of records for each advertising platform" requires reading one "advertising platform ID" column, which takes up 1 byte uncompressed. If most of the traffic was not from advertising platforms, you can expect at least 10-fold compression of this column. When using a quick compression algorithm, data decompression is possible at a speed of at least several gigabytes of uncompressed data per second. In other words, this query can be processed at a speed of approximately several billion rows per second on a single server. This speed is actually achieved in practice.
Example:
.. code-block:: text
milovidov@hostname:~$ clickhouse-client
......
......@@ -4,6 +4,7 @@ Queries
CREATE DATABASE
~~~~~~~~~~~~~~~
Creates the 'db_name' database.
.. code-block:: sql
CREATE DATABASE [IF NOT EXISTS] db_name
......@@ -28,11 +29,13 @@ Creates a table named 'name' in the 'db' database or the current database if 'db
A column description is ``name type`` in the simplest case. For example: ``RegionID UInt32``.
Expressions can also be defined for default values (see below).
.. code-block:: sql
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name AS [db2.]name2 [ENGINE = engine]
Creates a table with the same structure as another table. You can specify a different engine for the table. If the engine is not specified, the same engine will be used as for the 'db2.name2' table.
.. code-block:: sql
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] [db.]name ENGINE = engine AS SELECT ...
......@@ -111,15 +114,18 @@ Creates a view. There are two types of views: normal and MATERIALIZED.
Normal views don't store any data, but just perform a read from another table. In other words, a normal view is nothing more than a saved query. When reading from a view, this saved query is used as a subquery in the FROM clause.
As an example, assume you've created a view:
.. code-block:: sql
CREATE VIEW view AS SELECT ...
and written a query:
.. code-block:: sql
SELECT a, b, c FROM view
This query is fully equivalent to using the subquery:
.. code-block:: sql
SELECT a, b, c FROM (SELECT ...)
......@@ -170,6 +176,7 @@ If ``IF EXISTS`` is specified, it doesn't return an error if the table doesn't e
DETACH
~~~~~~
Deletes information about the table from the server. The server stops knowing about the table's existence.
.. code-block:: sql
DETACH TABLE [IF EXISTS] [db.]name
......@@ -203,6 +210,7 @@ Lets you change the table structure.
In the query, specify a list of one or more comma-separated actions. Each action is an operation on a column.
The following actions are supported:
.. code-block:: sql
ADD COLUMN name [type] [default_expr] [AFTER name_after]
......@@ -282,6 +290,7 @@ Another way to view a set of parts and partitions is to go into the directory wi
The directory with data is
/var/lib/clickhouse/data/database/table/,
where /var/lib/clickhouse/ is the path to ClickHouse data, 'database' is the database name, and 'table' is the table name. Example:
.. code-block:: bash
$ ls -l /var/lib/clickhouse/data/test/visits/
......@@ -306,6 +315,7 @@ Each part corresponds to a single partition and contains data for a single month
On an operating server, you can't manually change the set of parts or their data on the file system, since the server won't know about it. For non-replicated tables, you can do this when the server is stopped, but we don't recommended it. For replicated tables, the set of parts can't be changed in any case.
The 'detached' directory contains parts that are not used by the server - detached from the table using the ALTER ... DETACH query. Parts that are damaged are also moved to this directory, instead of deleting them. You can add, delete, or modify the data in the 'detached' directory at any time - the server won't know about this until you make the ALTER TABLE ... ATTACH query.
.. code-block:: sql
ALTER TABLE [db.]table DETACH PARTITION 'name'
......@@ -316,11 +326,13 @@ The partition name is specified in YYYYMM format. It can be indicated in single
After the query is executed, you can do whatever you want with the data in the 'detached' directory — delete it from the file system, or just leave it.
The query is replicated - data will be moved to the 'detached' directory and forgotten on all replicas. The query can only be sent to a leader replica. To find out if a replica is a leader, perform SELECT to the 'system.replicas' system table. Alternatively, it is easier to make a query on all replicas, and all except one will throw an exception.
.. code-block:: sql
ALTER TABLE [db.]table DROP PARTITION 'name'
Similar to the DETACH operation. Deletes data from the table. Data parts will be tagged as inactive and will be completely deleted in approximately 10 minutes. The query is replicated - data will be deleted on all replicas.
.. code-block:: sql
ALTER TABLE [db.]table ATTACH PARTITION|PART 'name'
......@@ -332,6 +344,7 @@ It is possible to add data for an entire partition or a separate part. For a par
The query is replicated. Each replica checks whether there is data in the 'detached' directory. If there is data, it checks the integrity, verifies that it matches the data on the server that initiated the query, and then adds it if everything is correct. If not, it downloads data from the query requestor replica, or from another replica where the data has already been added.
So you can put data in the 'detached' directory on one replica, and use the ALTER ... ATTACH query to add it to the table on all replicas.
.. code-block:: sql
ALTER TABLE [db.]table FREEZE PARTITION 'name'
......@@ -373,6 +386,7 @@ Replication provides protection from device failures. If all data disappeared on
For protection from device failures, you must use replication. For more information about replication, see the section "Data replication".
Backups protect against human error (accidentally deleting data, deleting the wrong data or in the wrong cluster, or corrupting data). For high-volume databases, it can be difficult to copy backups to remote servers. In such cases, to protect from human error, you can keep a backup on the same server (it will reside in /var/lib/clickhouse/shadow/).
.. code-block:: sql
ALTER TABLE [db.]table FETCH PARTITION 'name' FROM 'path-in-zookeeper'
......
......@@ -3,6 +3,7 @@ Syntax
There are two types of parsers in the system: a full SQL parser (a recursive descent parser), and a data format parser (a fast stream parser). In all cases except the INSERT query, only the full SQL parser is used.
The INSERT query uses both parsers:
.. code-block:: sql
INSERT INTO t VALUES (1, 'Hello, world'), (2, 'abc'), (3, 'def')
......@@ -83,6 +84,7 @@ Data types and table engines in the ``CREATE`` query are written the same way as
Synonyms
~~~~~~~~
In the SELECT query, expressions can specify synonyms using the AS keyword. Any expression is placed to the left of AS. The identifier name for the synonym is placed to the right of AS. As opposed to standard SQL, synonyms are not only declared on the top level of expressions:
.. code-block:: sql
SELECT (1 AS n) + 2, n
......
......@@ -2,6 +2,7 @@ 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:
.. code-block:: sql
SET profile = 'web'
......
......@@ -3,6 +3,7 @@ system.clusters
Contains information about clusters available in the config file and the servers in them.
Columns:
.. code-block:: text
cluster String - Cluster name.
......
......@@ -3,6 +3,7 @@ system.columns
Contains information about the columns in all tables.
You can use this table to get information similar to ``DESCRIBE TABLE``, but for multiple tables at once.
.. code-block:: text
database String - Name of the database the table is located in.
......
......@@ -4,6 +4,7 @@ system.dictionaries
Contains information about external dictionaries.
Columns:
.. code-block:: text
name String - Dictionary name.
......
......@@ -3,6 +3,7 @@ system.functions
Contains information about normal and aggregate functions.
Columns:
.. code-block:: text
name String - Function name.
......
......@@ -3,6 +3,7 @@ system.merges
Contains information about merges currently in process for tables in the MergeTree family.
Columns:
.. code-block:: text
database String - Name of the database the table is located in.
......
......@@ -3,6 +3,7 @@ system.parts
Contains information about parts of a table in the MergeTree family.
Columns:
.. code-block:: text
database String - Name of the database where the table that this part belongs to is located.
......
......@@ -3,6 +3,7 @@ system.processes
This system table is used for implementing the ``SHOW PROCESSLIST`` query.
Columns:
.. code-block:: text
user String - Name of the user who made the request. For distributed query processing, this is the user who helped the requestor server send the query to this server, not the user who made the distributed request on the requestor server.
......
......@@ -4,6 +4,7 @@ system.settings
Contains information about settings that are currently in use (i.e. used for executing the query you are using to read from the system.settings table).
Columns:
.. code-block:: text
name String - Setting name.
......
......@@ -9,6 +9,7 @@ To output data for all root nodes, write path = '/'.
If the path specified in 'path' doesn't exist, an exception will be thrown.
Columns:
.. code-block:: text
name String - Name of the node.
......
......@@ -2,6 +2,7 @@ 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.
.. code-block:: text
Buffer(database, table, num_layers, min_time, max_time, min_rows, max_rows, min_bytes, max_bytes)
......@@ -21,6 +22,7 @@ During the write operation, data is inserted to a 'num_layers' number of random
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.
Example:
.. code-block:: sql
CREATE TABLE merge.hits_buffer AS merge.hits ENGINE = Buffer(merge, hits, 16, 10, 100, 10000, 1000000, 10000000, 100000000)
......
......@@ -5,6 +5,7 @@ Distributed
Reading is automatically parallelized. During a read, the table indexes on remote servers are used, if there are any.
The Distributed engine accepts parameters: the cluster name in the server's config file, the name of a remote database, the name of a remote table, and (optionally) a sharding key.
Example:
.. code-block:: text
Distributed(logs, default, hits[, sharding_key])
......
......@@ -2,6 +2,7 @@ Join
----
A prepared data structure for JOIN that is always located in RAM.
.. code-block:: text
Join(ANY|ALL, LEFT|INNER, k1[, k2, ...])
......
......@@ -4,6 +4,7 @@ Merge
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:
.. code-block:: text
Merge(hits, '^WatchLog')
......
......@@ -8,11 +8,13 @@ The engine accepts parameters: the name of a Date type column containing the dat
Example:
Example without sampling support:
.. code-block:: text
MergeTree(EventDate, (CounterID, EventDate), 8192)
Example with sampling support:
.. code-block:: text
MergeTree(EventDate, intHash32(UserID), (CounterID, EventDate, intHash32(UserID)), 8192)
......
......@@ -73,6 +73,7 @@ The ``'Replicated'`` prefix is added to the table engine name. For example, ``Re
Two parameters are also added in the beginning of the parameters list - the path to the table in ZooKeeper, and the replica name in ZooKeeper.
Example:
.. code-block:: text
ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/hits', '{replica}', EventDate, intHash32(UserID), (CounterID, EventDate, intHash32(UserID), EventTime), 8192)
......
......@@ -28,6 +28,7 @@ If the name of a nested table ends in 'Map' and it contains at least two columns
Then this nested table is interpreted as a mapping of key => (values...), and when merging its rows, the elements of two data sets are merged by 'key' with a summation of the corresponding (values...).
Examples:
.. code-block:: text
[(1, 100)] + [(2, 150)] -> [(1, 100), (2, 150)]
......
......@@ -16,6 +16,7 @@ This may be just one server address. The server address is host:port, or just th
Note: As an exception, when specifying an IPv6 address, the port is required.
Examples:
.. code-block:: text
example01-01-1
......@@ -28,17 +29,20 @@ Examples:
Multiple addresses can be comma-separated. In this case, the query goes to all the specified addresses (like to shards with different data) and uses distributed processing.
Example:
.. code-block:: text
example01-01-1,example01-02-1
Part of the expression can be specified in curly brackets. The previous example can be written as follows:
.. code-block:: text
example01-0{1,2}-1
Curly brackets can contain a range of numbers separated by two dots (non-negative integers). In this case, the range is expanded to a set of values that generate shard addresses. If the first number starts with zero, the values are formed with the same zero alignment.
The previous example can be written as follows:
.. code-block:: text
example01-{01..02}-1
......@@ -48,6 +52,7 @@ If you have multiple pairs of curly brackets, it generates the direct product of
Addresses and fragments in curly brackets can be separated by the pipe (|) symbol. In this case, the corresponding sets of addresses are interpreted as replicas, and the query will be sent to the first healthy replica. The replicas are evaluated in the order currently set in the 'load_balancing' setting.
Example:
.. code-block:: text
example01-{01..02}-{1|2}
......
......@@ -236,6 +236,7 @@ sequenceMatch(pattern)(time, cond1, cond2, ...)
- была ли цепочка событий, в которой посещение страницы с адресом, содержащим company было раньше по времени посещения страницы с адресом, содержащим cart.
Это вырожденный пример. Его можно записать с помощью других агрегатных функций:
.. code-block:: text
minIf(EventTime, URL LIKE '%company%') < maxIf(EventTime, URL LIKE '%cart%').
......@@ -278,6 +279,7 @@ uniqUpTo(N)(x)
Работает максимально быстро за исключением патологических случаев, когда используется большое значение N и количество уникальных значений чуть меньше N.
Пример применения:
.. code-block:: text
Задача: показывать в отчёте только поисковые фразы, по которым было хотя бы 5 уникальных посетителей.
......
......@@ -4,6 +4,7 @@ Enum
Enum8 или Enum16. Представляет собой конечное множество строковых значений, сохраняемых более эффективно, чем это делает тип данных ``String``.
Пример:
.. code-block:: text
Enum8('hello' = 1, 'world' = 2)
......
......@@ -189,6 +189,7 @@ range_hashed
Пример: таблица содержит скидки для каждого рекламодателя в виде:
.. code-block:: text
+------------------+-----------------------------+------------+----------+
......
......@@ -10,6 +10,7 @@ ClickHouse позволяет отправить на сервер данные,
Внешние данные могут быть загружены как с помощью клиента командной строки (в неинтерактивном режиме), так и через HTTP-интерфейс.
В клиенте командной строки, может быть указана секция параметров вида
.. code-block:: bash
--external --file=... [--name=...] [--format=...] [--types=...|--structure=...]
......@@ -31,6 +32,7 @@ ClickHouse позволяет отправить на сервер данные,
Файлы, указанные в file, будут разобраны форматом, указанным в format, с использованием типов данных, указанных в types или structure. Таблица будет загружена на сервер, и доступна там в качестве временной таблицы с именем name.
Примеры:
.. code-block:: bash
echo -ne "1\n2\n3\n" | clickhouse-client --query="SELECT count() FROM test.visits WHERE TraficSourceID IN _data" --external --file=- --types=Int8
......@@ -45,6 +47,7 @@ ClickHouse позволяет отправить на сервер данные,
При использовании HTTP интерфейса, внешние данные передаются в формате multipart/form-data. Каждая таблица передаётся отдельным файлом. Имя таблицы берётся из имени файла. В query_string передаются параметры name_format, name_types, name_structure, где name - имя таблицы, которой соответствуют эти параметры. Смысл параметров такой же, как при использовании клиента командной строки.
Пример:
.. code-block:: bash
cat /etc/passwd | sed 's/:/\t/g' > passwd.tsv
......
......@@ -4,6 +4,7 @@ JSONCompact
Отличается от JSON только тем, что строчки данных выводятся в массивах, а не в object-ах.
Пример:
.. code-block:: json
{
......
......@@ -17,6 +17,7 @@ TabSeparated
В качестве исключения, поддерживается также парсинг даты-с-временем в формате unix timestamp, если он состоит ровно из 10 десятичных цифр. Результат не зависит от часового пояса. Различение форматов YYYY-MM-DD hh:mm:ss и NNNNNNNNNN делается автоматически.
Строки выводятся с экранированием спец-символов с помощью обратного слеша. При выводе, используются следующие escape-последовательности: ``\b``, ``\f``, ``\r``, ``\n``, ``\t``, ``\0``, ``\'``, ``\\``. При парсинге, также поддерживаются последовательности ``\a``, ``\v``, а также ``\xHH`` (hex escape-последовательности) и любые последовательности вида ``\c``, где ``c`` - любой символ - такие последовательности преобразуется в ``c``. Таким образом, при чтении поддерживаются форматы, где перевод строки может быть записан как ``\n`` и как ``\`` и перевод строки. Например, строка ``Hello world``, где между словами вместо пробела стоит перевод строки, может быть считана в любом из следующих вариантов:
.. code-block:: text
Hello\nworld
......
......@@ -2,6 +2,7 @@ TSKV
----
Похож на TabSeparated, но выводит значения в формате name=value. Имена экранируются так же, как строки в формате TabSeparated и, дополнительно, экранируется также символ =.
.. code-block:: text
SearchPhrase= count()=8267016
......
......@@ -33,6 +33,7 @@ visitParamExtractRaw(params, name)
Вернуть значение поля, включая разделители.
Примеры:
.. code-block:: text
visitParamExtractRaw('{"abc":"\\n\\u0000"}', 'abc') = '"\\n\\u0000"'
......@@ -43,6 +44,7 @@ visitParamExtractString(params, name)
Распарсить строку в двойных кавычках. У значения убирается экранирование. Если убрать экранированные символы не удалось, то возвращается пустая строка.
Примеры:
.. code-block:: text
visitParamExtractString('{"abc":"\\n\\u0000"}', 'abc') = '\n\0'
......
......@@ -27,6 +27,7 @@ toString
При преобразовании даты-с-временем в число или наоборот, дате-с-временем соответствует число секунд от начала unix эпохи.
Форматы даты и даты-с-временем для функций toDate/toDateTime определены следующим образом:
.. code-block:: text
YYYY-MM-DD
......
......@@ -73,6 +73,7 @@ URLPathHierarchy(URL)
"""""""""""""""""""""
То же самое, но без протокола и хоста в результате. Элемент / (корень) не включается. Пример:
Функция используется для реализации древовидных отчётов по URL в Яндекс.Метрике.
.. code-block:: text
URLPathHierarchy('https://example.com/browse/CONV-6788') =
......
......@@ -20,6 +20,7 @@ ClickHouse поддерживает работу одновременно с н
Во все функции по работе с регионами, в конце добавлен один необязательный аргумент - ключ словаря. Далее он обозначен как geobase.
Пример:
.. code-block:: text
regionToCountry(RegionID) - использует словарь по умолчанию: /opt/geo/regions_hierarchy.txt;
......
......@@ -23,6 +23,7 @@
~~~~~~~~~~~~~~~~~~~~
Пропишите в `/etc/apt/sources.list` (или в отдельный файл `/etc/apt/sources.list.d/clickhouse.list`) репозитории:
.. code-block:: text
deb http://repo.yandex.ru/clickhouse/trusty stable main
......@@ -30,6 +31,7 @@
На других версиях Ubuntu, замените `trusty` на `xenial` или `precise`.
Затем выполните:
.. code-block:: bash
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv E0C56BD4 # optional
......@@ -51,12 +53,14 @@ ClickHouse содержит настройки ограничения досту
Вы можете собрать пакеты и установить их.
Также вы можете использовать программы без установки пакетов.
.. code-block:: text
Клиент: dbms/src/Client/
Сервер: dbms/src/Server/
Для сервера создаёте директории с данными, например:
.. code-block:: text
/opt/clickhouse/data/default/
......
......@@ -161,11 +161,13 @@ wget сам всё эскейпит, но его не рекомендуется
Имя пользователя и пароль могут быть указаны в одном из двух вариантов:
1. С использованием HTTP Basic Authentification. Пример:
.. code-block:: bash
echo 'SELECT 1' | curl 'http://user:password@localhost:8123/' -d @-
2. В параметрах URL user и password. Пример:
.. code-block:: bash
echo 'SELECT 1' | curl 'http://localhost:8123/?user=user&password=password' -d @-
......
......@@ -88,6 +88,7 @@
Синонимы
~~~~~~~~
В запросе SELECT, в выражениях могут быть указаны синонимы с помощью ключевого слова AS. Слева от AS стоит любое выражение. Справа от AS стоит идентификатор - имя для синонима. В отличие от стандартного SQL, синонимы могут объявляться не только на верхнем уровне выражений:
.. code-block:: sql
SELECT (1 AS n) + 2, n
......
......@@ -2,6 +2,7 @@
================
Профили настроек - это множество настроек, сгруппированных под одним именем. Для каждого пользователя ClickHouse указывается некоторый профиль.
Все настройки профиля можно применить, установив настройку с именем profile. Пример:
.. code-block:: sql
SET profile = 'web'
......
......@@ -3,6 +3,7 @@ system.columns
Содержит информацию о столбцах всех таблиц.
С помощью этой таблицы можно получить информацию аналогично запросу ``DESCRIBE TABLE``, но для многих таблиц сразу.
.. code-block:: text
database String - имя базы данных, в которой находится таблица
......
......@@ -4,6 +4,7 @@ system.dictionaries
Содержит информацию о внешних словарях.
Столбцы:
.. code-block:: text
name String - имя словаря
......
......@@ -4,6 +4,7 @@ system.functions
Содержит информацию об обычных и агрегатных функциях.
Столбцы:
.. code-block:: text
name String - имя функции
......
......@@ -3,6 +3,7 @@ system.merges
Содержит информацию о производящихся прямо сейчас слияниях для таблиц семейства MergeTree.
Столбцы:
.. code-block:: text
database String - имя базы данных, в которой находится таблица
......
......@@ -3,6 +3,7 @@ system.parts
Содержит информацию о кусках таблиц семейства MergeTree.
Столбцы:
.. code-block:: text
database String - имя базы данных, в которой находится таблица, к которой относится кусок
......
......@@ -3,6 +3,7 @@ system.processes
Эта системная таблица используется для реализации запроса ``SHOW PROCESSLIST``.
Столбцы:
.. code-block:: text
user String - имя пользователя, который задал запрос. При распределённой обработке запроса, относится к пользователю, с помощью которого сервер-инициатор запроса отправил запрос на данный сервер, а не к имени пользователя, который задал распределённый запрос на сервер-инициатор запроса.
......
......@@ -5,6 +5,7 @@ system.settings
То есть, используемых для выполнения запроса, с помощью которого вы читаете из таблицы system.settings.
Столбцы:
.. code-block:: text
name String - имя настройки
......
......@@ -9,6 +9,7 @@ system.zookeeper
Если узла, указанного в path не существует, то будет брошено исключение.
Столбцы:
.. code-block:: text
name String - имя узла
......
......@@ -2,6 +2,7 @@ Buffer
------
Буферизует записываемые данные в оперативке, периодически сбрасывая их в другую таблицу. При чтении, производится чтение данных одновременно из буфера и из другой таблицы.
.. code-block:: text
Buffer(database, table, num_layers, min_time, max_time, min_rows, max_rows, min_bytes, max_bytes)
......@@ -21,6 +22,7 @@ min_bytes, max_bytes - условие на количество байт в бу
Условия для сброса данных учитываются отдельно для каждого из num_layers буферов. Например, если num_layers = 16 и max_bytes = 100000000, то максимальный расход оперативки будет 1.6 GB.
Пример:
.. code-block:: sql
CREATE TABLE merge.hits_buffer AS merge.hits ENGINE = Buffer(merge, hits, 16, 10, 100, 10000, 1000000, 10000000, 100000000)
......
......@@ -5,6 +5,7 @@ Distributed
Чтение автоматически распараллеливается. При чтении будут использованы индексы таблиц на удалённых серверах, если есть.
Движок Distributed принимает параметры: имя кластера в конфигурационном файле сервера, имя удалённой базы данных, имя удалённой таблицы, а также (не обязательно) ключ шардирования.
Пример:
.. code-block:: text
Distributed(logs, default, hits[, sharding_key])
......
......@@ -26,6 +26,7 @@ Graphite хранит в ClickHouse полные данные, а получат
* ``Version`` - настройка, которая определяет какое значение метрики с одинаковыми Path и Time останется в базе.
Шаблон правил rollup:
.. code-block:: text
pattern
......@@ -43,6 +44,7 @@ Graphite хранит в ClickHouse полные данные, а получат
При обработке записи ClickHouse проверит правила в секции ```pattern```. Если имя метрики соответствует шаблону ```regexp```, то применяются правила из ```pattern```, в противном случае из ```default```.
Поля шаблона правил.
.. code-block:: text
+---------------+----------------------------------------------------------------------------------------------------------------------------+
......
......@@ -2,6 +2,7 @@ Join
----
Представляет собой подготовленную структуру данных для JOIN-а, постоянно находящуюся в оперативке.
.. code-block:: text
Join(ANY|ALL, LEFT|INNER, k1[, k2, ...])
......
......@@ -4,6 +4,7 @@ Merge
Движок Merge (не путайте с движком ``MergeTree``) не хранит данные самостоятельно, а позволяет читать одновременно из произвольного количества других таблиц.
Чтение автоматически распараллеливается. Запись в таблицу не поддерживается. При чтении будут использованы индексы тех таблиц, из которых реально идёт чтение, если они существуют.
Движок Merge принимает параметры: имя базы данных и регулярное выражение для таблиц. Пример:
.. code-block:: text
Merge(hits, '^WatchLog')
......
......@@ -9,11 +9,13 @@ MergeTree
Движок принимает параметры: имя столбца типа Date, содержащего дату; выражение для семплирования (не обязательно); кортеж, определяющий первичный ключ таблицы; гранулированность индекса. Пример:
Пример без поддержки сэмплирования:
.. code-block:: text
MergeTree(EventDate, (CounterID, EventDate), 8192)
Пример с поддержкой сэмплирования:
.. code-block:: text
MergeTree(EventDate, intHash32(UserID), (CounterID, EventDate, intHash32(UserID)), 8192)
......
......@@ -75,6 +75,7 @@ ReplicatedSummingMergeTree
Также добавляются два параметра в начало списка параметров - путь к таблице в ZooKeeper, имя реплики в ZooKeeper.
Пример:
.. code-block:: text
ReplicatedMergeTree('/clickhouse/tables/{layer}-{shard}/hits', '{replica}', EventDate, intHash32(UserID), (CounterID, EventDate, intHash32(UserID), EventTime), 8192)
......
......@@ -28,6 +28,7 @@ SummingMergeTree
* остальные столбцы - арифметические ((U)IntN, Float32/64), условно (values...), то такая вложенная таблица воспринимается как отображение key => (values...) и при слиянии ее строк выполняется слияние элементов двух множеств по key со сложением соответствующих (values...).
Примеры:
.. code-block:: text
[(1, 100)] + [(2, 150)] -> [(1, 100), (2, 150)]
......
......@@ -6,6 +6,7 @@ remote
Позволяет обратиться к удалённым серверам без создания таблицы типа ``Distributed``.
Сигнатуры:
.. code-block:: sql
remote('addresses_expr', db, table[, 'user'[, 'password']])
......@@ -30,16 +31,19 @@ remote
Адреса можно указать через запятую, в этом случае ClickHouse обработает запрос как распределённый, т.е. отправит его по всем указанным адресам как на шарды с разными данными.
Пример:
.. code-block:: text
example01-01-1,example01-02-1
Часть выражения может быть указана в фигурных скобках. Предыдущий пример может быть записан следующим образом:
.. code-block:: text
example01-0{1,2}-1
В фигурных скобках может быть указан диапазон (неотрицательных целых) чисел через две точки. В этом случае, диапазон раскрывается в множество значений, генерирующих адреса шардов. Если запись первого числа начинается с нуля, то значения формируются с таким же выравниванием нулями. Предыдущий пример может быть записан следующим образом:
.. code-block:: text
example01-{01..02}-1
......@@ -49,6 +53,7 @@ remote
Адреса или их фрагменты в фигурных скобках можно указать через символ \|. В этом случае, соответствующие множества адресов понимаются как реплики - запрос будет отправлен на первую живую реплику. При этом, реплики перебираются в порядке, согласно текущей настройке :ref:`load_balancing <settings-load_balancing>`.
Пример:
.. code-block:: text
example01-{01..02}-{1|2}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册