Remove anchors to top of pages

This commit is contained in:
Ivan Blinkov 2018-12-12 16:30:55 +03:00
parent a433f1fd25
commit 5d5bde7174
150 changed files with 517 additions and 544 deletions

View File

@ -50,7 +50,7 @@ SELECT
## Working with data types
When creating an array on the fly, ClickHouse automatically defines the argument type as the narrowest data type that can store all the listed arguments. If there are any [NULL](../query_language/syntax.md#null-literal) or [Nullable](nullable.md#data_type-nullable) type arguments, the type of array elements is [Nullable](nullable.md#data_type-nullable).
When creating an array on the fly, ClickHouse automatically defines the argument type as the narrowest data type that can store all the listed arguments. If there are any [NULL](../query_language/syntax.md#null-literal) or [Nullable](nullable.md#data_type-nullable) type arguments, the type of array elements is [Nullable](nullable.md).
If ClickHouse couldn't determine the data type, it will generate an exception. For instance, this will happen when trying to create an array with strings and numbers simultaneously (`SELECT array(1, 'a')`).

View File

@ -77,9 +77,9 @@ SELECT toTypeName(CAST('a', 'Enum8(\'a\' = 1, \'b\' = 2)'))
Each of the values is assigned a number in the range `-128 ... 127` for `Enum8` or in the range `-32768 ... 32767` for `Enum16`. All the strings and numbers must be different. An empty string is allowed. If this type is specified (in a table definition), numbers can be in an arbitrary order. However, the order does not matter.
Neither the string nor the numeric value in an `Enum` can be [NULL](../query_language/syntax.md#null-literal).
Neither the string nor the numeric value in an `Enum` can be [NULL](../query_language/syntax.md).
An `Enum` can be contained in [Nullable](nullable.md#data_type-nullable) type. So if you create a table using the query
An `Enum` can be contained in [Nullable](nullable.md) type. So if you create a table using the query
```
CREATE TABLE t_enum_nullable

View File

@ -67,7 +67,7 @@ SELECT 0 / 0
└──────────────┘
```
See the rules for `NaN` sorting in the section [ORDER BY clause](../query_language/select.md#query_language-queries-order_by).
See the rules for `NaN` sorting in the section [ORDER BY clause](../query_language/select.md).
[Original article](https://clickhouse.yandex/docs/en/data_types/float/) <!--hide-->

View File

@ -25,7 +25,7 @@ CREATE TABLE t
) ENGINE = ...
```
[uniq](../../query_language/agg_functions/reference.md#agg_function-uniq), anyIf ([any](../../query_language/agg_functions/reference.md#agg_function-any)+[If](../../query_language/agg_functions/combinators.md#agg-functions-combine-if)) and [quantiles](../../query_language/agg_functions/reference.md#agg_function-quantiles) are the aggregate functions supported in ClickHouse.
[uniq](../../query_language/agg_functions/reference.md#agg_function-uniq), anyIf ([any](../../query_language/agg_functions/reference.md#agg_function-any)+[If](../../query_language/agg_functions/combinators.md#agg-functions-combine-if)) and [quantiles](../../query_language/agg_functions/reference.md) are the aggregate functions supported in ClickHouse.
## Usage
@ -60,7 +60,7 @@ SELECT uniqMerge(state) FROM (SELECT uniqState(UserID) AS state FROM table GROUP
## Usage Example
See [AggregatingMergeTree](../../operations/table_engines/aggregatingmergetree.md#table_engine-aggregatingmergetree) engine description.
See [AggregatingMergeTree](../../operations/table_engines/aggregatingmergetree.md) engine description.
[Original article](https://clickhouse.yandex/docs/en/data_types/nested_data_structures/aggregatefunction/) <!--hide-->

View File

@ -2,9 +2,9 @@
# Nullable(TypeName)
Allows to store special marker ([NULL](../query_language/syntax.md#null-literal)) that denotes "missing value" alongside normal values allowed by `TypeName`. For example, a `Nullable(Int8)` type column can store `Int8` type values, and the rows that don't have a value will store `NULL`.
Allows to store special marker ([NULL](../query_language/syntax.md)) that denotes "missing value" alongside normal values allowed by `TypeName`. For example, a `Nullable(Int8)` type column can store `Int8` type values, and the rows that don't have a value will store `NULL`.
For a `TypeName`, you can't use composite data types [Array](array.md#data_type is array) and [Tuple](tuple.md#data_type-tuple). Composite data types can contain `Nullable` type values, such as `Array(Nullable(Int8))`.
For a `TypeName`, you can't use composite data types [Array](array.md#data_type is array) and [Tuple](tuple.md). Composite data types can contain `Nullable` type values, such as `Array(Nullable(Int8))`.
A `Nullable` type field can't be included in table indexes.

View File

@ -4,7 +4,7 @@
The only purpose of this data type is to represent cases where value is not expected. So you can't create a `Nothing` type value.
For example, literal [NULL](../../query_language/syntax.md#null-literal) has type of `Nullable(Nothing)`. See more about [Nullable](../../data_types/nullable.md#data_type-nullable).
For example, literal [NULL](../../query_language/syntax.md#null-literal) has type of `Nullable(Nothing)`. See more about [Nullable](../../data_types/nullable.md).
The `Nothing` type can also used to denote empty arrays:

View File

@ -4,7 +4,7 @@
A tuple of elements, each having an individual [type](index.md#data_types).
You can't store tuples in tables (other than Memory tables). They are used for temporary column grouping. Columns can be grouped when an IN expression is used in a query, and for specifying certain formal parameters of lambda functions. For more information, see the sections [IN operators](../query_language/select.md#query_language-in_operators) and [Higher order functions](../query_language/functions/higher_order_functions.md#higher_order_functions).
You can't store tuples in tables (other than Memory tables). They are used for temporary column grouping. Columns can be grouped when an IN expression is used in a query, and for specifying certain formal parameters of lambda functions. For more information, see the sections [IN operators](../query_language/select.md) and [Higher order functions](../query_language/functions/higher_order_functions.md#higher_order_functions).
Tuples can be the result of a query. In this case, for text formats other than JSON, values are comma-separated in brackets. In JSON formats, tuples are output as arrays (in square brackets).
@ -34,7 +34,7 @@ SELECT
## Working with data types
When creating a tuple on the fly, ClickHouse automatically detects the type of each argument as the minimum of the types which can store the argument value. If the argument is [NULL](../query_language/syntax.md#null-literal), the type of the tuple element is [Nullable](nullable.md#data_type-nullable).
When creating a tuple on the fly, ClickHouse automatically detects the type of each argument as the minimum of the types which can store the argument value. If the argument is [NULL](../query_language/syntax.md#null-literal), the type of the tuple element is [Nullable](nullable.md).
Example of automatic data type detection:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -95,7 +95,7 @@ Only a small set of symbols are escaped. You can easily stumble onto a string va
Arrays are written as a list of comma-separated values in square brackets. Number items in the array are fomratted as normally, but dates, dates with times, and strings are written in single quotes with the same escaping rules as above.
[NULL](../query_language/syntax.md#null-literal) is formatted as `\N`.
[NULL](../query_language/syntax.md) is formatted as `\N`.
<a name="tabseparatedraw"></a>
@ -141,7 +141,7 @@ SearchPhrase=curtain designs count()=1064
SearchPhrase=baku count()=1000
```
[NULL](../query_language/syntax.md#null-literal) is formatted as `\N`.
[NULL](../query_language/syntax.md) is formatted as `\N`.
``` sql
SELECT * FROM t_null FORMAT TSKV
@ -267,7 +267,7 @@ If the query contains GROUP BY, rows_before_limit_at_least is the exact number o
This format is only appropriate for outputting a query result, but not for parsing (retrieving data to insert in a table).
ClickHouse supports [NULL](../query_language/syntax.md#null-literal), which is displayed as `null` in the JSON output.
ClickHouse supports [NULL](../query_language/syntax.md), which is displayed as `null` in the JSON output.
See also the JSONEachRow format.
@ -361,7 +361,7 @@ Outputs data as Unicode-art tables, also using ANSI-escape sequences for setting
A full grid of the table is drawn, and each row occupies two lines in the terminal.
Each result block is output as a separate table. This is necessary so that blocks can be output without buffering results (buffering would be necessary in order to pre-calculate the visible width of all the values).
[NULL](../query_language/syntax.md#null-literal) is output as `ᴺᵁᴸᴸ`.
[NULL](../query_language/syntax.md) is output as `ᴺᵁᴸᴸ`.
``` sql
SELECT * FROM t_null
@ -457,11 +457,11 @@ FixedString is represented simply as a sequence of bytes.
Array is represented as a varint length (unsigned [LEB128](https://en.wikipedia.org/wiki/LEB128)), followed by successive elements of the array.
For [NULL](../query_language/syntax.md#null-literal) support, an additional byte containing 1 or 0 is added before each [Nullable](../data_types/nullable.md#data_type-nullable) value. If 1, then the value is `NULL` and this byte is interpreted as a separate value. If 0, the value after the byte is not `NULL`.
For [NULL](../query_language/syntax.md#null-literal) support, an additional byte containing 1 or 0 is added before each [Nullable](../data_types/nullable.md) value. If 1, then the value is `NULL` and this byte is interpreted as a separate value. If 0, the value after the byte is not `NULL`.
## Values
Prints every row in brackets. Rows are separated by commas. There is no comma after the last row. The values inside the brackets are also comma-separated. Numbers are output in decimal format without quotes. Arrays are output in square brackets. Strings, dates, and dates with times are output in quotes. Escaping rules and parsing are similar to the [TabSeparated](#tabseparated) format. During formatting, extra spaces aren't inserted, but during parsing, they are allowed and skipped (except for spaces inside array values, which are not allowed). [NULL](../query_language/syntax.md#null-literal) is represented as `NULL`.
Prints every row in brackets. Rows are separated by commas. There is no comma after the last row. The values inside the brackets are also comma-separated. Numbers are output in decimal format without quotes. Arrays are output in square brackets. Strings, dates, and dates with times are output in quotes. Escaping rules and parsing are similar to the [TabSeparated](#tabseparated) format. During formatting, extra spaces aren't inserted, but during parsing, they are allowed and skipped (except for spaces inside array values, which are not allowed). [NULL](../query_language/syntax.md) is represented as `NULL`.
The minimum set of characters that you need to escape when passing data in Values format: single quotes and backslashes.
@ -473,7 +473,7 @@ This is the format that is used in `INSERT INTO t VALUES ...`, but you can also
Prints each value on a separate line with the column name specified. This format is convenient for printing just one or a few rows, if each row consists of a large number of columns.
[NULL](../query_language/syntax.md#null-literal) is output as `ᴺᵁᴸᴸ`.
[NULL](../query_language/syntax.md) is output as `ᴺᵁᴸᴸ`.
Example:
@ -618,7 +618,7 @@ struct Message {
}
```
Schema files are in the file that is located in the directory specified in [ format_schema_path](../operations/server_settings/settings.md#server_settings-format_schema_path) in the server configuration.
Schema files are in the file that is located in the directory specified in [ format_schema_path](../operations/server_settings/settings.md) in the server configuration.
Deserialization is effective and usually doesn't increase the system load.

View File

@ -59,6 +59,6 @@ ClickHouse provides various ways to trade accuracy for performance:
Uses asynchronous multimaster replication. After being written to any available replica, data is distributed to all the remaining replicas in the background. The system maintains identical data on different replicas. Recovery after most failures is performed automatically, and in complex cases — semi-automatically.
For more information, see the section [Data replication](../operations/table_engines/replication.md#table_engines-replication).
For more information, see the section [Data replication](../operations/table_engines/replication.md).
[Original article](https://clickhouse.yandex/docs/en/introduction/distinctive_features/) <!--hide-->

View File

@ -2,7 +2,7 @@
According to internal testing results at Yandex, ClickHouse shows the best performance (both the highest throughput for long queries and the lowest latency on short queries) for comparable operating scenarios among systems of its class that were available for testing. You can view the test results on a [separate page](https://clickhouse.yandex/benchmark.html).
This has also been confirmed by numerous independent benchmarks. They are not difficult to find using an internet search, or you can see [our small collection of related links](https://clickhouse.yandex/#independent-bookmarks).
This has also been confirmed by numerous independent benchmarks. They are not difficult to find using an internet search, or you can see [our small collection of related links](https://clickhouse.yandex/).
## Throughput for a Single Large Query

View File

@ -61,7 +61,7 @@ Users are recorded in the `users` section. Here is a fragment of the `users.xml`
You can see a declaration from two users: `default`and`web`. We added the `web` user separately.
The `default` user is chosen in cases when the username is not passed. The `default` user is also used for distributed query processing, if the configuration of the server or cluster doesn't specify the `user` and `password` (see the section on the [Distributed](../operations/table_engines/distributed.md#table_engines-distributed) engine).
The `default` user is chosen in cases when the username is not passed. The `default` user is also used for distributed query processing, if the configuration of the server or cluster doesn't specify the `user` and `password` (see the section on the [Distributed](../operations/table_engines/distributed.md) engine).
The user that is used for exchanging information between servers combined in a cluster must not have substantial restrictions or quotas otherwise, distributed queries will fail.
@ -87,8 +87,7 @@ The config includes comments explaining how to open access from everywhere.
For use in production, only specify `ip` elements (IP addresses and their masks), since using `host` and `hoost_regexp` might cause extra latency.
Next the user settings profile is specified (see the section "[Settings profiles](settings/settings_profiles.md#settings_profiles)"). You can specify the default profile, `default'`. The profile can have any name. You can specify the same profile for different users. The most important thing you can write in the settings profile is `readonly=1`, which ensures read-only access.
Next the user settings profile is specified (see the section "[Settings profiles](settings/settings_profiles.md
Then specify the quota to be used (see the section "[Quotas](quotas.md#quotas)"). You can specify the default quota: `default`. It is set in the config by default to only count resource usage, without restricting it. The quota can have any name. You can specify the same quota for different users in this case, resource usage is calculated for each user individually.
In the optional `<allow_databases>` section, you can also specify a list of databases that the user can access. By default, all databases are available to the user. You can specify the `default` database. In this case, the user will receive access to the database by default.

View File

@ -1,6 +1,6 @@
# Data Backup
While [replication](table_engines/replication.md#table_engines-replication) provides protection from hardware failures, it does not protect against human errors: accidentally deleting data, deleting the wrong table or on the wrong cluster, software bugs leading to incorrect data processing or data corruption. In many cases commands like these will affect all replicas. ClickHouse has built-in safeguards to prevent some of mistakes, for example by default [you can't just drop tables with MergeTree-like engine containing more than 50Gb of data](https://github.com/yandex/ClickHouse/blob/v18.14.18-stable/dbms/programs/server/config.xml#L322-L330), but they don't cover all possible cases and can be circumvented.
While [replication](table_engines/replication.md#table_engines-replication) provides protection from hardware failures, it does not protect against human errors: accidentally deleting data, deleting the wrong table or on the wrong cluster, software bugs leading to incorrect data processing or data corruption. In many cases commands like these will affect all replicas. ClickHouse has built-in safeguards to prevent some of mistakes, for example by default [you can't just drop tables with MergeTree-like engine containing more than 50Gb of data](https://github.com/yandex/ClickHouse/blob/v18.14.18-stable/dbms/programs/server/config.xml), but they don't cover all possible cases and can be circumvented.
So in order to effectively mitigate possible human errors, you should carefully prepare your backup and restore strategy **in advance**.
@ -27,7 +27,7 @@ For smaller volumes of data simple `INSERT INTO ... SELECT ...` to remote tables
ClickHouse allows to create a local copy of table partitions using `ALTER TABLE ... FREZE PARTITION ...` query. It's implemented using hardlinks to `/var/lib/clickhouse/shadow/` folder, so for old data it usually does not consume extra disk space. As created file copies are no longer touched by ClickHouse server, you can just leave them there: it's still be a simple backup that doesn't require any additional external system, but will be prone to hardware issues since. It's better to remotely copy them somewhere and then probably remove the local copies. Distributed filesystems and object stores are still a good options for this, but normal file servers attached with large enough capacity might work as well (in this case the transfer will happen via network filesystem or maybe [rsync](https://en.wikipedia.org/wiki/Rsync)).
More details on queries related to partition manipulations can be found in [respective section of ALTER documentation](../query_language/alter.md#query_language-manipulation-with-partitions-and-parts).
More details on queries related to partition manipulations can be found in [respective section of ALTER documentation](../query_language/alter.md).
There's a third-party tool to automate this approach: [clickhouse-backup](https://github.com/AlexAkulov/clickhouse-backup).

View File

@ -14,7 +14,7 @@ If `replace` is specified, it replaces the entire element with the specified one
If `remove` is specified, it deletes the element.
The config can also define "substitutions". If an element has the `incl` attribute, the corresponding substitution from the file will be used as the value. By default, the path to the file with substitutions is `/etc/metrika.xml`. This can be changed in the [include_from](server_settings/settings.md#server_settings-include_from) element in the server config. The substitution values are specified in `/yandex/substitution_name` elements in this file. If a substitution specified in `incl` does not exist, it is recorded in the log. To prevent ClickHouse from logging missing substitutions, specify the `optional="true"` attribute (for example, settings for [macros](server_settings/settings.md#server_settings-macros)).
The config can also define "substitutions". If an element has the `incl` attribute, the corresponding substitution from the file will be used as the value. By default, the path to the file with substitutions is `/etc/metrika.xml`. This can be changed in the [include_from](server_settings/settings.md#server_settings-include_from) element in the server config. The substitution values are specified in `/yandex/substitution_name` elements in this file. If a substitution specified in `incl` does not exist, it is recorded in the log. To prevent ClickHouse from logging missing substitutions, specify the `optional="true"` attribute (for example, settings for [macros](server_settings/settings.md)).
Substitutions can also be performed from ZooKeeper. To do this, specify the attribute `from_zk = "/path/to/node"`. The element value is replaced with the contents of the node at `/path/to/node` in ZooKeeper. You can also put an entire XML subtree on the ZooKeeper node and it will be fully inserted into the source element.

View File

@ -78,7 +78,7 @@ To get a list of databases, use the [ SHOW DATABASES](../../query_language/misc.
Default settings profile.
Settings profiles are located in the file specified in the parameter [user_config](#server_settings-users_config).
Settings profiles are located in the file specified in the parameter [user_config]().
**Example**
@ -97,7 +97,7 @@ Path:
- Specify the absolute path or the path relative to the server config file.
- The path can contain wildcards \* and ?.
See also "[External dictionaries](../../query_language/dicts/external_dicts.md#dicts-external_dicts)".
See also "[External dictionaries](../../query_language/dicts/external_dicts.md)".
**Example**
@ -176,7 +176,7 @@ You can configure multiple `<graphite>` clauses. For instance, you can use this
Settings for thinning data for Graphite.
For more details, see [GraphiteMergeTree](../../operations/table_engines/graphitemergetree.md#table_engines-graphitemergetree).
For more details, see [GraphiteMergeTree](../../operations/table_engines/graphitemergetree.md).
**Example**
@ -206,7 +206,7 @@ For more details, see [GraphiteMergeTree](../../operations/table_engines/graphit
The port for connecting to the server over HTTP(s).
If `https_port` is specified, [openSSL](#server_settings-openSSL) must be configured.
If `https_port` is specified, [openSSL]() must be configured.
If `http_port` is specified, the openSSL configuration is ignored even if it is set.
@ -357,7 +357,7 @@ Parameter substitutions for replicated tables.
Can be omitted if replicated tables are not used.
For more information, see the section "[Creating replicated tables](../../operations/table_engines/replication.md#table_engines-replication-creation_of_rep_tables)".
For more information, see the section "[Creating replicated tables](../../operations/table_engines/replication.md)".
**Example**
@ -369,7 +369,7 @@ For more information, see the section "[Creating replicated tables](../../operat
## mark_cache_size
Approximate size (in bytes) of the cache of "marks" used by [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree).
Approximate size (in bytes) of the cache of "marks" used by [MergeTree](../../operations/table_engines/mergetree.md).
The cache is shared for the server and memory is allocated as needed. The cache size must be at least 5368709120.
@ -425,7 +425,7 @@ We recommend using this option in Mac OS X, since the `getrlimit()` function ret
Restriction on deleting tables.
If the size of a [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree) table exceeds `max_table_size_to_drop` (in bytes), you can't delete it using a DROP query.
If the size of a [MergeTree](../../operations/table_engines/mergetree.md) table exceeds `max_table_size_to_drop` (in bytes), you can't delete it using a DROP query.
If you still need to delete the table without restarting the ClickHouse server, create the `<clickhouse-path>/flags/force_drop_table` file and run the DROP query.
@ -443,7 +443,7 @@ The value 0 means that you can delete all tables without any restrictions.
## merge_tree
Fine tuning for tables in the [ MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree).
Fine tuning for tables in the [ MergeTree](../../operations/table_engines/mergetree.md).
For more information, see the MergeTreeSettings.h header file.
@ -520,7 +520,7 @@ Keys for server/client settings:
## part_log
Logging events that are associated with [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree). For instance, adding or merging data. You can use the log to simulate merge algorithms and compare their characteristics. You can visualize the merge process.
Logging events that are associated with [MergeTree](../../operations/table_engines/mergetree.md). For instance, adding or merging data. You can use the log to simulate merge algorithms and compare their characteristics. You can visualize the merge process.
Queries are logged in the ClickHouse table, not in a separate file.
@ -541,7 +541,7 @@ Use the following parameters to configure logging:
- database Name of the database.
- table Name of the table.
- partition_by Sets a [custom partitioning key](../../operations/table_engines/custom_partitioning_key.md#custom-partitioning-key).
- partition_by Sets a [custom partitioning key](../../operations/table_engines/custom_partitioning_key.md).
- flush_interval_milliseconds Interval for flushing data from the buffer in memory to the table.
**Example**
@ -574,7 +574,7 @@ The path to the directory containing data.
## query_log
Setting for logging queries received with the [log_queries=1](../settings/settings.md#settings_settings-log_queries) setting.
Setting for logging queries received with the [log_queries=1](../settings/settings.md) setting.
Queries are logged in the ClickHouse table, not in a separate file.
@ -582,7 +582,7 @@ Use the following parameters to configure logging:
- database Name of the database.
- table Name of the table.
- partition_by Sets a [custom partitioning key](../../operations/table_engines/custom_partitioning_key.md#custom-partitioning-key).
- partition_by Sets a [custom partitioning key](../../operations/table_engines/custom_partitioning_key.md).
- flush_interval_milliseconds Interval for flushing data from the buffer in memory to the table.
If the table doesn't exist, ClickHouse will create it. If the structure of the query log changed when the ClickHouse server was updated, the table with the old structure is renamed, and a new table is created automatically.
@ -604,7 +604,7 @@ If the table doesn't exist, ClickHouse will create it. If the structure of the q
Configuration of clusters used by the Distributed table engine.
For more information, see the section "[Table engines/Distributed](../../operations/table_engines/distributed.md#table_engines-distributed)".
For more information, see the section "[Table engines/Distributed](../../operations/table_engines/distributed.md)".
**Example**
@ -661,9 +661,9 @@ Path to temporary data for processing large queries.
## uncompressed_cache_size
Cache size (in bytes) for uncompressed data used by table engines from the [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree).
Cache size (in bytes) for uncompressed data used by table engines from the [MergeTree](../../operations/table_engines/mergetree.md).
There is one shared cache for the server. Memory is allocated on demand. The cache is used if the option [use_uncompressed_cache](../settings/settings.md#settings-use_uncompressed_cache) is enabled.
There is one shared cache for the server. Memory is allocated on demand. The cache is used if the option [use_uncompressed_cache](../settings/settings.md) is enabled.
The uncompressed cache is advantageous for very short queries in individual cases.
@ -675,7 +675,7 @@ The uncompressed cache is advantageous for very short queries in individual case
## user_files_path
The directory with user files. Used in the table function [file()](../../query_language/table_functions/file.md#table_functions-file).
The directory with user files. Used in the table function [file()](../../query_language/table_functions/file.md).
**Example**
@ -710,7 +710,7 @@ ClickHouse uses ZooKeeper for storing replica metadata when using replicated tab
This parameter can be omitted if replicated tables are not used.
For more information, see the section "[Replication](../../operations/table_engines/replication.md#table_engines-replication)".
For more information, see the section "[Replication](../../operations/table_engines/replication.md)".
**Example**

View File

@ -4,7 +4,7 @@
## distributed_product_mode
Changes the behavior of [distributed subqueries](../../query_language/select.md#queries-distributed-subrequests).
Changes the behavior of [distributed subqueries](../../query_language/select.md).
ClickHouse applies this setting when the query contains the product of distributed tables, i.e. when the query for a distributed table contains a non-GLOBAL subquery for the distributed table.
@ -13,7 +13,7 @@ Restrictions:
- Only applied for IN and JOIN subqueries.
- Only if the FROM section uses a distributed table containing more than one shard.
- If the subquery concerns a distributed table containing more than one shard,
- Not used for a table-valued [remote](../../query_language/table_functions/remote.md#table_functions-remote) function.
- Not used for a table-valued [remote](../../query_language/table_functions/remote.md) function.
The possible values are:
@ -26,7 +26,7 @@ The possible values are:
## fallback_to_stale_replicas_for_distributed_queries
Forces a query to an out-of-date replica if updated data is not available. See "[Replication](../../operations/table_engines/replication.md#table_engines-replication)".
Forces a query to an out-of-date replica if updated data is not available. See "[Replication](../../operations/table_engines/replication.md)".
ClickHouse selects the most relevant from the outdated replicas of the table.
@ -42,7 +42,7 @@ Disables query execution if the index can't be used by date.
Works with tables in the MergeTree family.
If `force_index_by_date=1`, ClickHouse checks whether the query has a date key condition that can be used for restricting data ranges. If there is no suitable condition, it throws an exception. However, it does not check whether the condition actually reduces the amount of data to read. For example, the condition `Date != ' 2000-01-01 '` is acceptable even when it matches all the data in the table (i.e., running the query requires a full scan). For more information about ranges of data in MergeTree tables, see "[MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree)".
If `force_index_by_date=1`, ClickHouse checks whether the query has a date key condition that can be used for restricting data ranges. If there is no suitable condition, it throws an exception. However, it does not check whether the condition actually reduces the amount of data to read. For example, the condition `Date != ' 2000-01-01 '` is acceptable even when it matches all the data in the table (i.e., running the query requires a full scan). For more information about ranges of data in MergeTree tables, see "[MergeTree](../../operations/table_engines/mergetree.md)".
<a name="settings-settings-force_primary_key"></a>
@ -52,7 +52,7 @@ Disables query execution if indexing by the primary key is not possible.
Works with tables in the MergeTree family.
If `force_primary_key=1`, ClickHouse checks to see if the query has a primary key condition that can be used for restricting data ranges. If there is no suitable condition, it throws an exception. However, it does not check whether the condition actually reduces the amount of data to read. For more information about data ranges in MergeTree tables, see "[MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree)".
If `force_primary_key=1`, ClickHouse checks to see if the query has a primary key condition that can be used for restricting data ranges. If there is no suitable condition, it throws an exception. However, it does not check whether the condition actually reduces the amount of data to read. For more information about data ranges in MergeTree tables, see "[MergeTree](../../operations/table_engines/mergetree.md)".
<a name="settings_settings_fsync_metadata"></a>
@ -91,7 +91,7 @@ If `input_format_allow_errors_ratio` is exceeded, ClickHouse throws an exception
## join_default_strictness
Sets default strictness for [JOIN clause](../../query_language/select.md#query-language-join).
Sets default strictness for [JOIN clause](../../query_language/select.md).
**Possible values**
@ -123,7 +123,7 @@ Disabled by default (set to 0). It only works when reading from MergeTree engine
Setting up query logging.
Queries sent to ClickHouse with this setup are logged according to the rules in the [query_log](../server_settings/settings.md#server_settings-query_log) server configuration parameter.
Queries sent to ClickHouse with this setup are logged according to the rules in the [query_log](../server_settings/settings.md) server configuration parameter.
**Example**:
@ -147,7 +147,7 @@ This is slightly more than `max_block_size`. The reason for this is because cert
## max_replica_delay_for_distributed_queries
Disables lagging replicas for distributed queries. See "[Replication](../../operations/table_engines/replication.md#table_engines-replication)".
Disables lagging replicas for distributed queries. See "[Replication](../../operations/table_engines/replication.md)".
Sets the time in seconds. If a replica lags more than the set value, this replica is not used.
@ -180,7 +180,7 @@ Don't confuse blocks for compression (a chunk of memory consisting of bytes) and
## min_compress_block_size
For [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree)" tables. In order to reduce latency when processing queries, a block is compressed when writing the next mark if its size is at least 'min_compress_block_size'. By default, 65,536.
For [MergeTree](../../operations/table_engines/mergetree.md)" tables. In order to reduce latency when processing queries, a block is compressed when writing the next mark if its size is at least 'min_compress_block_size'. By default, 65,536.
The actual size of the block, if the uncompressed data is less than 'max_compress_block_size', is no less than this value and no less than the volume of data for one mark.
@ -281,7 +281,7 @@ This parameter is useful when you are using formats that require a schema defini
## stream_flush_interval_ms
Works for tables with streaming in the case of a timeout, or when a thread generates[max_insert_block_size](#settings-settings-max_insert_block_size) rows.
Works for tables with streaming in the case of a timeout, or when a thread generates[max_insert_block_size]() rows.
The default value is 7500.
@ -371,9 +371,9 @@ The character interpreted as a delimiter in the CSV data. By default, the delimi
## join_use_nulls
Affects the behavior of [JOIN](../../query_language/select.md#query_language-join).
Affects the behavior of [JOIN](../../query_language/select.md).
With `join_use_nulls=1,` `JOIN` behaves like in standard SQL, i.e. if empty cells appear when merging, the type of the corresponding field is converted to [Nullable](../../data_types/nullable.md#data_type-nullable), and empty cells are filled with [NULL](../../query_language/syntax.md#null-literal).
With `join_use_nulls=1,` `JOIN` behaves like in standard SQL, i.e. if empty cells appear when merging, the type of the corresponding field is converted to [Nullable](../../data_types/nullable.md#data_type-nullable), and empty cells are filled with [NULL](../../query_language/syntax.md).
<a name="setting-insert_quorum"></a>
@ -392,7 +392,7 @@ The default value is 0.
All the replicas in the quorum are consistent, i.e., they contain data from all previous `INSERT` queries. The `INSERT` sequence is linearized.
When reading the data written from the `insert_quorum`, you can use the[select_sequential_consistency](#setting-select_sequential_consistency) option.
When reading the data written from the `insert_quorum`, you can use the[select_sequential_consistency]() option.
**ClickHouse generates an exception**
@ -401,8 +401,8 @@ When reading the data written from the `insert_quorum`, you can use the[select_s
**See also the following parameters:**
- [insert_quorum_timeout](#setting-insert_quorum_timeout)
- [select_sequential_consistency](#setting-select_sequential_consistency)
- [insert_quorum_timeout]()
- [select_sequential_consistency]()
<a name="setting-insert_quorum_timeout"></a>
@ -414,8 +414,8 @@ By default, 60 seconds.
**See also the following parameters:**
- [insert_quorum](#setting-insert_quorum)
- [select_sequential_consistency](#setting-select_sequential_consistency)
- [insert_quorum]()
- [select_sequential_consistency]()
<a name="setting-select_sequential_consistency"></a>
@ -430,8 +430,8 @@ When sequential consistency is enabled, ClickHouse allows the client to execute
See also the following parameters:
- [insert_quorum](#setting-insert_quorum)
- [insert_quorum_timeout](#setting-insert_quorum_timeout)
- [insert_quorum]()
- [insert_quorum_timeout]()
[Original article](https://clickhouse.yandex/docs/en/operations/settings/settings/) <!--hide-->

View File

@ -128,7 +128,7 @@ This is similar to the DUAL table found in other DBMSs.
## system.parts
Contains information about parts of [MergeTree](table_engines/mergetree.md#table_engines-mergetree) tables.
Contains information about parts of [MergeTree](table_engines/mergetree.md) tables.
Each row describes one part of the data.

View File

@ -2,11 +2,11 @@
# 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 (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.
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)) 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.
The engine processes all columns with [AggregateFunction](../../data_types/nested_data_structures/aggregatefunction.md#data_type-aggregatefunction) type.
The engine processes all columns with [AggregateFunction](../../data_types/nested_data_structures/aggregatefunction.md) type.
It is appropriate to use `AggregatingMergeTree` if it reduces the number of rows by orders.
@ -25,11 +25,11 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of request parameters, see [request description](../../query_language/create.md#query_language-queries-create_table).
For a description of request parameters, see [request description](../../query_language/create.md).
**Query clauses**
When creating a `ReplacingMergeTree` table the same [clauses](mergetree.md#table_engines-mergetree-configuring) are required, as when creating a `MergeTree` table.
When creating a `ReplacingMergeTree` table the same [clauses](mergetree.md) are required, as when creating a `MergeTree` table.
<details markdown="1"><summary>Deprecated Method for Creating a Table</summary>
@ -50,8 +50,7 @@ All of the parameters have the same meaning as in `MergeTree`.
## SELECT and INSERT
To insert data, use [INSERT SELECT](../../query_language/insert_into.md#queries-insert-select) query with aggregate `-State`- functions.
To insert data, use [INSERT SELECT](../../query_language/insert_into.md
When selecting data from `AggregatingMergeTree` table, use `GROUP BY` clause and the same aggregate functions as when inserting data, but using `-Merge` suffix.
In the results of `SELECT` query the values of `AggregateFunction` type have implementation-specific binary representation for all of the ClickHouse output formats. If dump data into, for example, `TabSeparated` format with `SELECT` query then this dump can be loaded back using `INSERT` query.

View File

@ -2,9 +2,9 @@
# CollapsingMergeTree
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree) and adds the logic of rows collapsing to data parts merge algorithm.
The engine inherits from [MergeTree](mergetree.md) and adds the logic of rows collapsing to data parts merge algorithm.
`CollapsingMergeTree` asynchronously deletes (collapses) pairs of rows if all of the fields in a row are equivalent excepting the particular field `Sign` which can have `1` and `-1` values. Rows without a pair are kept. For more details see the [Collapsing](#collapsingmergetree-collapsing) section of the document.
`CollapsingMergeTree` asynchronously deletes (collapses) pairs of rows if all of the fields in a row are equivalent excepting the particular field `Sign` which can have `1` and `-1` values. Rows without a pair are kept. For more details see the [Collapsing]() section of the document.
The engine may significantly reduce the volume of storage and increase efficiency of `SELECT` query as a consequence.
@ -23,7 +23,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of query parameters, see [query description](../../query_language/create.md#query_language-queries-create_table).
For a description of query parameters, see [query description](../../query_language/create.md).
**CollapsingMergeTree Parameters**
@ -33,7 +33,7 @@ For a description of query parameters, see [query description](../../query_langu
**Query clauses**
When creating a `CollapsingMergeTree` table, the same [clauses](mergetree.md#table_engines-mergetree-configuring) are required, as when creating a `MergeTree` table.
When creating a `CollapsingMergeTree` table, the same [clauses](mergetree.md) are required, as when creating a `MergeTree` table.
<details markdown="1"><summary>Deprecated Method for Creating a Table</summary>

View File

@ -2,7 +2,7 @@
# Dictionary
The `Dictionary` engine displays the [dictionary](../../query_language/dicts/external_dicts.md#dicts-external_dicts) data as a ClickHouse table.
The `Dictionary` engine displays the [dictionary](../../query_language/dicts/external_dicts.md) data as a ClickHouse table.
As an example, consider a dictionary of `products` with the following configuration:

View File

@ -18,11 +18,11 @@ File(Format)
`Format` should be supported for either `INSERT` and `SELECT`. For the full list of supported formats see [Formats](../../interfaces/formats.md#formats).
ClickHouse does not allow to specify filesystem path for`File`. It will use folder defined by [path](../server_settings/settings.md#server_settings-path) setting in server configuration.
ClickHouse does not allow to specify filesystem path for`File`. It will use folder defined by [path](../server_settings/settings.md) setting in server configuration.
When creating table using `File(Format)` it creates empty subdirectory in that folder. When data is written to that table, it's put into `data.Format` file in that subdirectory.
You may manually create this subfolder and file in server filesystem and then [ATTACH](../../query_language/misc.md#queries-attach) it to table information with matching name, so you can query data from that file.
You may manually create this subfolder and file in server filesystem and then [ATTACH](../../query_language/misc.md) it to table information with matching name, so you can query data from that file.
!!! warning
Be careful with this funcionality, because ClickHouse does not keep track of external changes to such files. The result of simultaneous writes via ClickHouse and outside of ClickHouse is undefined.
@ -60,8 +60,7 @@ SELECT * FROM file_engine_table
## Usage in Clickhouse-local
In [clickhouse-local](../utils/clickhouse-local.md#utils-clickhouse-local) File engine accepts file path in addition to `Format`. Default input/output streams can be specified using numeric or human-readable names like `0` or `stdin`, `1` or `stdout`.
In [clickhouse-local](../utils/clickhouse-local.md
**Example:**
```bash

View File

@ -6,7 +6,7 @@ This engine is designed for rollup (thinning and aggregating/averaging) [Graphit
You can use any ClickHouse table engine to store the Graphite data if you don't need rollup, but if you need a rollup use `GraphiteMergeTree`. The engine reduces the volume of storage and increases the efficiency of queries from Graphite.
The engine inherits properties from [MergeTree](mergetree.md#table_engines-mergetree).
The engine inherits properties from [MergeTree](mergetree.md).
## Creating a Table
@ -25,7 +25,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of request parameters, see [request description](../../query_language/create.md#query_language-queries-create_table).
For a description of request parameters, see [request description](../../query_language/create.md).
A table for the Graphite date should have the following columns:
@ -44,7 +44,7 @@ The names of these columns should be set in the rollup configuration.
**Query clauses**
When creating a `GraphiteMergeTree` table, the same [clauses](mergetree.md#table_engines-mergetree-configuring) are required, as when creating a `MergeTree` table.
When creating a `GraphiteMergeTree` table, the same [clauses](mergetree.md) are required, as when creating a `MergeTree` table.
<details markdown="1"><summary>Deprecated Method for Creating a Table</summary>
@ -70,7 +70,7 @@ All of the parameters excepting `config_section` have the same meaning as in `Me
## Rollup configuration
The settings for rollup are defined by the [graphite_rollup](../server_settings/settings.md#server_settings-graphite_rollup) parameter in the server configuration. The name of the parameter could be any. You can create several configurations and use them for different tables.
The settings for rollup are defined by the [graphite_rollup](../server_settings/settings.md) parameter in the server configuration. The name of the parameter could be any. You can create several configurations and use them for different tables.
Rollup configuration structure:

View File

@ -106,7 +106,7 @@ Example:
SELECT level, sum(total) FROM daily GROUP BY level;
```
To improve performance, received messages are grouped into blocks the size of [max_insert_block_size](../settings/settings.md#settings-settings-max_insert_block_size). If the block wasn't formed within [stream_flush_interval_ms](../settings/settings.md#settings-settings_stream_flush_interval_ms) milliseconds, the data will be flushed to the table regardless of the completeness of the block.
To improve performance, received messages are grouped into blocks the size of [max_insert_block_size](../settings/settings.md#settings-settings-max_insert_block_size). If the block wasn't formed within [stream_flush_interval_ms](../settings/settings.md) milliseconds, the data will be flushed to the table regardless of the completeness of the block.
To stop receiving topic data or to change the conversion logic, detach the materialized view:

View File

@ -1,6 +1,6 @@
# MaterializedView
Used for implementing materialized views (for more information, see [CREATE TABLE](../../query_language/create.md#query_language-queries-create_table)). For storing data, it uses a different engine that was specified when creating the view. When reading from a table, it just uses this engine.
Used for implementing materialized views (for more information, see [CREATE TABLE](../../query_language/create.md)). For storing data, it uses a different engine that was specified when creating the view. When reading from a table, it just uses this engine.
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/materializedview/) <!--hide-->

View File

@ -12,20 +12,20 @@ Main features:
This allows you to create a small sparse index that helps find data faster.
- This allows you to use partitions if the [partitioning key](custom_partitioning_key.md#table_engines-custom_partitioning_key) is specified.
- This allows you to use partitions if the [partitioning key](custom_partitioning_key.md) is specified.
ClickHouse supports certain operations with partitions that are more effective than general operations on the same data with the same result. ClickHouse also automatically cuts off the partition data where the partitioning key is specified in the query. This also increases the query performance.
- Data replication support.
The family of `ReplicatedMergeTree` tables is used for this. For more information, see the [Data replication](replication.md#table_engines-replication) section.
The family of `ReplicatedMergeTree` tables is used for this. For more information, see the [Data replication](replication.md) section.
- Data sampling support.
If necessary, you can set the data sampling method in the table.
!!! info
The [Merge](merge.md#table_engine-merge) engine does not belong to the `*MergeTree` family.
The [Merge](merge.md) engine does not belong to the `*MergeTree` family.
<a name="table_engines-mergetree-configuring"></a>
@ -45,21 +45,21 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of request parameters, see [request description](../../query_language/create.md#query_language-queries-create_table).
For a description of request parameters, see [request description](../../query_language/create.md).
**Query clauses**
- `ENGINE` - Name and parameters of the engine. `ENGINE = MergeTree()`. `MergeTree` engine does not have parameters.
- `PARTITION BY` — The [partitioning key](custom_partitioning_key.md#table_engines-custom_partitioning_key).
- `PARTITION BY` — The [partitioning key](custom_partitioning_key.md).
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.
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). The partition names here have the `"YYYYMM"` format.
- `ORDER BY` — The sorting key.
A tuple of columns or arbitrary expressions. Example: `ORDER BY (CounterID, EventDate)`.
- `PRIMARY KEY` - The primary key if it [differs from the sorting key](mergetree.md#table_engines-mergetree-sorting_key).
- `PRIMARY KEY` - The primary key if it [differs from the sorting key](mergetree.md).
By default the primary key is the same as the sorting key (which is specified by the `ORDER BY` clause).
Thus in most cases it is unnecessary to specify a separate `PRIMARY KEY` clause.
@ -80,7 +80,7 @@ ENGINE MergeTree() PARTITION BY toYYYYMM(EventDate) ORDER BY (CounterID, EventDa
In the example, we set partitioning by month.
We also set an expression for sampling as a hash by the user ID. This allows you to pseudorandomize the data in the table for each `CounterID` and `EventDate`. If, when selecting the data, you define a [SAMPLE](../../query_language/select.md#select-section-sample) clause, ClickHouse will return an evenly pseudorandom data sample for a subset of users.
We also set an expression for sampling as a hash by the user ID. This allows you to pseudorandomize the data in the table for each `CounterID` and `EventDate`. If, when selecting the data, you define a [SAMPLE](../../query_language/select.md) clause, ClickHouse will return an evenly pseudorandom data sample for a subset of users.
`index_granularity` could be omitted because 8192 is the default value.
@ -100,10 +100,9 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
**MergeTree() parameters**
- `date-column` — The name of a column of the type [Date](../../data_types/date.md#data_type-date). ClickHouse automatically creates partitions by month on the basis of this column. The partition names are in the `"YYYYMM"` format.
- `date-column` — The name of a column of the type [Date](../../data_types/date.md). ClickHouse automatically creates partitions by month on the basis of this column. The partition names are in the `"YYYYMM"` format.
- `sampling_expression` — an expression for sampling.
- `(primary, key)` — primary key. Type — [Tuple()](../../data_types/tuple.md#data_type-tuple). It may consist of arbitrary expressions, but it typically is a tuple of columns. It must include an expression for sampling if it is set. It must not include a column with a `date-column` date.
- `index_granularity` — The granularity of an index. The number of data rows between the "marks" of an index. The value 8192 is appropriate for most tasks.
- `(primary, key)` — primary key. Type — [Tuple()](../../data_types/tuple.md- `index_granularity` — The granularity of an index. The number of data rows between the "marks" of an index. The value 8192 is appropriate for most tasks.
**Example**
@ -167,7 +166,7 @@ The number of columns in the primary key is not explicitly limited. Depending on
ClickHouse sorts data by primary key, so the higher the consistency, the better the compression.
- Provide additional logic when data parts merging in the [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) and [SummingMergeTree](summingmergetree.md#table_engine-summingmergetree) engines.
- Provide additional logic when data parts merging in the [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) and [SummingMergeTree](summingmergetree.md) engines.
In this case it makes sense to specify the *sorting key* that is different from the primary key.
@ -192,7 +191,7 @@ 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
[ALTER of the sorting key](../../query_language/alter.md) 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).
@ -226,7 +225,7 @@ In the example below, the index can't be used.
SELECT count() FROM table WHERE CounterID = 34 OR URL LIKE '%upyachka%'
```
To check whether ClickHouse can use the index when running a query, use the settings [force_index_by_date](../settings/settings.md#settings-settings-force_index_by_date) and [force_primary_key](../settings/settings.md#settings-settings-force_primary_key).
To check whether ClickHouse can use the index when running a query, use the settings [force_index_by_date](../settings/settings.md#settings-settings-force_index_by_date) and [force_primary_key](../settings/settings.md).
The key for partitioning by month allows reading only those data blocks which contain dates from the proper range. In this case, the data block may contain data for many dates (up to an entire month). Within a block, data is sorted by primary key, which might not contain the date as the first column. Because of this, using a query with only a date condition that does not specify the primary key prefix will cause more data to be read than for a single date.

View File

@ -28,7 +28,7 @@ At this time, simple `WHERE` clauses such as ` =, !=, >, >=, <, <=` are executed
The rest of the conditions and the `LIMIT` sampling constraint are executed in ClickHouse only after the query to MySQL finishes.
The `MySQL` engine does not support the [Nullable](../../data_types/nullable.md#data_type-nullable) data type, so when reading data from MySQL tables, `NULL` is converted to default values for the specified column type (usually 0 or an empty string).
The `MySQL` engine does not support the [Nullable](../../data_types/nullable.md) data type, so when reading data from MySQL tables, `NULL` is converted to default values for the specified column type (usually 0 or an empty string).
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/mysql/) <!--hide-->

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 (or more accurately, with the same [sorting key](mergetree.md#table_engines-mergetree-sorting_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) 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.
@ -21,7 +21,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of request parameters, see [request description](../../query_language/create.md#query_language-queries-create_table).
For a description of request parameters, see [request description](../../query_language/create.md).
**ReplacingMergeTree Parameters**
@ -33,7 +33,7 @@ For a description of request parameters, see [request description](../../query_l
**Query clauses**
When creating a `ReplacingMergeTree` table the same [clauses](mergetree.md#table_engines-mergetree-configuring) are required, as when creating a `MergeTree` table.
When creating a `ReplacingMergeTree` table the same [clauses](mergetree.md) are required, as when creating a `MergeTree` table.
<details markdown="1"><summary>Deprecated Method for Creating a Table</summary>

View File

@ -49,7 +49,7 @@ You can specify any existing ZooKeeper cluster and the system will use a directo
If ZooKeeper isn't set in the config file, you can't create replicated tables, and any existing replicated tables will be read-only.
ZooKeeper is not used in `SELECT` queries because replication does not affect the performance of `SELECT` and queries run just as fast as they do for non-replicated tables. When querying distributed replicated tables, ClickHouse behavior is controlled by the settings [max_replica_delay_for_distributed_queries](../settings/settings.md#settings_settings_max_replica_delay_for_distributed_queries) and [fallback_to_stale_replicas_for_distributed_queries](../settings/settings.md#settings-settings-fallback_to_stale_replicas_for_distributed_queries).
ZooKeeper is not used in `SELECT` queries because replication does not affect the performance of `SELECT` and queries run just as fast as they do for non-replicated tables. When querying distributed replicated tables, ClickHouse behavior is controlled by the settings [max_replica_delay_for_distributed_queries](../settings/settings.md#settings_settings_max_replica_delay_for_distributed_queries) and [fallback_to_stale_replicas_for_distributed_queries](../settings/settings.md).
For each `INSERT` query, approximately ten entries are added to ZooKeeper through several transactions. (To be more precise, this is for each inserted block of data; an INSERT query contains one block or one block per `max_insert_block_size = 1048576` rows.) This leads to slightly longer latencies for `INSERT` compared to non-replicated tables. But if you follow the recommendations to insert data in batches of no more than one `INSERT` per second, it doesn't create any problems. The entire ClickHouse cluster used for coordinating one ZooKeeper cluster has a total of several hundred `INSERTs` per second. The throughput on data inserts (the number of rows per second) is just as high as for non-replicated data.
@ -61,7 +61,7 @@ By default, an INSERT query waits for confirmation of writing the data from only
Each block of data is written atomically. The INSERT query is divided into blocks up to `max_insert_block_size = 1048576` rows. In other words, if the `INSERT` query has less than 1048576 rows, it is made atomically.
Data blocks are deduplicated. For multiple writes of the same data block (data blocks of the same size containing the same rows in the same order), the block is only written once. The reason for this is in case of network failures when the client application doesn't know if the data was written to the DB, so the `INSERT` query can simply be repeated. It doesn't matter which replica INSERTs were sent to with identical data. `INSERTs` are idempotent. Deduplication parameters are controlled by [merge_tree](../server_settings/settings.md#server_settings-merge_tree) server settings.
Data blocks are deduplicated. For multiple writes of the same data block (data blocks of the same size containing the same rows in the same order), the block is only written once. The reason for this is in case of network failures when the client application doesn't know if the data was written to the DB, so the `INSERT` query can simply be repeated. It doesn't matter which replica INSERTs were sent to with identical data. `INSERTs` are idempotent. Deduplication parameters are controlled by [merge_tree](../server_settings/settings.md) server settings.
During replication, only the source data to insert is transferred over the network. Further data transformation (merging) is coordinated and performed on all the replicas in the same way. This minimizes network usage, which means that replication works well when replicas reside in different datacenters. (Note that duplicating data in different datacenters is the main goal of replication.)
@ -173,7 +173,7 @@ If all data and metadata disappeared from one of the servers, follow these steps
Then start the server (restart, if it is already running). Data will be downloaded from replicas.
An alternative recovery option is to delete information about the lost replica from ZooKeeper (`/path_to_table/replica_name`), then create the replica again as described in "[Creating replicatable tables](#table_engines-replication-creation_of_rep_tables)".
An alternative recovery option is to delete information about the lost replica from ZooKeeper (`/path_to_table/replica_name`), then create the replica again as described in "[Creating replicatable tables]()".
There is no restriction on network bandwidth during recovery. Keep this in mind if you are restoring many replicas at once.

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 (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.
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)) 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.
@ -21,7 +21,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of request parameters, see [request description](../../query_language/create.md#query_language-queries-create_table).
For a description of request parameters, see [request description](../../query_language/create.md).
**Parameters of SummingMergeTree**
@ -32,7 +32,7 @@ The columns must be of a numeric type and must not be in the primary key.
**Query clauses**
When creating a `SummingMergeTree` table the same [clauses](mergetree.md#table_engines-mergetree-configuring) are required, as when creating a `MergeTree` table.
When creating a `SummingMergeTree` table the same [clauses](mergetree.md) are required, as when creating a `MergeTree` table.
<details markdown="1"><summary>Deprecated Method for Creating a Table</summary>
@ -73,7 +73,7 @@ Insert data to it:
:) INSERT INTO summtt Values(1,1),(1,2),(2,1)
```
ClickHouse may sum all the rows not completely ([see below](#summary-data-processing)), so we use an aggregate function `sum` and `GROUP BY` clause in the query.
ClickHouse may sum all the rows not completely ([see below]()), so we use an aggregate function `sum` and `GROUP BY` clause in the query.
```sql
SELECT key, sum(value) FROM summtt GROUP BY key
@ -92,7 +92,7 @@ SELECT key, sum(value) FROM summtt GROUP BY key
When data are inserted into a table, they are saved as-is. Clickhouse merges the inserted parts of data periodically and this is when rows with the same primary key are summed and replaced with one for each resulting part of data.
ClickHouse can merge the data parts so that different resulting parts of data cat consist rows with the same primary key, i.e. the summation will be incomplete. Therefore (`SELECT`) an aggregate function [sum()](../../query_language/agg_functions/reference.md#agg_function-sum) and `GROUP BY` clause should be used in a query as described in the example above.
ClickHouse can merge the data parts so that different resulting parts of data cat consist rows with the same primary key, i.e. the summation will be incomplete. Therefore (`SELECT`) an aggregate function [sum()](../../query_language/agg_functions/reference.md) and `GROUP BY` clause should be used in a query as described in the example above.
### Common rules for summation
@ -106,7 +106,7 @@ The values are not summarized for columns in the primary key.
### The Summation in the AggregateFunction Columns
For columns of [AggregateFunction type](../../data_types/nested_data_structures/aggregatefunction.md#data_type-aggregatefunction) ClickHouse behaves as [AggregatingMergeTree](aggregatingmergetree.md#table_engine-aggregatingmergetree) engine aggregating according to the function.
For columns of [AggregateFunction type](../../data_types/nested_data_structures/aggregatefunction.md#data_type-aggregatefunction) ClickHouse behaves as [AggregatingMergeTree](aggregatingmergetree.md) engine aggregating according to the function.
### Nested Structures
@ -128,7 +128,7 @@ Examples:
[(1, 100), (2, 150)] + [(1, -100)] -> [(2, 150)]
```
When requesting data, use the [sumMap(key, value)](../../query_language/agg_functions/reference.md#agg_function-summary) function for aggregation of `Map`.
When requesting data, use the [sumMap(key, value)](../../query_language/agg_functions/reference.md) function for aggregation of `Map`.
For nested data structure, you do not need to specify its columns in the tuple of columns for summation.

View File

@ -7,9 +7,9 @@ This engine:
- Allows quick writing of continually changing states of objects.
- Deletes old states of objects in the background. It causes to significant reduction of the volume of storage.
See the section [Collapsing](#versionedcollapsingmergetree-collapsing) for details.
See the section [Collapsing]() for details.
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree) and adds the logic of rows collapsing to data parts merge algorithm. `VersionedCollapsingMergeTree` solves the same problem as the [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) but uses another algorithm of collapsing. It allows inserting the data in any order with multiple threads. The particular `Version` column helps to collapse the rows properly even if they are inserted in the wrong order. `CollapsingMergeTree` allows only strictly consecutive insertion.
The engine inherits from [MergeTree](mergetree.md#table_engines-mergetree) and adds the logic of rows collapsing to data parts merge algorithm. `VersionedCollapsingMergeTree` solves the same problem as the [CollapsingMergeTree](collapsingmergetree.md) but uses another algorithm of collapsing. It allows inserting the data in any order with multiple threads. The particular `Version` column helps to collapse the rows properly even if they are inserted in the wrong order. `CollapsingMergeTree` allows only strictly consecutive insertion.
## Creating a Table
@ -26,7 +26,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
For a description of query parameters, see [query description](../../query_language/create.md#query_language-queries-create_table).
For a description of query parameters, see [query description](../../query_language/create.md).
**Engine Parameters**
@ -44,7 +44,7 @@ VersionedCollapsingMergeTree(sign, version)
**Query Clauses**
When creating a `VersionedCollapsingMergeTree` table, the same [clauses](mergetree.md#table_engines-mergetree-configuring) are required, as when creating a `MergeTree` table.
When creating a `VersionedCollapsingMergeTree` table, the same [clauses](mergetree.md) are required, as when creating a `MergeTree` table.
<details markdown="1"><summary>Deprecated Method for Creating a Table</summary>

View File

@ -1,7 +1,7 @@
# ClickHouse Utility
* [clickhouse-local](clickhouse-local.md#utils-clickhouse-local) — Allows running SQL queries on data without stopping the ClickHouse server, similar to how `awk` does this.
* [clickhouse-copier](clickhouse-copier.md#utils-clickhouse-copier) — Copies (and reshards) data from one cluster to another cluster.
* [clickhouse-local](clickhouse-local.md) — Allows running SQL queries on data without stopping the ClickHouse server, similar to how `awk` does this.
* [clickhouse-copier](clickhouse-copier.md) — Copies (and reshards) data from one cluster to another cluster.
[Original article](https://clickhouse.yandex/docs/en/operations/utils/) <!--hide-->

View File

@ -61,7 +61,7 @@ windowFunnel(window)(timestamp, cond1, cond2, cond3, ...)
**Parameters:**
- `window` — Length of the sliding window in seconds.
- `timestamp` — Name of the column containing the timestamp. Data type: [DateTime](../../data_types/datetime.md#data_type-datetime) or [UInt32](../../data_types/int_uint.md#data_type-int).
- `timestamp` — Name of the column containing the timestamp. Data type: [DateTime](../../data_types/datetime.md#data_type-datetime) or [UInt32](../../data_types/int_uint.md).
- `cond1`, `cond2`... — Conditions or data describing the chain of events. Data type: `UInt8`. Values can be 0 or 1.
**Algorithm**

View File

@ -35,7 +35,7 @@ anyHeavy(column)
**Example**
Take the [OnTime](../../getting_started/example_datasets/ontime.md#example_datasets-ontime) data set and select any frequently occurring value in the `AirlineID` column.
Take the [OnTime](../../getting_started/example_datasets/ontime.md) data set and select any frequently occurring value in the `AirlineID` column.
``` sql
SELECT anyHeavy(AirlineID) AS res
@ -462,7 +462,7 @@ We recommend using the `N < 10 ` value; performance is reduced with large `N` va
**Example**
Take the [OnTime](../../getting_started/example_datasets/ontime.md#example_datasets-ontime) data set and select the three most frequently occurring values in the `AirlineID` column.
Take the [OnTime](../../getting_started/example_datasets/ontime.md) data set and select the three most frequently occurring values in the `AirlineID` column.
``` sql
SELECT topK(3)(AirlineID) AS res

View File

@ -78,7 +78,7 @@ MODIFY ORDER BY new_expression
It only works for tables in the [`MergeTree`](../operations/table_engines/mergetree.md) family (including
[replicated](../operations/table_engines/replication.md) tables). The command changes the
[sorting key](../operations/table_engines/mergetree.md#table_engines-mergetree-sorting_key) of the table
[sorting key](../operations/table_engines/mergetree.md) 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

View File

@ -2,16 +2,16 @@
# External Dictionaries
You can add your own dictionaries from various data sources. The data source for a dictionary can be a local text or executable file, an HTTP(s) resource, or another DBMS. For more information, see "[Sources for external dictionaries](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources)".
You can add your own dictionaries from various data sources. The data source for a dictionary can be a local text or executable file, an HTTP(s) resource, or another DBMS. For more information, see "[Sources for external dictionaries](external_dicts_dict_sources.md)".
ClickHouse:
> - Fully or partially stores dictionaries in RAM.
- Periodically updates dictionaries and dynamically loads missing values. In other words, dictionaries can be loaded dynamically.
The configuration of external dictionaries is located in one or more files. The path to the configuration is specified in the [dictionaries_config](../../operations/server_settings/settings.md#server_settings-dictionaries_config) parameter.
The configuration of external dictionaries is located in one or more files. The path to the configuration is specified in the [dictionaries_config](../../operations/server_settings/settings.md) parameter.
Dictionaries can be loaded at server startup or at first use, depending on the [dictionaries_lazy_load](../../operations/server_settings/settings.md#server_settings-dictionaries_lazy_load) setting.
Dictionaries can be loaded at server startup or at first use, depending on the [dictionaries_lazy_load](../../operations/server_settings/settings.md) setting.
The dictionary config file has the following format:
@ -35,11 +35,11 @@ The dictionary config file has the following format:
</yandex>
```
You can [configure](external_dicts_dict.md#dicts-external_dicts_dict) any number of dictionaries in the same file. The file format is preserved even if there is only one dictionary (i.e. `<yandex><dictionary> <!--configuration -> </dictionary></yandex>` ).
You can [configure](external_dicts_dict.md).
See also "[Functions for working with external dictionaries](../functions/ext_dict_functions.md#ext_dict_functions)".
!!! attention
You can convert values for a small dictionary by describing it in a `SELECT` query (see the [transform](../functions/other_functions.md#other_functions-transform) function). This functionality is not related to external dictionaries.
You can convert values for a small dictionary by describing it in a `SELECT` query (see the [transform](../functions/other_functions.md) function). This functionality is not related to external dictionaries.
[Original article](https://clickhouse.yandex/docs/en/query_language/dicts/external_dicts/) <!--hide-->

View File

@ -27,9 +27,9 @@ The dictionary configuration has the following structure:
```
- name The identifier that can be used to access the dictionary. Use the characters `[a-zA-Z0-9_\-]`.
- [source](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources) — Source of the dictionary.
- [layout](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout) — Dictionary layout in memory.
- [structure](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure) — Structure of the dictionary . A key and attributes that can be retrieved by this key.
- [lifetime](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime) — Frequency of dictionary updates.
- [source](external_dicts_dict_sources.md) — Source of the dictionary.
- [layout](external_dicts_dict_layout.md) — Dictionary layout in memory.
- [structure](external_dicts_dict_structure.md) — Structure of the dictionary . A key and attributes that can be retrieved by this key.
- [lifetime](external_dicts_dict_lifetime.md) — Frequency of dictionary updates.
[Original article](https://clickhouse.yandex/docs/en/query_language/dicts/external_dicts_dict/) <!--hide-->

View File

@ -2,11 +2,11 @@
# Storing Dictionaries in Memory
There are a [variety of ways](#dicts-external_dicts_dict_layout-manner) to store dictionaries in memory.
There are a [variety of ways]() to store dictionaries in memory.
We recommend [flat](#dicts-external_dicts_dict_layout-flat), [hashed](#dicts-external_dicts_dict_layout-hashed)and[complex_key_hashed](#dicts-external_dicts_dict_layout-complex_key_hashed). which provide optimal processing speed.
We recommend [flat](#dicts-external_dicts_dict_layout-flat), [hashed](#dicts-external_dicts_dict_layout-hashed)and[complex_key_hashed](). which provide optimal processing speed.
Caching is not recommended because of potentially poor performance and difficulties in selecting optimal parameters. Read more in the section "[cache](#dicts-external_dicts_dict_layout-cache)".
Caching is not recommended because of potentially poor performance and difficulties in selecting optimal parameters. Read more in the section "[cache]()".
There are several ways to improve dictionary performance:
@ -40,13 +40,13 @@ The configuration looks like this:
## Ways to Store Dictionaries in Memory
- [flat](#dicts-external_dicts_dict_layout-flat)
- [hashed](#dicts-external_dicts_dict_layout-hashed)
- [cache](#dicts-external_dicts_dict_layout-cache)
- [range_hashed](#dicts-external_dicts_dict_layout-range_hashed)
- [complex_key_hashed](#dicts-external_dicts_dict_layout-complex_key_hashed)
- [complex_key_cache](#dicts-external_dicts_dict_layout-complex_key_cache)
- [ip_trie](#dicts-external_dicts_dict_layout-ip_trie)
- [flat]()
- [hashed]()
- [cache]()
- [range_hashed]()
- [complex_key_hashed]()
- [complex_key_cache]()
- [ip_trie]()
<a name="dicts-external_dicts_dict_layout-flat"></a>
@ -88,7 +88,7 @@ Configuration example:
### complex_key_hashed
This type of storage is for use with composite [keys](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure). Similar to `hashed`.
This type of storage is for use with composite [keys](external_dicts_dict_structure.md). Similar to `hashed`.
Configuration example:
@ -120,7 +120,7 @@ Example: The table contains discounts for each advertiser in the format:
+---------------+---------------------+-------------------+--------+
```
To use a sample for date ranges, define the `range_min` and `range_max` elements in the [structure](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure).
To use a sample for date ranges, define the `range_min` and `range_max` elements in the [structure](external_dicts_dict_structure.md).
Example:
@ -193,13 +193,12 @@ The dictionary is stored in a cache that has a fixed number of cells. These cell
When searching for a dictionary, the cache is searched first. For each block of data, all keys that are not found in the cache or are outdated are requested from the source using ` SELECT attrs... FROM db.table WHERE id IN (k1, k2, ...)`. The received data is then written to the cache.
For cache dictionaries, the expiration [lifetime](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime) of data in the cache can be set. If more time than `lifetime` has passed since loading the data in a cell, the cell's value is not used, and it is re-requested the next time it needs to be used.
For cache dictionaries, the expiration [lifetime](external_dicts_dict_lifetime.md
This is the least effective of all the ways to store dictionaries. The speed of the cache depends strongly on correct settings and the usage scenario. A cache type dictionary performs well only when the hit rates are high enough (recommended 99% and higher). You can view the average hit rate in the `system.dictionaries` table.
To improve cache performance, use a subquery with ` LIMIT`, and call the function with the dictionary externally.
Supported [sources](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources): MySQL, ClickHouse, executable, HTTP.
Supported [sources](external_dicts_dict_sources.md): MySQL, ClickHouse, executable, HTTP.
Example of settings:
@ -226,7 +225,7 @@ Set a large enough cache size. You need to experiment to select the number of ce
### complex_key_cache
This type of storage is for use with composite [keys](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure). Similar to `cache`.
This type of storage is for use with composite [keys](external_dicts_dict_structure.md). Similar to `cache`.
<a name="dicts-external_dicts_dict_layout-ip_trie"></a>

View File

@ -33,7 +33,7 @@ Example of settings:
</dictionary>
```
When upgrading the dictionaries, the ClickHouse server applies different logic depending on the type of [ source](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources):
When upgrading the dictionaries, the ClickHouse server applies different logic depending on the type of [ source](external_dicts_dict_sources.md):
- For a text file, it checks the time of modification. If the time differs from the previously recorded time, the dictionary is updated.
- For MyISAM tables, the time of modification is checked using a `SHOW TABLE STATUS` query.
@ -42,7 +42,7 @@ When upgrading the dictionaries, the ClickHouse server applies different logic d
For MySQL (InnoDB), ODBC and ClickHouse sources, you can set up a query that will update the dictionaries only if they really changed, rather than each time. To do this, follow these steps:
- The dictionary table must have a field that always changes when the source data is updated.
- The settings of the source must specify a query that retrieves the changing field. The ClickHouse server interprets the query result as a row, and if this row has changed relative to its previous state, the dictionary is updated. Specify the query in the `<invalidate_query>` field in the settings for the [source](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources).
- The settings of the source must specify a query that retrieves the changing field. The ClickHouse server interprets the query result as a row, and if this row has changed relative to its previous state, the dictionary is updated. Specify the query in the `<invalidate_query>` field in the settings for the [source](external_dicts_dict_sources.md).
Example of settings:

View File

@ -25,14 +25,14 @@ The source is configured in the `source` section.
Types of sources (`source_type`):
- [Local file](#dicts-external_dicts_dict_sources-local_file)
- [Executable file](#dicts-external_dicts_dict_sources-executable)
- [HTTP(s)](#dicts-external_dicts_dict_sources-http)
- [Local file]()
- [Executable file]()
- [HTTP(s)]()
- DBMS
- [MySQL](#dicts-external_dicts_dict_sources-mysql)
- [ClickHouse](#dicts-external_dicts_dict_sources-clickhouse)
- [MongoDB](#dicts-external_dicts_dict_sources-mongodb)
- [ODBC](#dicts-external_dicts_dict_sources-odbc)
- [MySQL]()
- [ClickHouse]()
- [MongoDB]()
- [ODBC]()
<a name="dicts-external_dicts_dict_sources-local_file"></a>
@ -58,7 +58,7 @@ Setting fields:
## Executable File
Working with executable files depends on [how the dictionary is stored in memory](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout). If the dictionary is stored using `cache` and `complex_key_cache`, ClickHouse requests the necessary keys by sending a request to the executable file's `STDIN`.
Working with executable files depends on [how the dictionary is stored in memory](external_dicts_dict_layout.md). If the dictionary is stored using `cache` and `complex_key_cache`, ClickHouse requests the necessary keys by sending a request to the executable file's `STDIN`.
Example of settings:
@ -80,7 +80,7 @@ Setting fields:
## HTTP(s)
Working with an HTTP(s) server depends on [how the dictionary is stored in memory](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout). If the dictionary is stored using `cache` and `complex_key_cache`, ClickHouse requests the necessary keys by sending a request via the `POST` method.
Working with an HTTP(s) server depends on [how the dictionary is stored in memory](external_dicts_dict_layout.md). If the dictionary is stored using `cache` and `complex_key_cache`, ClickHouse requests the necessary keys by sending a request via the `POST` method.
Example of settings:
@ -93,7 +93,7 @@ Example of settings:
</source>
```
In order for ClickHouse to access an HTTPS resource, you must [configure openSSL](../../operations/server_settings/settings.md#server_settings-openSSL) in the server configuration.
In order for ClickHouse to access an HTTPS resource, you must [configure openSSL](../../operations/server_settings/settings.md) in the server configuration.
Setting fields:
@ -122,7 +122,7 @@ Setting fields:
- `db` Name of the database. Omit it if the database name is set in the `<connection_string>` parameters.
- `table` Name of the table and schema if exists.
- `connection_string` Connection string.
- `invalidate_query` Query for checking the dictionary status. Optional parameter. Read more in the section [Updating dictionaries](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime).
- `invalidate_query` Query for checking the dictionary status. Optional parameter. Read more in the section [Updating dictionaries](external_dicts_dict_lifetime.md).
ClickHouse receives quoting symbols from ODBC-driver and quote all settings in queries to driver, so it's necessary to set table name accordingly to table name case in database.
@ -350,7 +350,7 @@ Setting fields:
- `where ` The selection criteria. Optional parameter.
- `invalidate_query` Query for checking the dictionary status. Optional parameter. Read more in the section [Updating dictionaries](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime).
- `invalidate_query` Query for checking the dictionary status. Optional parameter. Read more in the section [Updating dictionaries](external_dicts_dict_lifetime.md).
MySQL can be connected on a local host via sockets. To do this, set `host` and `socket`.
@ -393,14 +393,14 @@ Example of settings:
Setting fields:
- `host` The ClickHouse host. If it is a local host, the query is processed without any network activity. To improve fault tolerance, you can create a [Distributed](../../operations/table_engines/distributed.md#table_engines-distributed) table and enter it in subsequent configurations.
- `host` The ClickHouse host. If it is a local host, the query is processed without any network activity. To improve fault tolerance, you can create a [Distributed](../../operations/table_engines/distributed.md) table and enter it in subsequent configurations.
- `port` The port on the ClickHouse server.
- `user` Name of the ClickHouse user.
- `password` Password of the ClickHouse user.
- `db` Name of the database.
- `table` Name of the table.
- `where ` The selection criteria. May be omitted.
- `invalidate_query` Query for checking the dictionary status. Optional parameter. Read more in the section [Updating dictionaries](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime).
- `invalidate_query` Query for checking the dictionary status. Optional parameter. Read more in the section [Updating dictionaries](external_dicts_dict_lifetime.md).
<a name="dicts-external_dicts_dict_sources-mongodb"></a>

View File

@ -25,8 +25,8 @@ Overall structure:
Columns are described in the structure:
- `<id>` - [key column](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-key).
- `<attribute>` - [data column](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-attributes). There can be a large number of columns.
- `<id>` - [key column](external_dicts_dict_structure.md).
- `<attribute>` - [data column](external_dicts_dict_structure.md). There can be a large number of columns.
<a name="dicts-external_dicts_dict_structure-key"></a>
@ -60,12 +60,12 @@ Configuration fields:
### Composite Key
The key can be a `tuple` from any types of fields. The [layout](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout) in this case must be `complex_key_hashed` or `complex_key_cache`.
The key can be a `tuple` from any types of fields. The [layout](external_dicts_dict_layout.md) in this case must be `complex_key_hashed` or `complex_key_cache`.
!!! tip
A composite key can consist of a single element. This makes it possible to use a string as the key, for instance.
The key structure is set in the element `<key>`. Key fields are specified in the same format as the dictionary [attributes](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-attributes). Example:
The key structure is set in the element `<key>`. Key fields are specified in the same format as the dictionary [attributes](external_dicts_dict_structure.md). Example:
```xml
<structure>

View File

@ -4,12 +4,12 @@ A dictionary is a mapping (`key -> attributes`) that is convenient for various t
ClickHouse supports special functions for working with dictionaries that can be used in queries. It is easier and more efficient to use dictionaries with functions than a `JOIN` with reference tables.
[NULL](../syntax.md#null-literal) values can't be stored in a dictionary.
[NULL](../syntax.md) values can't be stored in a dictionary.
ClickHouse supports:
- [Built-in dictionaries](internal_dicts.md#internal_dicts) with a specific [set of functions](../functions/ym_dict_functions.md#ym_dict_functions).
- [Plug-in (external) dictionaries](external_dicts.md#dicts-external_dicts) with a [set of functions](../functions/ext_dict_functions.md#ext_dict_functions).
- [Plug-in (external) dictionaries](external_dicts.md) with a [set of functions](../functions/ext_dict_functions.md#ext_dict_functions).
[Original article](https://clickhouse.yandex/docs/en/query_language/dicts/) <!--hide-->

View File

@ -55,8 +55,7 @@ arrayConcat(arrays)
**Parameters**
- `arrays` Arbitrary number of arguments of [Array][../../data_types/array.md#data_type-array] type.
- `arrays` Arbitrary number of arguments of [Array][../../data_types/array.md
**Example**
``` sql

View File

@ -2,7 +2,7 @@
# Functions for working with external dictionaries
For information on connecting and configuring external dictionaries, see "[External dictionaries](../dicts/external_dicts.md#dicts-external_dicts)".
For information on connecting and configuring external dictionaries, see "[External dictionaries](../dicts/external_dicts.md)".
## dictGetUInt8, dictGetUInt16, dictGetUInt32, dictGetUInt64

View File

@ -2,7 +2,7 @@
## isNull
Checks whether the argument is [NULL](../syntax.md#null-literal).
Checks whether the argument is [NULL](../syntax.md).
```
isNull(x)
@ -46,7 +46,7 @@ WHERE isNull(y)
## isNotNull
Checks whether the argument is [NULL](../syntax.md#null-literal).
Checks whether the argument is [NULL](../syntax.md).
```
isNotNull(x)
@ -207,8 +207,7 @@ SELECT nullIf(1, 2)
## assumeNotNull
Results in a value of type [Nullable](../../data_types/nullable.md#data_type-nullable) for a non- `Nullable`, if the value is not `NULL`.
Results in a value of type [Nullable](../../data_types/nullable.md
```
assumeNotNull(x)
```

View File

@ -77,8 +77,8 @@ pointInPolygon((x, y), [(a, b), (c, d) ...], ...)
**Input values**
- `(x, y)` — Coordinates of a point on the plane. Data type — [Tuple](../../data_types/tuple.md#data_type-tuple) — A tuple of two numbers.
- `[(a, b), (c, d) ...]` — Polygon vertices. Data type — [Array](../../data_types/array.md#data_type-array). Each vertex is represented by a pair of coordinates `(a, b)`. Vertices should be specified in a clockwise or counterclockwise order. The minimum number of vertices is 3. The polygon must be constant.
- `(x, y)` — Coordinates of a point on the plane. Data type — [Tuple](../../data_types/tuple.md) — A tuple of two numbers.
- `[(a, b), (c, d) ...]` — Polygon vertices. Data type — [Array](../../data_types/array.md). Each vertex is represented by a pair of coordinates `(a, b)`. Vertices should be specified in a clockwise or counterclockwise order. The minimum number of vertices is 3. The polygon must be constant.
- The function also supports polygons with holes (cut out sections). In this case, add polygons that define the cut out sections using additional arguments of the function. The function does not support non-simply-connected polygons.
**Returned values**

View File

@ -2,7 +2,7 @@
## in, notIn, globalIn, globalNotIn
See the section [IN operators](../select.md/#query_language-in_operators).
See the section [IN operators](../select.md/).
## tuple(x, y, ...), operator (x, y, ...)

View File

@ -298,7 +298,7 @@ Accepts a MAC address in the format AA:BB:CC:DD:EE:FF (colon-separated numbers i
## getSizeOfEnumType
Returns the number of fields in [Enum](../../data_types/enum.md#data_type-enum).
Returns the number of fields in [Enum](../../data_types/enum.md).
```
getSizeOfEnumType(value)
@ -407,7 +407,7 @@ defaultValueOfArgumentType(expression)
- `0` for numbers.
- Empty string for strings.
- `ᴺᵁᴸᴸ` for [Nullable](../../data_types/nullable.md#data_type-nullable).
- `ᴺᵁᴸᴸ` for [Nullable](../../data_types/nullable.md).
**Example**
@ -445,7 +445,7 @@ The expression passed to the function is not calculated, but ClickHouse applies
**Example**
Here is a table with the test data for [ontime](../../getting_started/example_datasets/ontime.md#example_datasets-ontime).
Here is a table with the test data for [ontime](../../getting_started/example_datasets/ontime.md).
```
SELECT count() FROM ontime

View File

@ -14,7 +14,7 @@
## toDecimal32(value, S), toDecimal64(value, S), toDecimal128(value, S)
Converts `value` to [Decimal](../../data_types/decimal.md#data_type-decimal) of precision `S`. The `value` can be a number or a string. The `S` (scale) parameter specifies the number of decimal places.
Converts `value` to [Decimal](../../data_types/decimal.md) of precision `S`. The `value` can be a number or a string. The `S` (scale) parameter specifies the number of decimal places.
## toString
@ -125,7 +125,7 @@ SELECT
Conversion to FixedString(N) only works for arguments of type String or FixedString(N).
Type conversion to [Nullable](../../data_types/nullable.md#data_type-nullable) and back is supported. Example:
Type conversion to [Nullable](../../data_types/nullable.md) and back is supported. Example:
```
SELECT toTypeName(x) FROM t_null

View File

@ -1,10 +1,10 @@
# SQL Reference
* [SELECT](select.md#select)
* [INSERT INTO](insert_into.md#queries-insert)
* [CREATE](create.md#create-database)
* [INSERT INTO](insert_into.md)
* [CREATE](create.md)
* [ALTER](alter.md#query_language_queries_alter)
* [Other types of queries](misc.md#miscellanous-queries)
* [Other types of queries](misc.md)
[Original article](https://clickhouse.yandex/docs/en/query_language/) <!--hide-->

View File

@ -15,7 +15,7 @@ The query can specify a list of columns to insert `[(c1, c2, c3)]`. In this case
- The values calculated from the `DEFAULT` expressions specified in the table definition.
- Zeros and empty strings, if `DEFAULT` expressions are not defined.
If [strict_insert_defaults=1](../operations/settings/settings.md#settings-strict_insert_defaults), columns that do not have `DEFAULT` defined must be listed in the query.
If [strict_insert_defaults=1](../operations/settings/settings.md), columns that do not have `DEFAULT` defined must be listed in the query.
Data can be passed to the INSERT in any [format](../interfaces/formats.md#formats) supported by ClickHouse. The format must be specified explicitly in the query:

View File

@ -213,7 +213,7 @@ TRUNCATE TABLE [IF EXISTS] [db.]name [ON CLUSTER cluster]
Removes all data from a table. When the clause `IF EXISTS` is omitted, the query returns an error if the table does not exist.
The `TRUNCATE` query is not supported for [View](../operations/table_engines/view.md#table_engines-view), [File](../operations/table_engines/file.md#table_engines-file), [URL](../operations/table_engines/url.md#table_engines-url) and [Null](../operations/table_engines/null.md#table_engines-null) table engines.
The `TRUNCATE` query is not supported for [View](../operations/table_engines/view.md#table_engines-view), [File](../operations/table_engines/file.md#table_engines-file), [URL](../operations/table_engines/url.md#table_engines-url) and [Null](../operations/table_engines/null.md) table engines.
## USE

View File

@ -53,7 +53,7 @@ Groups of operators are listed in order of priority (the higher it is in the lis
## Operators for Working With Data Sets
*See the section [IN operators](select.md/#query_language-in_operators).*
*See the section [IN operators](select.md/).*
`a IN ...` The `in(a, b) function`
@ -134,7 +134,7 @@ ClickHouse supports the `IS NULL` and `IS NOT NULL` operators.
### IS NULL
- For [Nullable](../data_types/nullable.md#data_type-nullable) type values, the `IS NULL` operator returns:
- For [Nullable](../data_types/nullable.md) type values, the `IS NULL` operator returns:
- `1`, if the value is `NULL`.
- `0` otherwise.
- For other values, the `IS NULL` operator always returns `0`.
@ -157,7 +157,7 @@ WHERE isNull(y)
### IS NOT NULL
- For [Nullable](../data_types/nullable.md#data_type-nullable) type values, the `IS NOT NULL` operator returns:
- For [Nullable](../data_types/nullable.md) type values, the `IS NOT NULL` operator returns:
- `0`, if the value is `NULL`.
- `1` otherwise.
- For other values, the `IS NOT NULL` operator always returns `1`.

View File

@ -341,7 +341,7 @@ The corresponding conversion can be performed before the WHERE/PREWHERE clause (
Joins the data in the usual [SQL JOIN](https://en.wikipedia.org/wiki/Join_(SQL)) sense.
!!! info "Note"
Not related to [ARRAY JOIN](#select-array-join).
Not related to [ARRAY JOIN]().
``` sql
@ -351,7 +351,7 @@ FROM <left_subquery>
(ON <expr_list>)|(USING <column_list>) ...
```
The table names can be specified instead of `<left_subquery>` and `<right_subquery>`. This is equivalent to the `SELECT * FROM table` subquery, except in a special case when the table has the [Join](../operations/table_engines/join.md#table-engine-join) engine an array prepared for joining.
The table names can be specified instead of `<left_subquery>` and `<right_subquery>`. This is equivalent to the `SELECT * FROM table` subquery, except in a special case when the table has the [Join](../operations/table_engines/join.md) engine an array prepared for joining.
**Supported types of `JOIN`**
@ -368,7 +368,7 @@ You may skip the `OUTER` keyword it is implied by default.
If `ALL` is specified and the right table has several matching rows, the data will be multiplied by the number of these rows. It is a normal `JOIN` behavior from standard SQL.
If `ANY` is specified and the right table has several matching rows, only the first one found is joined. If the right table has only one matching row, the results of `ANY` and `ALL` are the same.
You can set the default value of strictness with session configuration parameter [join_default_strictness](../operations/settings/settings.md#session-setting-join_default_strictness).
You can set the default value of strictness with session configuration parameter [join_default_strictness](../operations/settings/settings.md).
**`GLOBAL` distribution**
@ -376,7 +376,7 @@ When using a normal `JOIN`, the query is sent to remote servers. Subqueries are
When using `GLOBAL ... JOIN`, first the requestor server runs a subquery to calculate the right table. This temporary table is passed to each remote server, and queries are run on them using the temporary data that was transmitted.
Be careful when using `GLOBAL`. For more information, see the section [Distributed subqueries](#queries-distributed-subqueries).
Be careful when using `GLOBAL`. For more information, see the section [Distributed subqueries]().
**Usage Recommendations**
@ -439,13 +439,13 @@ Each time a query is run with the same `JOIN`, the subquery is run again the
In some cases, it is more efficient to use `IN` instead of `JOIN`.
Among the various types of `JOIN`, the most efficient is `ANY LEFT JOIN`, then `ANY INNER JOIN`. The least efficient are `ALL LEFT JOIN` and `ALL INNER JOIN`.
If you need a `JOIN` for joining with dimension tables (these are relatively small tables that contain dimension properties, such as names for advertising campaigns), a `JOIN` might not be very convenient due to the bulky syntax and the fact that the right table is re-accessed for every query. For such cases, there is an "external dictionaries" feature that you should use instead of `JOIN`. For more information, see the section [External dictionaries](dicts/external_dicts.md#dicts-external_dicts).
If you need a `JOIN` for joining with dimension tables (these are relatively small tables that contain dimension properties, such as names for advertising campaigns), a `JOIN` might not be very convenient due to the bulky syntax and the fact that the right table is re-accessed for every query. For such cases, there is an "external dictionaries" feature that you should use instead of `JOIN`. For more information, see the section [External dictionaries](dicts/external_dicts.md).
#### NULL processing
The JOIN behavior is affected by the [join_use_nulls](../operations/settings/settings.md#settings-join_use_nulls) setting. With `join_use_nulls=1`, `JOIN` works like in standard SQL.
The JOIN behavior is affected by the [join_use_nulls](../operations/settings/settings.md) setting. With `join_use_nulls=1`, `JOIN` works like in standard SQL.
If the JOIN keys are [Nullable](../data_types/nullable.md#data_types-nullable) fields, the rows where at least one of the keys has the value [NULL](syntax.md#null-literal) are not joined.
If the JOIN keys are [Nullable](../data_types/nullable.md#data_types-nullable) fields, the rows where at least one of the keys has the value [NULL](syntax.md) are not joined.
<a name="query_language-queries-where"></a>
@ -515,7 +515,7 @@ A constant can't be specified as arguments for aggregate functions. Example: sum
#### NULL processing
For grouping, ClickHouse interprets [NULL](syntax.md#null-literal) as a value, and `NULL=NULL`.
For grouping, ClickHouse interprets [NULL](syntax.md) as a value, and `NULL=NULL`.
Here's an example to show what this means.
@ -698,7 +698,7 @@ The result will be the same as if GROUP BY were specified across all the fields
DISTINCT is not supported if SELECT has at least one array column.
`DISTINCT` works with [NULL](syntax.md#null-literal) as if `NULL` were a specific value, and `NULL=NULL`. In other words, in the `DISTINCT` results, different combinations with `NULL` only occur once.
`DISTINCT` works with [NULL](syntax.md) as if `NULL` were a specific value, and `NULL=NULL`. In other words, in the `DISTINCT` results, different combinations with `NULL` only occur once.
### LIMIT Clause
@ -819,7 +819,7 @@ A subquery in the IN clause is always run just one time on a single server. Ther
#### NULL processing
During request processing, the IN operator assumes that the result of an operation with [NULL](syntax.md#null-literal) is always equal to `0`, regardless of whether `NULL` is on the right or left side of the operator. `NULL` values are not included in any dataset, do not correspond to each other and cannot be compared.
During request processing, the IN operator assumes that the result of an operation with [NULL](syntax.md) is always equal to `0`, regardless of whether `NULL` is on the right or left side of the operator. `NULL` values are not included in any dataset, do not correspond to each other and cannot be compared.
Here is an example with the `t_null` table:
@ -857,7 +857,7 @@ FROM t_null
There are two options for IN-s with subqueries (similar to JOINs): normal `IN` / `JOIN` and `GLOBAL IN` / `GLOBAL JOIN`. They differ in how they are run for distributed query processing.
!!! attention
Remember that the algorithms described below may work differently depending on the [settings](../operations/settings/settings.md#settings-distributed_product_mode) `distributed_product_mode` setting.
Remember that the algorithms described below may work differently depending on the [settings](../operations/settings/settings.md) `distributed_product_mode` setting.
When using the regular IN, the query is sent to remote servers, and each of them runs the subqueries in the `IN` or `JOIN` clause.

View File

@ -78,13 +78,13 @@ Tuples have a special purpose for use in the IN clause of a SELECT query. Tuples
Indicates that the value is missing.
In order to store `NULL` in a table field, it must be of the [Nullable](../data_types/nullable.md#data_type-nullable) type.
In order to store `NULL` in a table field, it must be of the [Nullable](../data_types/nullable.md) type.
Depending on the data format (input or output), `NULL` may have a different representation. For more information, see the documentation for [data formats](../interfaces/formats.md#formats).
There are many nuances to processing `NULL`. For example, if at least one of the arguments of a comparison operation is `NULL`, the result of this operation will also be `NULL`. The same is true for multiplication, addition, and other operations. For more information, read the documentation for each operation.
In queries, you can check `NULL` using the [IS NULL](operators.md#operator-is-null) and [IS NOT NULL](operators.md#operator-is-not-null) operators and the related functions `isNull` and `isNotNull`.
In queries, you can check `NULL` using the [IS NULL](operators.md#operator-is-null) and [IS NOT NULL](operators.md) operators and the related functions `isNull` and `isNotNull`.
## Functions
@ -113,13 +113,13 @@ expr AS alias
For example, `SELECT b.column_name from t b`.
In the [CAST function](functions/type_conversion_functions.md#type_conversion_function-cast), the `AS` keyword has another meaning. See the description of the function.
In the [CAST function](functions/type_conversion_functions.md), the `AS` keyword has another meaning. See the description of the function.
- `expr` — any expression supported by ClickHouse.
For example `SELECT column_name * 2 AS double FROM some_table`.
- `alias` — [string literal](#syntax-string_literal). If an alias contains spaces, enclose it in double quotes or backticks.
- `alias` — [string literal](). If an alias contains spaces, enclose it in double quotes or backticks.
For example, `SELECT "table t".col_name FROM t AS "table t"`.

View File

@ -49,7 +49,7 @@ example01-{01..02}-1
If you have multiple pairs of curly brackets, it generates the direct product of the corresponding sets.
Addresses and parts of addresses 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. However, the replicas are iterated in the order currently set in the [load_balancing](../../operations/settings/settings.md#settings-load_balancing) setting.
Addresses and parts of addresses 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. However, the replicas are iterated in the order currently set in the [load_balancing](../../operations/settings/settings.md) setting.
Example:

View File

@ -84,7 +84,7 @@ SELECT 0 / 0
<div dir="rtl" markdown="1">
قوانین مربوط به مرتب سازی ` Nan ` را در بخش [ORDER BY clause](../query_language/select.md#query_language-queries-order_by) ببینید.
قوانین مربوط به مرتب سازی ` Nan ` را در بخش [ORDER BY clause](../query_language/select.md) ببینید.
</div>
[مقاله اصلی](https://clickhouse.yandex/docs/fa/data_types/float/) <!--hide-->

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -578,7 +578,7 @@ struct Message {
<div dir="rtl" markdown="1">
فایل های Schema در فایلی قرار دارند که این فایل در دایرکتوری مشخص شده کانفیگ [ format_schema_path](../operations/server_settings/settings.md#server_settings-format_schema_path) قرار گرفته اند.
فایل های Schema در فایلی قرار دارند که این فایل در دایرکتوری مشخص شده کانفیگ [ format_schema_path](../operations/server_settings/settings.md) قرار گرفته اند.
عملیات Deserialization موثر است و معمولا لود سیستم را افزایش نمی دهد.

View File

@ -61,7 +61,7 @@ ClickHouse روش های مختلفی برای کسب دقیق performance ار
ClickHouse از روش asynchronous multimaster replication استفاده می کند. بعد از نوشتن داده در یکی از replica های موجود، داده به صورت توزیع شده به بقیه replica ها منتقل می شود. این سیستم داده های مشابه را در replica های مختلف نگه داری می کند. در اکثر موارد که سیستم fail می شوند، داده ها به صورت اتوماتیک restore می شوند و یا در موارد پیچیده به صورت نیمه اتوماتیک restore می شوند.
برای اطلاعات بیشتر، به بخش [replication داده ها](../operations/table_engines/replication.md#table_engines-replication) مراجعه کنید.
برای اطلاعات بیشتر، به بخش [replication داده ها](../operations/table_engines/replication.md) مراجعه کنید.
</div>
[مقاله اصلی](https://clickhouse.yandex/docs/fa/introduction/distinctive_features/) <!--hide-->

View File

@ -4,7 +4,7 @@
با توجه به نتایج تست های Yandex، ClickHouse بهترین عملکرد را برای سناریوهای عملیاتی قابل مقایسه با دیگر سیستم های در کلاس خود را از خود نشان داد. این تست ها شامل بالاترین توان عملیاتی برای query های طولانی، و کمترین latency برای query های کوتاه بود. نتایج این تست های در [صفحه ی جدا](https://clickhouse.yandex/benchmark.html) موجود است.
benchmark های زیادی وجود دارند که این نتایج را تایید می کنند. میتوانید این نتایج را جستجو کنید و یا [این لینک های benchmark](https://clickhouse.yandex/#independent-benchmarks). مستقل را ببینید.
benchmark های زیادی وجود دارند که این نتایج را تایید می کنند. میتوانید این نتایج را جستجو کنید و یا [این لینک های benchmark](https://clickhouse.yandex/). مستقل را ببینید.
## توان عملیاتی برای یک query بزرگ

View File

@ -49,7 +49,7 @@ SELECT
## Особенности работы с типами данных
При создании массива "на лету" ClickHouse автоматически определяет тип аргументов как наиболее узкий тип данных, в котором можно хранить все перечисленные аргументы. Если среди аргументов есть [NULL](../query_language/syntax.md#null-literal) или аргумент типа [Nullable](nullable.md#data_type-nullable), то тип элементов массива — [Nullable](nullable.md#data_type-nullable).
При создании массива "на лету" ClickHouse автоматически определяет тип аргументов как наиболее узкий тип данных, в котором можно хранить все перечисленные аргументы. Если среди аргументов есть [NULL](../query_language/syntax.md#null-literal) или аргумент типа [Nullable](nullable.md#data_type-nullable), то тип элементов массива — [Nullable](nullable.md).
Если ClickHouse не смог подобрать тип данных, то он сгенерирует исключение. Это произойдёт, например, при попытке создать массив одновременно со строками и числами `SELECT array(1, 'a')`.

View File

@ -76,9 +76,9 @@ SELECT toTypeName(CAST('a', 'Enum8(\'a\' = 1, \'b\' = 2)'))
Для каждого из значений прописывается число в диапазоне `-128 .. 127` для `Enum8` или в диапазоне `-32768 .. 32767` для `Enum16`. Все строки должны быть разными, числа - тоже. Разрешена пустая строка. При указании такого типа (в определении таблицы), числа могут идти не подряд и в произвольном порядке. При этом, порядок не имеет значения.
Ни строка, ни цифровое значение в `Enum` не могут быть [NULL](../query_language/syntax.md#null-literal).
Ни строка, ни цифровое значение в `Enum` не могут быть [NULL](../query_language/syntax.md).
`Enum` может быть передан в тип [Nullable](nullable.md#data_type-nullable). Таким образом, если создать таблицу запросом
`Enum` может быть передан в тип [Nullable](nullable.md). Таким образом, если создать таблицу запросом
```
CREATE TABLE t_enum_nullable

View File

@ -65,6 +65,6 @@ SELECT 0 / 0
└──────────────┘
```
Смотрите правила сортировки `NaN` в разделе [Секция ORDER BY](../query_language/select.md#query_language-queries-order_by).
Смотрите правила сортировки `NaN` в разделе [Секция ORDER BY](../query_language/select.md).
[Оригинальная статья](https://clickhouse.yandex/docs/ru/data_types/float/) <!--hide-->

View File

@ -25,7 +25,7 @@ CREATE TABLE t
) ENGINE = ...
```
[uniq](../../query_language/agg_functions/reference.md#agg_function-uniq), anyIf ([any](../../query_language/agg_functions/reference.md#agg_function-any)+[If](../../query_language/agg_functions/combinators.md#agg-functions-combinator-if)) и [quantiles](../../query_language/agg_functions/reference.md#agg_function-quantiles) — агрегатные функции, поддержанные в ClickHouse.
[uniq](../../query_language/agg_functions/reference.md#agg_function-uniq), anyIf ([any](../../query_language/agg_functions/reference.md#agg_function-any)+[If](../../query_language/agg_functions/combinators.md#agg-functions-combinator-if)) и [quantiles](../../query_language/agg_functions/reference.md) — агрегатные функции, поддержанные в ClickHouse.
## Особенности использования
@ -60,6 +60,6 @@ SELECT uniqMerge(state) FROM (SELECT uniqState(UserID) AS state FROM table GROUP
## Пример использования
Смотрите в описании движка [AggregatingMergeTree](../../operations/table_engines/aggregatingmergetree.md#table_engine-aggregatingmergetree).
Смотрите в описании движка [AggregatingMergeTree](../../operations/table_engines/aggregatingmergetree.md).
[Оригинальная статья](https://clickhouse.yandex/docs/ru/data_types/nested_data_structures/aggregatefunction/) <!--hide-->

View File

@ -2,9 +2,9 @@
# Nullable(TypeName)
Позволяет работать как со значением типа `TypeName` так и с отсутствием этого значения ([NULL](../query_language/syntax.md#null-literal)) в одной и той же переменной, в том числе хранить `NULL` в таблицах вместе со значения типа `TypeName`. Например, в столбце типа `Nullable(Int8)` можно хранить значения типа `Int8`, а в тех строках, где значения нет, будет храниться `NULL`.
Позволяет работать как со значением типа `TypeName` так и с отсутствием этого значения ([NULL](../query_language/syntax.md)) в одной и той же переменной, в том числе хранить `NULL` в таблицах вместе со значения типа `TypeName`. Например, в столбце типа `Nullable(Int8)` можно хранить значения типа `Int8`, а в тех строках, где значения нет, будет храниться `NULL`.
В качестве `TypeName` нельзя использовать составные типы данных [Array](array.md#data_type-array) и [Tuple](tuple.md#data_type-tuple). Составные типы данных могут содержать значения типа `Nullable`, например `Array(Nullable(Int8))`.
В качестве `TypeName` нельзя использовать составные типы данных [Array](array.md#data_type-array) и [Tuple](tuple.md). Составные типы данных могут содержать значения типа `Nullable`, например `Array(Nullable(Int8))`.
Поле типа `Nullable` нельзя включать в индексы.

View File

@ -2,9 +2,9 @@
# Nothing
Этот тип данных предназначен только для того, чтобы представлять [NULL](../../query_language/syntax.md#null-literal), т.е. отсутствие значения.
Этот тип данных предназначен только для того, чтобы представлять [NULL](../../query_language/syntax.md), т.е. отсутствие значения.
Невозможно создать значение типа `Nothing`, поэтому он используется там, где значение не подразумевается. Например, `NULL` записывается как `Nullable(Nothing)` ([Nullable](../../data_types/nullable.md#data_type-nullable) — это тип данных, позволяющий хранить `NULL` в таблицах). Также тип `Nothing` используется для обозначения пустых массивов:
Невозможно создать значение типа `Nothing`, поэтому он используется там, где значение не подразумевается. Например, `NULL` записывается как `Nullable(Nothing)` ([Nullable](../../data_types/nullable.md) — это тип данных, позволяющий хранить `NULL` в таблицах). Также тип `Nothing` используется для обозначения пустых массивов:
```bash
:) SELECT toTypeName(Array())

View File

@ -4,7 +4,7 @@
Кортеж из элементов любого [типа](index.md#data_types). Элементы кортежа могут быть одного или разных типов.
Кортежи нельзя хранить в таблицах (кроме таблиц типа Memory). Они используется для временной группировки столбцов. Столбцы могут группироваться при использовании выражения IN в запросе, а также для указания нескольких формальных параметров лямбда-функций. Подробнее смотрите разделы [Операторы IN](../query_language/select.md#query_language-in_operators), [Функции высшего порядка](../query_language/functions/higher_order_functions.md#higher_order_functions).
Кортежи нельзя хранить в таблицах (кроме таблиц типа Memory). Они используется для временной группировки столбцов. Столбцы могут группироваться при использовании выражения IN в запросе, а также для указания нескольких формальных параметров лямбда-функций. Подробнее смотрите разделы [Операторы IN](../query_language/select.md), [Функции высшего порядка](../query_language/functions/higher_order_functions.md#higher_order_functions).
Кортежи могут быть результатом запроса. В этом случае, в текстовых форматах кроме JSON, значения выводятся в круглых скобках через запятую. В форматах JSON, кортежи выводятся в виде массивов (в квадратных скобках).
@ -34,7 +34,7 @@ SELECT
## Особенности работы с типами данных
При создании кортежа "на лету" ClickHouse автоматически определяет тип каждого аргументов как минимальный из типов, который может сохранить значение аргумента. Если аргумент — [NULL](../query_language/syntax.md#null-literal), то тип элемента кортежа — [Nullable](nullable.md#data_type-nullable).
При создании кортежа "на лету" ClickHouse автоматически определяет тип каждого аргументов как минимальный из типов, который может сохранить значение аргумента. Если аргумент — [NULL](../query_language/syntax.md#null-literal), то тип элемента кортежа — [Nullable](nullable.md).
Пример автоматического определения типа данных:

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@ -95,7 +95,7 @@ world
Массивы форматируются в виде списка значений через запятую в квадратных скобках. Элементы массива - числа форматируются как обычно, а даты, даты-с-временем и строки - в одинарных кавычках с такими же правилами экранирования, как указано выше.
[NULL](../query_language/syntax.md#null-literal) форматируется в виде `\N`.
[NULL](../query_language/syntax.md) форматируется в виде `\N`.
<a name="tabseparatedraw"></a>
@ -141,7 +141,7 @@ SearchPhrase=дизайн штор count()=1064
SearchPhrase=баку count()=1000
```
[NULL](../query_language/syntax.md#null-literal) форматируется в виде `\N`.
[NULL](../query_language/syntax.md) форматируется в виде `\N`.
``` sql
SELECT * FROM t_null FORMAT TSKV
@ -266,7 +266,7 @@ JSON совместим с JavaScript. Для этого, дополнитель
Этот формат подходит только для вывода результата выполнения запроса, но не для парсинга (приёма данных для вставки в таблицу).
ClickHouse поддерживает [NULL](../query_language/syntax.md#null-literal), который при выводе JSON будет отображен как `null`.
ClickHouse поддерживает [NULL](../query_language/syntax.md), который при выводе JSON будет отображен как `null`.
Смотрите также формат JSONEachRow.
@ -360,7 +360,7 @@ ClickHouse поддерживает [NULL](../query_language/syntax.md#null-lite
Рисуется полная сетка таблицы и, таким образом, каждая строчка занимает две строки в терминале.
Каждый блок результата выводится в виде отдельной таблицы. Это нужно, чтобы можно было выводить блоки без буферизации результата (буферизация потребовалась бы, чтобы заранее вычислить видимую ширину всех значений.)
[NULL](../query_language/syntax.md#null-literal) выводится как `ᴺᵁᴸᴸ`.
[NULL](../query_language/syntax.md) выводится как `ᴺᵁᴸᴸ`.
``` sql
SELECT * FROM t_null
@ -455,11 +455,10 @@ FixedString представлены просто как последовате
Array представлены как длина в формате varint (unsigned [LEB128](https://en.wikipedia.org/wiki/LEB128)), а затем элементы массива, подряд.
Для поддержки [NULL](../query_language/syntax.md#null-literal) перед каждым значением типа [Nullable](../data_types/nullable.md#data_type-nullable) в строке добавлен дополнительный байт, который содержит 1 или 0. Если 1, то значение — `NULL` и этот байт трактуется как отдельное значение. Если 0, то после байта идёт не `NULL`-значение.
Для поддержки [NULL](../query_language/syntax.md#null-literal) перед каждым значением типа [Nullable](../data_types/nullable.md
## Values
Выводит каждую строку в скобках. Строки разделены запятыми. После последней строки запятой нет. Значения внутри скобок также разделены запятыми. Числа выводятся в десятичном виде без кавычек. Массивы выводятся в квадратных скобках. Строки, даты, даты-с-временем выводятся в кавычках. Правила экранирования и особенности парсинга аналогичны формату [TabSeparated](#tabseparated). При форматировании, лишние пробелы не ставятся, а при парсинге - допустимы и пропускаются (за исключением пробелов внутри значений типа массив, которые недопустимы). [NULL](../query_language/syntax.md#null-literal) представляется как `NULL`.
Выводит каждую строку в скобках. Строки разделены запятыми. После последней строки запятой нет. Значения внутри скобок также разделены запятыми. Числа выводятся в десятичном виде без кавычек. Массивы выводятся в квадратных скобках. Строки, даты, даты-с-временем выводятся в кавычках. Правила экранирования и особенности парсинга аналогичны формату [TabSeparated](#tabseparated). При форматировании, лишние пробелы не ставятся, а при парсинге - допустимы и пропускаются (за исключением пробелов внутри значений типа массив, которые недопустимы). [NULL](../query_language/syntax.md) представляется как `NULL`.
Минимальный набор символов, которых вам необходимо экранировать при передаче в Values формате: одинарная кавычка и обратный слеш.
@ -471,7 +470,7 @@ Array представлены как длина в формате varint (unsig
Выводит каждое значение на отдельной строке, с указанием имени столбца. Формат удобно использовать для вывода одной-нескольких строк, если каждая строка состоит из большого количества столбцов.
[NULL](../query_language/syntax.md#null-literal) выводится как `ᴺᵁᴸᴸ`.
[NULL](../query_language/syntax.md) выводится как `ᴺᵁᴸᴸ`.
Пример:
@ -614,7 +613,7 @@ struct Message {
```
Файлы со схемами находятся в файле, который находится в каталоге указанном в параметре [format_schema_path](../operations/server_settings/settings.md#server_settings-format_schema_path) конфигурации сервера.
Файлы со схемами находятся в файле, который находится в каталоге указанном в параметре [format_schema_path](../operations/server_settings/settings.md) конфигурации сервера.
Десериализация эффективна и обычно не повышает нагрузку на систему.

View File

@ -57,8 +57,8 @@ ClickHouse предоставляет различные способы разм
## Репликация данных и поддержка целостности
Используется асинхронная multimaster репликация. После записи на любую доступную реплику, данные распространяются на все остальные реплики в фоне. Система поддерживает полную идентичность данных на разных репликах. Восстановление после большинства сбоев осуществляется автоматически, а в сложных случаях — полуавтоматически. При необходимости, можно [включить кворумную запись](../operations/settings/settings.md#setting-insert_quorum) данных.
Используется асинхронная multimaster репликация. После записи на любую доступную реплику, данные распространяются на все остальные реплики в фоне. Система поддерживает полную идентичность данных на разных репликах. Восстановление после большинства сбоев осуществляется автоматически, а в сложных случаях — полуавтоматически. При необходимости, можно [включить кворумную запись](../operations/settings/settings.md) данных.
Подробнее смотрите раздел [Репликация данных](../operations/table_engines/replication.md#table_engines-replication).
Подробнее смотрите раздел [Репликация данных](../operations/table_engines/replication.md).
[Оригинальная статья](https://clickhouse.yandex/docs/ru/introduction/distinctive_features/) <!--hide-->

View File

@ -2,7 +2,7 @@
По результатам внутреннего тестирования в Яндексе, ClickHouse обладает наиболее высокой производительностью (как наиболее высокой пропускной способностью на длинных запросах, так и наиболее низкой задержкой на коротких запросах), при соответствующем сценарии работы, среди доступных для тестирования систем подобного класса. Результаты тестирования можно посмотреть на [отдельной странице](https://clickhouse.yandex/benchmark.html).
Также это подтверждают многочисленные независимые бенчмарки. Их не сложно найти в Интернете самостоятельно, либо можно воспользоваться [небольшой коллекцией ссылок по теме](https://clickhouse.yandex/#independent-benchmarks).
Также это подтверждают многочисленные независимые бенчмарки. Их не сложно найти в Интернете самостоятельно, либо можно воспользоваться [небольшой коллекцией ссылок по теме](https://clickhouse.yandex/).
## Пропускная способность при обработке одного большого запроса

View File

@ -61,7 +61,7 @@
Здесь видно объявление двух пользователей - `default` и `web`. Пользователя `web` мы добавили самостоятельно.
Пользователь `default` выбирается в случаях, когда имя пользователя не передаётся. Также пользователь `default` может использоваться при распределённой обработке запроса - если в конфигурации кластера для сервера не указаны `user` и `password`. (см. раздел о движке [Distributed](../operations/table_engines/distributed.md#table_engines-distributed)).
Пользователь `default` выбирается в случаях, когда имя пользователя не передаётся. Также пользователь `default` может использоваться при распределённой обработке запроса - если в конфигурации кластера для сервера не указаны `user` и `password`. (см. раздел о движке [Distributed](../operations/table_engines/distributed.md)).
Пользователь, который используется для обмена информацией между серверами, объединенными в кластер, не должен иметь существенных ограничений или квот - иначе распределённые запросы сломаются.
@ -87,8 +87,7 @@
Для продакшен использования, указывайте только элементы вида `ip` (IP-адреса и их маски), так как использование `host` и `host_regexp` может вызывать лишние задержки.
Далее указывается используемый профиль настроек пользователя (смотрите раздел "[Профили настроек](settings/settings_profiles.md#settings_profiles)"). Вы можете указать профиль по умолчанию - `default`. Профиль может называться как угодно; один и тот же профиль может быть указан для разных пользователей. Наиболее важная вещь, которую вы можете прописать в профиле настроек `readonly=1`, что обеспечивает доступ только на чтение.
Далее указывается используемый профиль настроек пользователя (смотрите раздел "[Профили настроек](settings/settings_profiles.md
Затем указывается используемая квота (смотрите раздел "[Квоты](quotas.md#quotas)"). Вы можете указать квоту по умолчанию — `default`. Она настроена в конфиге по умолчанию так, что только считает использование ресурсов, но никак их не ограничивает. Квота может называться как угодно. Одна и та же квота может быть указана для разных пользователей, в этом случае подсчёт использования ресурсов делается для каждого пользователя по отдельности.
Также, в необязательном разделе `<allow_databases>` можно указать перечень баз, к которым у пользователя будет доступ. По умолчанию пользователю доступны все базы. Можно указать базу данных `default`, в этом случае пользователь получит доступ к базе данных по умолчанию.

View File

@ -14,7 +14,7 @@
Если указано `remove` - удалить элемент.
Также в конфиге могут быть указаны "подстановки". Если у элемента присутствует атрибут `incl`, то в качестве значения будет использована соответствующая подстановка из файла. По умолчанию, путь к файлу с подстановками - `/etc/metrika.xml`. Он может быть изменён в конфигурации сервера в элементе [include_from](server_settings/settings.md#server_settings-include_from). Значения подстановок указываются в элементах `/yandex/имя_подстановки` этого файла. Если подстановка, заданная в `incl` отсутствует, то в лог попадает соответствующая запись. Чтобы ClickHouse не писал в лог об отсутствии подстановки, необходимо указать атрибут `optional="true"` (например, настройка [macros](server_settings/settings.md#server_settings-macros)).
Также в конфиге могут быть указаны "подстановки". Если у элемента присутствует атрибут `incl`, то в качестве значения будет использована соответствующая подстановка из файла. По умолчанию, путь к файлу с подстановками - `/etc/metrika.xml`. Он может быть изменён в конфигурации сервера в элементе [include_from](server_settings/settings.md#server_settings-include_from). Значения подстановок указываются в элементах `/yandex/имя_подстановки` этого файла. Если подстановка, заданная в `incl` отсутствует, то в лог попадает соответствующая запись. Чтобы ClickHouse не писал в лог об отсутствии подстановки, необходимо указать атрибут `optional="true"` (например, настройка [macros](server_settings/settings.md)).
Подстановки могут также выполняться из ZooKeeper. Для этого укажите у элемента атрибут `from_zk = "/path/to/node"`. Значение элемента заменится на содержимое узла `/path/to/node` в ZooKeeper. В ZooKeeper-узел также можно положить целое XML-поддерево, оно будет целиком вставлено в исходный элемент.

View File

@ -78,7 +78,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
Профиль настроек по умолчанию.
Профили настроек находятся в файле, указанном в параметре [user_config](#server_settings-users_config).
Профили настроек находятся в файле, указанном в параметре [user_config]().
**Пример**
@ -97,7 +97,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
- Указывается абсолютным или относительно конфигурационного файла сервера.
- Может содержать wildcard-ы \* и ?.
Смотрите также "[Внешние словари](../../query_language/dicts/external_dicts.md#dicts-external_dicts)".
Смотрите также "[Внешние словари](../../query_language/dicts/external_dicts.md)".
**Пример**
@ -177,7 +177,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
Настройка прореживания данных для Graphite.
Подробнее читайте в разделе [GraphiteMergeTree](../../operations/table_engines/graphitemergetree.md#table_engines-graphitemergetree).
Подробнее читайте в разделе [GraphiteMergeTree](../../operations/table_engines/graphitemergetree.md).
**Пример**
@ -207,7 +207,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
Порт для обращений к серверу по протоколу HTTP(s).
Если указан `https_port`, то требуется конфигурирование [openSSL](#server_settings-openSSL).
Если указан `https_port`, то требуется конфигурирование [openSSL]().
Если указан `http_port`, то настройка openSSL игнорируется, даже если она задана.
@ -357,7 +357,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
Можно не указывать, если реплицируемых таблицы не используются.
Подробнее смотрите в разделе "[Создание реплицируемых таблиц](../../operations/table_engines/replication.md#table_engines-replication-creation_of_rep_tables)".
Подробнее смотрите в разделе "[Создание реплицируемых таблиц](../../operations/table_engines/replication.md)".
**Пример**
@ -369,7 +369,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
## mark_cache_size
Приблизительный размер (в байтах) кеша "засечек", используемых движками таблиц семейства [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree).
Приблизительный размер (в байтах) кеша "засечек", используемых движками таблиц семейства [MergeTree](../../operations/table_engines/mergetree.md).
Кеш общий для сервера, память выделяется по мере необходимости. Кеш не может быть меньше, чем 5368709120.
@ -425,7 +425,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
Ограничение на удаление таблиц.
Если размер таблицы семейства [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree) превышает `max_table_size_to_drop` (в байтах), то ее нельзя удалить запросом DROP.
Если размер таблицы семейства [MergeTree](../../operations/table_engines/mergetree.md) превышает `max_table_size_to_drop` (в байтах), то ее нельзя удалить запросом DROP.
Если таблицу все же необходимо удалить, не перезапуская при этом сервер ClickHouse, то необходимо создать файл `<clickhouse-path>/flags/force_drop_table` и выполнить запрос DROP.
@ -443,7 +443,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
## merge_tree
Тонкая настройка таблиц семейства [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree).
Тонкая настройка таблиц семейства [MergeTree](../../operations/table_engines/mergetree.md).
Подробнее смотрите в заголовочном файле MergeTreeSettings.h.
@ -520,7 +520,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
## part_log
Логгирование событий, связанных с данными типа [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree). Например, события добавления или мержа данных. Лог можно использовать для симуляции алгоритмов слияния, чтобы сравнивать их характеристики. Также, можно визуализировать процесс слияния.
Логгирование событий, связанных с данными типа [MergeTree](../../operations/table_engines/mergetree.md). Например, события добавления или мержа данных. Лог можно использовать для симуляции алгоритмов слияния, чтобы сравнивать их характеристики. Также, можно визуализировать процесс слияния.
Запросы логгируются не в отдельный файл, а в таблицу ClickHouse.
@ -541,7 +541,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
- database - Имя базы данных.
- table - Имя таблицы.
- partition_by - Устанавливает [произвольный ключ партиционирования](../../operations/table_engines/custom_partitioning_key.md#custom-partitioning-key).
- partition_by - Устанавливает [произвольный ключ партиционирования](../../operations/table_engines/custom_partitioning_key.md).
- flush_interval_milliseconds - Период сброса данных из буфера в памяти в таблицу.
@ -575,7 +575,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
## query_log
Настройка логгирования запросов, принятых с настройкой [log_queries=1](../settings/settings.md#settings_settings-log_queries).
Настройка логгирования запросов, принятых с настройкой [log_queries=1](../settings/settings.md).
Запросы логгируются не в отдельный файл, а в таблицу ClickHouse.
@ -583,7 +583,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
- database - Имя базы данных.
- table - Имя таблицы.
- partition_by - Устанавливает [произвольный ключ партиционирования](../../operations/table_engines/custom_partitioning_key.md#custom-partitioning-key).
- partition_by - Устанавливает [произвольный ключ партиционирования](../../operations/table_engines/custom_partitioning_key.md).
- flush_interval_milliseconds - Период сброса данных из буфера в памяти в таблицу.
Если таблица не существует, то ClickHouse создаст её. Если структура журнала запросов изменилась при обновлении сервера ClickHouse, то таблица со старой структурой переименовывается, а новая таблица создается автоматически.
@ -605,7 +605,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
Конфигурация кластеров, которые использует движок таблиц Distributed.
Пример настройки смотрите в разделе "[Движки таблиц/Distributed](../../operations/table_engines/distributed.md#table_engines-distributed)".
Пример настройки смотрите в разделе "[Движки таблиц/Distributed](../../operations/table_engines/distributed.md)".
**Пример**
@ -663,9 +663,9 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
## uncompressed_cache_size
Размер кеша (в байтах) для несжатых данных, используемых движками таблиц семейства [MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree).
Размер кеша (в байтах) для несжатых данных, используемых движками таблиц семейства [MergeTree](../../operations/table_engines/mergetree.md).
Кеш единый для сервера. Память выделяется по-требованию. Кеш используется в том случае, если включена опция [use_uncompressed_cache](../settings/settings.md#settings-use_uncompressed_cache).
Кеш единый для сервера. Память выделяется по-требованию. Кеш используется в том случае, если включена опция [use_uncompressed_cache](../settings/settings.md).
Несжатый кеш выгодно использовать для очень коротких запросов в отдельных случаях.
@ -677,7 +677,7 @@ ClickHouse проверит условия `min_part_size` и `min_part_size_rat
## user_files_path
Каталог с пользовательскими файлами. Используется в табличной функции [file()](../../query_language/table_functions/file.md#table_functions-file).
Каталог с пользовательскими файлами. Используется в табличной функции [file()](../../query_language/table_functions/file.md).
**Пример**
@ -712,7 +712,7 @@ ClickHouse использует ZooKeeper для хранения метадан
Параметр можно не указывать, если реплицированные таблицы не используются.
Подробно читайте в разделе "[Репликация](../../operations/table_engines/replication.md#table_engines-replication)".
Подробно читайте в разделе "[Репликация](../../operations/table_engines/replication.md)".
**Пример**

View File

@ -4,7 +4,7 @@
## distributed_product_mode
Изменяет поведение [распределенных подзапросов](../../query_language/select.md#queries-distributed-subrequests).
Изменяет поведение [распределенных подзапросов](../../query_language/select.md).
ClickHouse применяет настройку в тех случаях, когда запрос содержит произведение распределённых таблиц, т.е. когда запрос к распределенной таблице содержит не-GLOBAL подзапрос к также распределенной таблице.
@ -13,7 +13,7 @@ ClickHouse применяет настройку в тех случаях, ко
- Только подзапросы для IN, JOIN.
- Только если в секции FROM используется распределённая таблица, содержащая более одного шарда.
- Если подзапрос касается распределенной таблицы, содержащей более одного шарда,
- Не используется в случае табличной функции [remote](../../query_language/table_functions/remote.md#table_functions-remote).
- Не используется в случае табличной функции [remote](../../query_language/table_functions/remote.md).
Возможные значения:
@ -26,7 +26,7 @@ ClickHouse применяет настройку в тех случаях, ко
## fallback_to_stale_replicas_for_distributed_queries
Форсирует запрос в устаревшую реплику в случае, если актуальные данные недоступны. Смотрите "[Репликация](../../operations/table_engines/replication.md#table_engines-replication)".
Форсирует запрос в устаревшую реплику в случае, если актуальные данные недоступны. Смотрите "[Репликация](../../operations/table_engines/replication.md)".
Из устаревших реплик таблицы ClickHouse выбирает наиболее актуальную.
@ -42,7 +42,7 @@ ClickHouse применяет настройку в тех случаях, ко
Работает с таблицами семейства MergeTree.
При `force_index_by_date=1` ClickHouse проверяет, есть ли в запросе условие на ключ даты, которое может использоваться для отсечения диапазонов данных. Если подходящего условия нет - кидается исключение. При этом не проверяется, действительно ли условие уменьшает объём данных для чтения. Например, условие `Date != '2000-01-01'` подходит даже в том случае, когда соответствует всем данным в таблице (т.е. для выполнения запроса требуется full scan). Подробнее про диапазоны данных в таблицах MergeTree читайте в разделе "[MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree)".
При `force_index_by_date=1` ClickHouse проверяет, есть ли в запросе условие на ключ даты, которое может использоваться для отсечения диапазонов данных. Если подходящего условия нет - кидается исключение. При этом не проверяется, действительно ли условие уменьшает объём данных для чтения. Например, условие `Date != '2000-01-01'` подходит даже в том случае, когда соответствует всем данным в таблице (т.е. для выполнения запроса требуется full scan). Подробнее про диапазоны данных в таблицах MergeTree читайте в разделе "[MergeTree](../../operations/table_engines/mergetree.md)".
<a name="settings-settings-force_primary_key"></a>
@ -52,7 +52,7 @@ ClickHouse применяет настройку в тех случаях, ко
Работает с таблицами семейства MergeTree.
При `force_primary_key=1` ClickHouse проверяет, есть ли в запросе условие на первичный ключ, которое может использоваться для отсечения диапазонов данных. Если подходящего условия нет - кидается исключение. При этом не проверяется, действительно ли условие уменьшает объём данных для чтения. Подробнее про диапазоны данных в таблицах MergeTree читайте в разделе "[MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree)".
При `force_primary_key=1` ClickHouse проверяет, есть ли в запросе условие на первичный ключ, которое может использоваться для отсечения диапазонов данных. Если подходящего условия нет - кидается исключение. При этом не проверяется, действительно ли условие уменьшает объём данных для чтения. Подробнее про диапазоны данных в таблицах MergeTree читайте в разделе "[MergeTree](../../operations/table_engines/mergetree.md)".
<a name="settings_settings_fsync_metadata"></a>
@ -107,7 +107,7 @@ ClickHouse применяет настройку в тех случаях, ко
Установка логгирования запроса.
Запросы, переданные в ClickHouse с этой установкой, логгируются согласно правилам конфигурационного параметра сервера [query_log](../server_settings/settings.md#server_settings-query_log).
Запросы, переданные в ClickHouse с этой установкой, логгируются согласно правилам конфигурационного параметра сервера [query_log](../server_settings/settings.md).
**Пример** :
@ -131,7 +131,7 @@ ClickHouse применяет настройку в тех случаях, ко
## max_replica_delay_for_distributed_queries
Отключает отстающие реплики при распределенных запросах. Смотрите "[Репликация](../../operations/table_engines/replication.md#table_engines-replication)".
Отключает отстающие реплики при распределенных запросах. Смотрите "[Репликация](../../operations/table_engines/replication.md)".
Устанавливает время в секундах. Если оставание реплики больше установленного значения, то реплика не используется.
@ -163,8 +163,7 @@ ClickHouse применяет настройку в тех случаях, ко
## min_compress_block_size
Для таблиц типа "[MergeTree](../../operations/table_engines/mergetree.md#table_engines-mergetree)". В целях уменьшения задержек при обработке запросов, блок сжимается при записи следующей засечки, если его размер не меньше min_compress_block_size. По умолчанию - 65 536.
Для таблиц типа "[MergeTree](../../operations/table_engines/mergetree.md
Реальный размер блока, если несжатых данных меньше max_compress_block_size, будет не меньше этого значения и не меньше объёма данных на одну засечку.
Рассмотрим пример. Пусть index_granularity, указанная при создании таблицы - 8192.
@ -264,7 +263,7 @@ ClickHouse применяет настройку в тех случаях, ко
## stream_flush_interval_ms
Работает для таблиц со стриммингом в случае тайм-аута, или когда поток генерирует [max_insert_block_size](#settings-settings-max_insert_block_size) строк.
Работает для таблиц со стриммингом в случае тайм-аута, или когда поток генерирует [max_insert_block_size]() строк.
Значение по умолчанию - 7500.
@ -352,9 +351,9 @@ ClickHouse применяет настройку в тех случаях, ко
## join_use_nulls
Влияет на поведение [JOIN](../../query_language/select.md#query_language-join).
Влияет на поведение [JOIN](../../query_language/select.md).
При `join_use_nulls=1` `JOIN` ведёт себя как в стандартном SQL, т.е. если при слиянии возникают пустые ячейки, то тип соответствующего поля преобразуется к [Nullable](../../data_types/nullable.md#data_type-nullable), а пустые ячейки заполняются значениями [NULL](../../query_language/syntax.md#null-literal).
При `join_use_nulls=1` `JOIN` ведёт себя как в стандартном SQL, т.е. если при слиянии возникают пустые ячейки, то тип соответствующего поля преобразуется к [Nullable](../../data_types/nullable.md#data_type-nullable), а пустые ячейки заполняются значениями [NULL](../../query_language/syntax.md).
<a name="setting-insert_quorum"></a>
@ -373,7 +372,7 @@ ClickHouse применяет настройку в тех случаях, ко
Все реплики в кворуме консистентны, т.е. содержат данные всех более ранних запросов `INSERT`. Последовательность `INSERT` линеаризуется.
При чтении данных, записанных с `insert_quorum` можно использовать настройку [select_sequential_consistency](#setting-select_sequential_consistency).
При чтении данных, записанных с `insert_quorum` можно использовать настройку [select_sequential_consistency]().
**ClickHouse генерирует исключение**
@ -382,8 +381,8 @@ ClickHouse применяет настройку в тех случаях, ко
**См. также параметры**
- [insert_quorum_timeout](#setting-insert_quorum_timeout)
- [select_sequential_consistency](#setting-select_sequential_consistency)
- [insert_quorum_timeout]()
- [select_sequential_consistency]()
<a name="setting-insert_quorum_timeout"></a>
@ -395,8 +394,8 @@ ClickHouse применяет настройку в тех случаях, ко
**См. также параметры**
- [insert_quorum](#setting-insert_quorum)
- [select_sequential_consistency](#setting-select_sequential_consistency)
- [insert_quorum]()
- [select_sequential_consistency]()
<a name="setting-select_sequential_consistency"></a>
@ -411,7 +410,7 @@ ClickHouse применяет настройку в тех случаях, ко
См. также параметры:
- [insert_quorum](#setting-insert_quorum)
- [insert_quorum_timeout](#setting-insert_quorum_timeout)
- [insert_quorum]()
- [insert_quorum_timeout]()
[Оригинальная статья](https://clickhouse.yandex/docs/ru/operations/settings/settings/) <!--hide-->

View File

@ -122,7 +122,7 @@ default_expression String - выражение для значения по ум
## system.parts
Содержит информацию о кусках таблиц семейства [MergeTree](table_engines/mergetree.md#table_engines-mergetree).
Содержит информацию о кусках таблиц семейства [MergeTree](table_engines/mergetree.md).
Каждая строка описывает один кусок данных.

View File

@ -2,11 +2,11 @@
# AggregatingMergeTree
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree), изменяя логику слияния кусков данных. Все строки с одинаковым первичным ключом (точнее, с одинаковым [ключом сортировки](mergetree.md#table_engines-mergetree-sorting_key)) ClickHouse заменяет на одну (в пределах одного куска данных), которая хранит объединение состояний агрегатных функций.
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree), изменяя логику слияния кусков данных. Все строки с одинаковым первичным ключом (точнее, с одинаковым [ключом сортировки](mergetree.md)) ClickHouse заменяет на одну (в пределах одного куска данных), которая хранит объединение состояний агрегатных функций.
Таблицы типа `AggregatingMergeTree` могут использоваться для инкрементальной агрегации данных, в том числе, для агрегирующих материализованных представлений.
Движок обрабатывает все столбцы типа [AggregateFunction](../../data_types/nested_data_structures/aggregatefunction.md#data_type-aggregatefunction).
Движок обрабатывает все столбцы типа [AggregateFunction](../../data_types/nested_data_structures/aggregatefunction.md).
Использование `AggregatingMergeTree` оправдано только в том случае, когда это уменьшает количество строк на порядки.
@ -25,11 +25,11 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md#query_language-queries-create_table).
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md).
**Секции запроса**
При создании таблицы `AggregatingMergeTree` используются те же [секции](mergetree.md#table_engines-mergetree-configuring), что и при создании таблицы `MergeTree`.
При создании таблицы `AggregatingMergeTree` используются те же [секции](mergetree.md), что и при создании таблицы `MergeTree`.
<details markdown="1"><summary>Устаревший способ создания таблицы</summary>

View File

@ -2,7 +2,7 @@
# Dictionary
Движок `Dictionary` отображает данные [словаря](../../query_language/dicts/external_dicts.md#dicts-external_dicts) как таблицу ClickHouse.
Движок `Dictionary` отображает данные [словаря](../../query_language/dicts/external_dicts.md) как таблицу ClickHouse.
Рассмотрим для примера словарь `products` со следующей конфигурацией:

View File

@ -18,11 +18,11 @@ File(Format)
`Format` должен быть таким, который ClickHouse может использовать и в запросах `INSERT` и в запросах `SELECT`. Полный список поддерживаемых форматов смотрите в разделе [Форматы](../../interfaces/formats.md#formats).
Сервер ClickHouse не позволяет указать путь к файлу, с которым будет работать `File`. Используется путь к хранилищу, определенный параметром [path](../server_settings/settings.md#server_settings-path) в конфигурации сервера.
Сервер ClickHouse не позволяет указать путь к файлу, с которым будет работать `File`. Используется путь к хранилищу, определенный параметром [path](../server_settings/settings.md) в конфигурации сервера.
При создании таблицы с помощью `File(Format)` сервер ClickHouse создает в хранилище каталог с именем таблицы, а после добавления в таблицу данных помещает туда файл `data.Format`.
Можно вручную создать в хранилище каталог таблицы, поместить туда файл, затем на сервере ClickHouse добавить ([ATTACH](../../query_language/misc.md#queries-attach)) информацию о таблице, соответствующей имени каталога и прочитать из файла данные.
Можно вручную создать в хранилище каталог таблицы, поместить туда файл, затем на сервере ClickHouse добавить ([ATTACH](../../query_language/misc.md)) информацию о таблице, соответствующей имени каталога и прочитать из файла данные.
!!! warning
Будьте аккуратны с этой функциональностью, поскольку сервер ClickHouse не отслеживает внешние изменения данных. Если в файл будет производиться запись одновременно со стороны сервера ClickHouse и с внешней стороны, то результат непредсказуем.
@ -60,7 +60,7 @@ SELECT * FROM file_engine_table
## Использование движка в clickhouse-local
В [clickhouse-local](../utils/clickhouse-local.md#utils-clickhouse-local) движок в качестве параметра принимает не только формат, но и путь к файлу. В том числе можно указать стандартные потоки ввода/вывода цифровым или буквенным обозначением `0` или `stdin`, `1` или `stdout`.
В [clickhouse-local](../utils/clickhouse-local.md) движок в качестве параметра принимает не только формат, но и путь к файлу. В том числе можно указать стандартные потоки ввода/вывода цифровым или буквенным обозначением `0` или `stdin`, `1` или `stdout`.
**Пример:**

View File

@ -8,13 +8,13 @@ Graphite хранит в ClickHouse полные данные, а получат
- Без прореживания.
Используется движок [MergeTree](mergetree.md#table_engines-mergetree).
Используется движок [MergeTree](mergetree.md).
- С прореживанием.
Используется движок `GraphiteMergeTree`.
Движок наследует свойства MergeTree. Настройки прореживания данных задаются параметром [graphite_rollup](../server_settings/settings.md#server_settings-graphite_rollup) в конфигурации сервера .
Движок наследует свойства MergeTree. Настройки прореживания данных задаются параметром [graphite_rollup](../server_settings/settings.md) в конфигурации сервера .
## Использование движка

View File

@ -105,7 +105,7 @@ Kafka SETTINGS
SELECT level, sum(total) FROM daily GROUP BY level;
```
Для улучшения производительности полученные сообщения группируются в блоки размера [max_insert_block_size](../settings/settings.md#settings-settings-max_insert_block_size). Если блок не удалось сформировать за [stream_flush_interval_ms](../settings/settings.md#settings-settings_stream_flush_interval_ms) миллисекунд, то данные будут сброшены в таблицу независимо от полноты блока.
Для улучшения производительности полученные сообщения группируются в блоки размера [max_insert_block_size](../settings/settings.md#settings-settings-max_insert_block_size). Если блок не удалось сформировать за [stream_flush_interval_ms](../settings/settings.md) миллисекунд, то данные будут сброшены в таблицу независимо от полноты блока.
Чтобы остановить получение данных топика или изменить логику преобразования, отсоедините материализованное представление:

View File

@ -1,5 +1,5 @@
# MaterializedView
Используется для реализации материализованных представлений (подробнее см. запрос [CREATE TABLE](../../query_language/create.md#query_language-queries-create_table)). Для хранения данных, использует другой движок, который был указан при создании представления. При чтении из таблицы, просто использует этот движок.
Используется для реализации материализованных представлений (подробнее см. запрос [CREATE TABLE](../../query_language/create.md)). Для хранения данных, использует другой движок, который был указан при создании представления. При чтении из таблицы, просто использует этот движок.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/operations/table_engines/materializedview/) <!--hide-->

View File

@ -5,7 +5,7 @@
Движок `MergeTree`, а также другие движки этого семейства (`*MergeTree`) — это наиболее функциональные движки таблиц ClickHousе.
!!!info
Движок [Merge](merge.md#table_engine-merge) не относится к семейству `*MergeTree`.
Движок [Merge](merge.md) не относится к семейству `*MergeTree`.
Основные возможности:
@ -13,13 +13,13 @@
Это позволяет создавать разреженный индекс небольшого объёма, который позволяет быстрее находить данные.
- Позволяет оперировать партициями, если задан [ключ партиционирования](custom_partitioning_key.md#table_engines-custom_partitioning_key).
- Позволяет оперировать партициями, если задан [ключ партиционирования](custom_partitioning_key.md).
ClickHouse поддерживает отдельные операции с партициями, которые работают эффективнее, чем общие операции с этим же результатом над этими же данными. Также, ClickHouse автоматически отсекает данные по партициям там, где ключ партиционирования указан в запросе. Это также увеличивает эффективность выполнения запросов.
- Поддерживает репликацию данных.
Для этого используется семейство таблиц `ReplicatedMergeTree`. Подробнее читайте в разделе [Репликация данных](replication.md#table_engines-replication).
Для этого используется семейство таблиц `ReplicatedMergeTree`. Подробнее читайте в разделе [Репликация данных](replication.md).
- Поддерживает сэмплирование данных.
@ -43,21 +43,21 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md#query_language-queries-create_table).
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md).
**Секции запроса**
- `ENGINE` — Имя и параметры движка. `ENGINE = MergeTree()`. Движок `MergeTree` не имеет параметров.
- `PARTITION BY` — [ключ партиционирования](custom_partitioning_key.md#table_engines-custom_partitioning_key).
- `PARTITION BY` — [ключ партиционирования](custom_partitioning_key.md).
Для партиционирования по месяцам используйте выражение `toYYYYMM(date_column)`, где `date_column` — столбец с датой типа [Date](../../data_types/date.md#data_type-date). В этом случае имена партиций имеют формат `"YYYYMM"`.
Для партиционирования по месяцам используйте выражение `toYYYYMM(date_column)`, где `date_column` — столбец с датой типа [Date](../../data_types/date.md). В этом случае имена партиций имеют формат `"YYYYMM"`.
- `ORDER BY` — ключ сортировки.
Кортеж столбцов или произвольных выражений. Пример: `ORDER BY (CounerID, EventDate)`.
- `PRIMARY KEY` - первичный ключ, если он [отличается от ключа сортировки](mergetree.md#table_engines-mergetree-sorting_key).
- `PRIMARY KEY` - первичный ключ, если он [отличается от ключа сортировки](mergetree.md).
По умолчанию первичный ключ совпадает с ключом сортировки (который задаётся секцией `ORDER BY`). Поэтому
в большинстве случаев секцию `PRIMARY KEY` отдельно указывать не нужно.
@ -79,8 +79,7 @@ ENGINE MergeTree() PARTITION BY toYYYYMM(EventDate) ORDER BY (CounterID, EventDa
В примере мы устанавливаем партиционирование по месяцам.
Также мы задаем выражение для сэмплирования в виде хэша по идентификатору посетителя. Это позволяет псевдослучайным образом перемешать данные в таблице для каждого `CounterID` и `EventDate`. Если при выборке данных задать секцию [SAMPLE](../../query_language/select.md#select-section-sample) то ClickHouse вернёт равномерно-псевдослучайную выборку данных для подмножества посетителей.
Также мы задаем выражение для сэмплирования в виде хэша по идентификатору посетителя. Это позволяет псевдослучайным образом перемешать данные в таблице для каждого `CounterID` и `EventDate`. Если при выборке данных задать секцию [SAMPLE](../../query_language/select.md
`index_granularity` можно было не указывать, поскольку 8192 — это значение по умолчанию.
<details markdown="1"><summary>Устаревший способ создания таблицы</summary>
@ -99,10 +98,9 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
**Параметры MergeTree()**
- `date-column` — имя столбца с типом [Date](../../data_types/date.md#data_type-date). На основе этого столбца ClickHouse автоматически создаёт партиции по месяцам. Имена партиций имеют формат `"YYYYMM"`.
- `date-column` — имя столбца с типом [Date](../../data_types/date.md). На основе этого столбца ClickHouse автоматически создаёт партиции по месяцам. Имена партиций имеют формат `"YYYYMM"`.
- `sampling_expression` — выражение для сэмплирования.
- `(primary, key)` — первичный ключ. Тип — [Tuple()](../../data_types/tuple.md#data_type-tuple). Может состоять из произвольных выражений, но обычно это кортеж столбцов. Обязательно должен включать в себя выражение для сэмплирования, если оно задано. Не обязан включать в себя столбец с датой `date-column`.
- `index_granularity` — гранулярность индекса. Число строк данных между «засечками» индекса. Для большинства задач подходит значение 8192.
- `(primary, key)` — первичный ключ. Тип — [Tuple()](../../data_types/tuple.md- `index_granularity` — гранулярность индекса. Число строк данных между «засечками» индекса. Для большинства задач подходит значение 8192.
**Пример**
@ -167,7 +165,7 @@ ClickHouse не требует уникального первичного кл
ClickHouse сортирует данные по первичному ключу, поэтому чем выше однородность, тем лучше сжатие.
- Обеспечить дополнительную логику при слиянии кусков данных в движках [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) и [SummingMergeTree](summingmergetree.md#table_engine-summingmergetree).
- Обеспечить дополнительную логику при слиянии кусков данных в движках [CollapsingMergeTree](collapsingmergetree.md#table_engine-collapsingmergetree) и [SummingMergeTree](summingmergetree.md).
В этом случае имеет смысл задать отдельный *ключ сортировки*, отличающийся от первичного ключа.
@ -193,8 +191,7 @@ ClickHouse не требует уникального первичного кл
В этом сценарии имеет смысл оставить в первичном ключе всего несколько столбцов, которые обеспечат эффективную
фильтрацию по индексу, а остальные столбцы-измерения добавить в выражение ключа сортировки.
[ALTER ключа сортировки](../../query_language/alter.md#query_language-queries-alter-key_alters) - легкая
операция, так как при одновременном добавлении нового столбца в таблицу и ключ сортировки не нужно изменять
[ALTER ключа сортировки](../../query_language/alter.mdоперация, так как при одновременном добавлении нового столбца в таблицу и ключ сортировки не нужно изменять
данные кусков (они остаются упорядоченными и по новому выражению ключа).
### Использование индексов и партиций в запросах
@ -227,7 +224,7 @@ ClickHouse будет использовать индекс по первичн
SELECT count() FROM table WHERE CounterID = 34 OR URL LIKE '%upyachka%'
```
Чтобы проверить, сможет ли ClickHouse использовать индекс при выполнении запроса, используйте настройки [force_index_by_date](../settings/settings.md#settings-settings-force_index_by_date) и [force_primary_key](../settings/settings.md#settings-settings-force_primary_key).
Чтобы проверить, сможет ли ClickHouse использовать индекс при выполнении запроса, используйте настройки [force_index_by_date](../settings/settings.md#settings-settings-force_index_by_date) и [force_primary_key](../settings/settings.md).
Ключ партиционирования по месяцам обеспечивает чтение только тех блоков данных, которые содержат даты из нужного диапазона. При этом блок данных может содержать данные за многие даты (до целого месяца). В пределах одного блока данные упорядочены по первичному ключу, который может не содержать дату в качестве первого столбца. В связи с этим, при использовании запроса с указанием условия только на дату, но не на префикс первичного ключа, будет читаться данных больше, чем за одну дату.

View File

@ -28,6 +28,6 @@ MySQL('host:port', 'database', 'table', 'user', 'password'[, replace_query, 'on_
Остальные условия и ограничение выборки `LIMIT` будут выполнены в ClickHouse только после выполнения запроса к MySQL.
Движок `MySQL` не поддерживает тип данных [Nullable](../../data_types/nullable.md#data_type-nullable), поэтому при чтении данных из таблиц MySQL `NULL` преобразуются в значения по умолчанию для заданного типа столбца, обычно это 0 или пустая строка.
Движок `MySQL` не поддерживает тип данных [Nullable](../../data_types/nullable.md), поэтому при чтении данных из таблиц MySQL `NULL` преобразуются в значения по умолчанию для заданного типа столбца, обычно это 0 или пустая строка.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/operations/table_engines/mysql/) <!--hide-->

View File

@ -1,6 +1,6 @@
# ReplacingMergeTree
Движок отличается от [MergeTree](mergetree.md#table_engines-mergetree) тем, что выполняет удаление дублирующихся записей с одинаковым значением первичного ключа (точнее, с одинаковым значением [ключа сортировки](mergetree.md#table_engines-mergetree-sorting_key)).
Движок отличается от [MergeTree](mergetree.md#table_engines-mergetree) тем, что выполняет удаление дублирующихся записей с одинаковым значением первичного ключа (точнее, с одинаковым значением [ключа сортировки](mergetree.md)).
Дедупликация данных производится лишь во время слияний. Слияние происходят в фоне в неизвестный момент времени, на который вы не можете ориентироваться. Некоторая часть данных может остаться необработанной. Хотя вы можете вызвать внеочередное слияние с помощью запроса `OPTIMIZE`, на это не стоит рассчитывать, так как запрос `OPTIMIZE` приводит к чтению и записи большого объёма данных.
@ -21,7 +21,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md#query_language-queries-create_table).
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md).
**Параметры ReplacingMergeTree**
@ -34,7 +34,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
**Секции запроса**
При создании таблицы `ReplacingMergeTree` используются те же [секции](mergetree.md#table_engines-mergetree-configuring), что и при создании таблицы `MergeTree`.
При создании таблицы `ReplacingMergeTree` используются те же [секции](mergetree.md), что и при создании таблицы `MergeTree`.
<details markdown="1"><summary>Устаревший способ создания таблицы</summary>

View File

@ -48,7 +48,7 @@
Если в конфигурационном файле не настроен ZooKeeper, то вы не сможете создать реплицируемые таблицы, а уже имеющиеся реплицируемые таблицы будут доступны в режиме только на чтение.
При запросах `SELECT`, ZooKeeper не используется, т.е. репликация не влияет на производительность `SELECT` и запросы работают так же быстро, как и для нереплицируемых таблиц. При запросах к распределенным реплицированным таблицам поведение ClickHouse регулируется настройками [max_replica_delay_for_distributed_queries](../settings/settings.md#settings_settings_max_replica_delay_for_distributed_queries) и [fallback_to_stale_replicas_for_distributed_queries](../settings/settings.md#settings-settings-fallback_to_stale_replicas_for_distributed_queries).
При запросах `SELECT`, ZooKeeper не используется, т.е. репликация не влияет на производительность `SELECT` и запросы работают так же быстро, как и для нереплицируемых таблиц. При запросах к распределенным реплицированным таблицам поведение ClickHouse регулируется настройками [max_replica_delay_for_distributed_queries](../settings/settings.md#settings_settings_max_replica_delay_for_distributed_queries) и [fallback_to_stale_replicas_for_distributed_queries](../settings/settings.md).
При каждом запросе `INSERT` (точнее, на каждый вставляемый блок данных; запрос INSERT содержит один блок, или по блоку на каждые `max_insert_block_size = 1048576` строк), делается около десятка записей в ZooKeeper в рамках нескольких транзакций. Это приводит к некоторому увеличению задержек при `INSERT`, по сравнению с нереплицируемыми таблицами. Но если придерживаться обычных рекомендаций - вставлять данные пачками не более одного `INSERT` в секунду, то это не составляет проблем. На всём кластере ClickHouse, использующим для координации один кластер ZooKeeper, может быть в совокупности несколько сотен `INSERT` в секунду. Пропускная способность при вставке данных (количество строчек в секунду) такая же высокая, как для нереплицируемых таблиц.
@ -56,11 +56,11 @@
Репликация асинхронная, мульти-мастер. Запросы `INSERT` (а также `ALTER`) можно отправлять на любой доступный сервер. Данные вставятся на сервер, где выполнен запрос, а затем скопируются на остальные серверы. В связи с асинхронностью, только что вставленные данные появляются на остальных репликах с небольшой задержкой. Если часть реплик недоступна, данные на них запишутся тогда, когда они станут доступны. Если реплика доступна, то задержка составляет столько времени, сколько требуется для передачи блока сжатых данных по сети.
По умолчанию, запрос INSERT ждёт подтверждения записи только от одной реплики. Если данные были успешно записаны только на одну реплику, и сервер с этой репликой перестал существовать, то записанные данные будут потеряны. Вы можете включить подтверждение записи от нескольких реплик, используя настройку [insert_quorum](../settings/settings.md#setting-insert_quorum).
По умолчанию, запрос INSERT ждёт подтверждения записи только от одной реплики. Если данные были успешно записаны только на одну реплику, и сервер с этой репликой перестал существовать, то записанные данные будут потеряны. Вы можете включить подтверждение записи от нескольких реплик, используя настройку [insert_quorum](../settings/settings.md).
Каждый блок данных записывается атомарно. Запрос INSERT разбивается на блоки данных размером до `max_insert_block_size = 1048576` строк. То есть, если в запросе `INSERT` менее 1048576 строк, то он делается атомарно.
Блоки данных дедуплицируются. При многократной записи одного и того же блока данных (блоков данных одинакового размера, содержащих одни и те же строчки в одном и том же порядке), блок будет записан только один раз. Это сделано для того, чтобы в случае сбоя в сети, когда клиентское приложение не может понять, были ли данные записаны в БД, можно было просто повторить запрос `INSERT`. При этом не имеет значения, на какую реплику будут отправлены INSERT-ы с одинаковыми данными. То есть, обеспечивается идемпотентность `INSERT`. Параметры дедупликации регулируются настройками сервера [merge_tree](../server_settings/settings.md#server_settings-merge_tree).
Блоки данных дедуплицируются. При многократной записи одного и того же блока данных (блоков данных одинакового размера, содержащих одни и те же строчки в одном и том же порядке), блок будет записан только один раз. Это сделано для того, чтобы в случае сбоя в сети, когда клиентское приложение не может понять, были ли данные записаны в БД, можно было просто повторить запрос `INSERT`. При этом не имеет значения, на какую реплику будут отправлены INSERT-ы с одинаковыми данными. То есть, обеспечивается идемпотентность `INSERT`. Параметры дедупликации регулируются настройками сервера [merge_tree](../server_settings/settings.md).
При репликации, по сети передаются только исходные вставляемые данные. Дальнейшие преобразования данных (слияния) координируются и делаются на всех репликах одинаковым образом. За счёт этого минимизируется использование сети, и благодаря этому, репликация хорошо работает при расположении реплик в разных датацентрах. (Стоит заметить, что дублирование данных в разных датацентрах, по сути, является основной задачей репликации).
@ -169,7 +169,7 @@ sudo -u clickhouse touch /var/lib/clickhouse/flags/force_restore_data
Затем запустите сервер (перезапустите, если уже запущен). Данные будут скачаны с реплик.
В качестве альтернативного варианта восстановления, вы можете удалить из ZooKeeper информацию о потерянной реплике - `/path_to_table/replica_name`, и затем создать реплику заново, как написано в разделе "[Создание реплицируемых таблиц](#table_engines-replication-creation_of_rep_tables)".
В качестве альтернативного варианта восстановления, вы можете удалить из ZooKeeper информацию о потерянной реплике - `/path_to_table/replica_name`, и затем создать реплику заново, как написано в разделе "[Создание реплицируемых таблиц]()".
Отсутствует ограничение на использование сетевой полосы при восстановлении. Имейте это ввиду, если восстанавливаете сразу много реплик.

View File

@ -2,7 +2,7 @@
# SummingMergeTree
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree). Отличие заключается в том, что для таблиц `SummingMergeTree` при слиянии кусков данных ClickHouse все строки с одинаковым первичным ключом (точнее, с одинаковым [ключом сортировки](mergetree.md#table_engines-mergetree-sorting_key)) заменяет на одну, которая хранит только суммы значений из столбцов с цифровым типом данных. Если ключ сортировки подобран таким образом, что одному значению ключа соответствует много строк, это значительно уменьшает объем хранения и ускоряет последующую выборку данных.
Движок наследует функциональность [MergeTree](mergetree.md#table_engines-mergetree). Отличие заключается в том, что для таблиц `SummingMergeTree` при слиянии кусков данных ClickHouse все строки с одинаковым первичным ключом (точнее, с одинаковым [ключом сортировки](mergetree.md)) заменяет на одну, которая хранит только суммы значений из столбцов с цифровым типом данных. Если ключ сортировки подобран таким образом, что одному значению ключа соответствует много строк, это значительно уменьшает объем хранения и ускоряет последующую выборку данных.
Мы рекомендуем использовать движок в паре с `MergeTree`. В `MergeTree` храните полные данные, а `SummingMergeTree` используйте для хранения агрегированных данных, например, при подготовке отчетов. Такой подход позволит не утратить ценные данные из-за неправильно выбранного первичного ключа.
@ -21,7 +21,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
[SETTINGS name=value, ...]
```
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md#query_language-queries-create_table).
Описание параметров запроса смотрите в [описании запроса](../../query_language/create.md).
**Параметры SummingMergeTree**
@ -32,7 +32,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
**Секции запроса**
При создании таблицы `SummingMergeTree` использутся те же [секции](mergetree.md#table_engines-mergetree-configuring) запроса, что и при создании таблицы `MergeTree`.
При создании таблицы `SummingMergeTree` использутся те же [секции](mergetree.md) запроса, что и при создании таблицы `MergeTree`.
<details markdown="1"><summary>Устаревший способ создания таблицы</summary>
@ -73,7 +73,7 @@ ORDER BY key
:) INSERT INTO summtt Values(1,1),(1,2),(2,1)
```
ClickHouse может не полностью просуммировать все строки ([смотрите ниже по тексту](#summingmergetree-data-processing)), поэтому при запросе мы используем агрегатную функцию `sum` и секцию `GROUP BY`.
ClickHouse может не полностью просуммировать все строки ([смотрите ниже по тексту]()), поэтому при запросе мы используем агрегатную функцию `sum` и секцию `GROUP BY`.
```sql
SELECT key, sum(value) FROM summtt GROUP BY key
@ -91,7 +91,7 @@ SELECT key, sum(value) FROM summtt GROUP BY key
При вставке данных в таблицу они сохраняются как есть. Периодически ClickHouse выполняет слияние вставленных кусков данных и именно в этот момент производится суммирование и замена многих строк с одинаковым первичным ключом на одну для каждого результирующего куска данных.
ClickHouse может слить куски данных таким образом, что не все строки с одинаковым первичным ключом окажутся в одном финальном куске, т.е. суммирование будет не полным. Поэтому, при выборке данных (`SELECT`) необходимо использовать агрегатную функцию [sum()](../../query_language/agg_functions/reference.md#agg_function-sum) и секцию `GROUP BY` как описано в примере выше.
ClickHouse может слить куски данных таким образом, что не все строки с одинаковым первичным ключом окажутся в одном финальном куске, т.е. суммирование будет не полным. Поэтому, при выборке данных (`SELECT`) необходимо использовать агрегатную функцию [sum()](../../query_language/agg_functions/reference.md) и секцию `GROUP BY` как описано в примере выше.
### Общие правила суммирования
@ -105,7 +105,7 @@ ClickHouse может слить куски данных таким образо
### Суммирование в столбцах AggregateFunction
Для столбцов типа [AggregateFunction](../../data_types/nested_data_structures/aggregatefunction.md#data_type-aggregatefunction) ClickHouse выполняет агрегацию согласно заданной функции, повторяя поведение движка [AggregatingMergeTree](aggregatingmergetree.md#table_engine-aggregatingmergetree).
Для столбцов типа [AggregateFunction](../../data_types/nested_data_structures/aggregatefunction.md#data_type-aggregatefunction) ClickHouse выполняет агрегацию согласно заданной функции, повторяя поведение движка [AggregatingMergeTree](aggregatingmergetree.md).
### Вложенные структуры
@ -127,7 +127,7 @@ ClickHouse может слить куски данных таким образо
[(1, 100), (2, 150)] + [(1, -100)] -> [(2, 150)]
```
При запросе данных используйте функцию [sumMap(key, value)](../../query_language/agg_functions/reference.md#agg_function-summap) для агрегации `Map`.
При запросе данных используйте функцию [sumMap(key, value)](../../query_language/agg_functions/reference.md) для агрегации `Map`.
Для вложенной структуры данных не нужно указывать её столбцы в кортеже столбцов для суммирования.

View File

@ -1,6 +1,5 @@
# Утилиты ClickHouse
* [clickhouse-local](clickhouse-local.md#utils-clickhouse-local) - позволяет выполнять SQL-запросы над данными без установки сервера ClickHouse подобно тому, как это делает `awk`.
* [clickhouse-copier](clickhouse-copier.md#utils-clickhouse-copier) - копирует (и перешардирует) данные с одного кластера на другой.
* [clickhouse-local](clickhouse-local.md* [clickhouse-copier](clickhouse-copier.md) данные с одного кластера на другой.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/operations/utils/) <!--hide-->

View File

@ -62,7 +62,7 @@ windowFunnel(window)(timestamp, cond1, cond2, cond3, ...)
**Параметры**
- `window` — ширина скользящего окна по времени в секундах.
- `timestamp` — имя столбца, содержащего отметки времени. Тип данных [DateTime](../../data_types/datetime.md#data_type-datetime) или [UInt32](../../data_types/int_uint.md#data_type-int).
- `timestamp` — имя столбца, содержащего отметки времени. Тип данных [DateTime](../../data_types/datetime.md#data_type-datetime) или [UInt32](../../data_types/int_uint.md).
- `cond1`, `cond2`... — условия или данные, описывающие цепочку событий. Тип данных — `UInt8`. Значения могут быть 0 или 1.
**Алгоритм**

View File

@ -35,7 +35,7 @@ anyHeavy(column)
**Пример**
Возьмём набор данных [OnTime](../../getting_started/example_datasets/ontime.md#example_datasets-ontime) и выберем произвольное часто встречающееся значение в столбце `AirlineID`.
Возьмём набор данных [OnTime](../../getting_started/example_datasets/ontime.md) и выберем произвольное часто встречающееся значение в столбце `AirlineID`.
```sql
SELECT anyHeavy(AirlineID) AS res
@ -463,7 +463,7 @@ topK(N)(column)
**Пример**
Возьмём набор данных [OnTime](../../getting_started/example_datasets/ontime.md#example_datasets-ontime) и выберем 3 наиболее часто встречающихся значения в столбце `AirlineID`.
Возьмём набор данных [OnTime](../../getting_started/example_datasets/ontime.md) и выберем 3 наиболее часто встречающихся значения в столбце `AirlineID`.
```sql
SELECT topK(3)(AirlineID) AS res

View File

@ -75,7 +75,7 @@ MODIFY ORDER BY new_expression
```
Работает только для таблиц семейства [`MergeTree`](../operations/table_engines/mergetree.md) (в том числе [реплицированных](../operations/table_engines/replication.md)). После выполнения запроса
[ключ сортировки](../operations/table_engines/mergetree.md#table_engines-mergetree-sorting_key) таблицы
[ключ сортировки](../operations/table_engines/mergetree.md) таблицы
заменяется на `new_expression` (выражение или кортеж выражений). Первичный ключ при этом остаётся прежним.
Операция затрагивает только метаданные. Чтобы сохранить свойство упорядоченности кусков данных по ключу

View File

@ -2,16 +2,16 @@
# Внешние словари
Существует возможность подключать собственные словари из различных источников данных. Источником данных для словаря может быть локальный текстовый/исполняемый файл, HTTP(s) ресурс или другая СУБД. Подробнее смотрите в разделе "[Источники внешних словарей](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources)".
Существует возможность подключать собственные словари из различных источников данных. Источником данных для словаря может быть локальный текстовый/исполняемый файл, HTTP(s) ресурс или другая СУБД. Подробнее смотрите в разделе "[Источники внешних словарей](external_dicts_dict_sources.md)".
ClickHouse:
- Полностью или частично хранит словари в оперативной памяти.
- Периодически обновляет их и динамически подгружает отсутствующие значения. Т.е. словари можно подгружать динамически.
Конфигурация внешних словарей находится в одном или нескольких файлах. Путь к конфигурации указывается в параметре [dictionaries_config](../../operations/server_settings/settings.md#server_settings-dictionaries_config).
Конфигурация внешних словарей находится в одном или нескольких файлах. Путь к конфигурации указывается в параметре [dictionaries_config](../../operations/server_settings/settings.md).
Словари могут загружаться при старте сервера или при первом использовании, в зависимости от настройки [dictionaries_lazy_load](../../operations/server_settings/settings.md#server_settings-dictionaries_lazy_load).
Словари могут загружаться при старте сервера или при первом использовании, в зависимости от настройки [dictionaries_lazy_load](../../operations/server_settings/settings.md).
Конфигурационный файл словарей имеет вид:
@ -35,18 +35,18 @@ ClickHouse:
</yandex>
```
В одном файле можно [сконфигурировать](external_dicts_dict.md#dicts-external_dicts_dict) произвольное количество словарей. Формат файла сохраняется даже если словарь один (т.е. `<yandex><dictionary> <!--configuration--> </dictionary></yandex>`).
В одном файле можно [сконфигурировать](external_dicts_dict.md).
>Вы можете преобразовывать значения по небольшому словарю, описав его в запросе `SELECT` (см. функцию [transform](../functions/other_functions.md#other_functions-transform)). Эта функциональность не связана с внешними словарями.
>Вы можете преобразовывать значения по небольшому словарю, описав его в запросе `SELECT` (см. функцию [transform](../functions/other_functions.md)). Эта функциональность не связана с внешними словарями.
Смотрите также:
- [Настройка внешнего словаря](external_dicts_dict.md#dicts-external_dicts_dict)
- [Хранение словарей в памяти](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout)
- [Обновление словарей](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime)
- [Источники внешних словарей](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources)
- [Ключ и поля словаря](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure)
- [Настройка внешнего словаря](external_dicts_dict.md)
- [Хранение словарей в памяти](external_dicts_dict_layout.md)
- [Обновление словарей](external_dicts_dict_lifetime.md)
- [Источники внешних словарей](external_dicts_dict_sources.md)
- [Ключ и поля словаря](external_dicts_dict_structure.md)
- [Функции для работы с внешними словарями](../functions/ext_dict_functions.md#ext_dict_functions)
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/dicts/external_dicts/) <!--hide-->

View File

@ -27,9 +27,5 @@
```
- name - Идентификатор, под которым словарь будет доступен для использования. Используйте символы `[a-zA-Z0-9_\-]`.
- [source](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources) - Источник словаря.
- [layout](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout) - Размещение словаря в памяти.
- [structure](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure) - Структура словаря. Ключ и атрибуты, которые можно получить по ключу.
- [lifetime](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime) - Периодичность обновления словарей.
- [source](external_dicts_dict_sources.md- [layout](external_dicts_dict_layout.md- [structure](external_dicts_dict_structure.md- [lifetime](external_dicts_dict_lifetime.md
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/dicts/external_dicts_dict/) <!--hide-->

View File

@ -2,11 +2,11 @@
# Хранение словарей в памяти
Словари можно размещать в памяти [множеством способов](#dicts-external_dicts_dict_layout-manner).
Словари можно размещать в памяти [множеством способов]().
Рекомендуем [flat](#dicts-external_dicts_dict_layout-flat), [hashed](#dicts-external_dicts_dict_layout-hashed) и [complex_key_hashed](#dicts-external_dicts_dict_layout-complex_key_hashed). Скорость обработки словарей при этом максимальна.
Рекомендуем [flat](#dicts-external_dicts_dict_layout-flat), [hashed](#dicts-external_dicts_dict_layout-hashed) и [complex_key_hashed](). Скорость обработки словарей при этом максимальна.
Размещение с кэшированием не рекомендуется использовать из-за потенциально низкой производительности и сложностей в подборе оптимальных параметров. Читайте об этом подробнее в разделе "[cache](#dicts-external_dicts_dict_layout-cache)".
Размещение с кэшированием не рекомендуется использовать из-за потенциально низкой производительности и сложностей в подборе оптимальных параметров. Читайте об этом подробнее в разделе "[cache]()".
Повысить производительнось словарей можно следующими способами:
@ -40,13 +40,13 @@
## Способы размещения словарей в памяти
- [flat](#dicts-external_dicts_dict_layout-flat)
- [hashed](#dicts-external_dicts_dict_layout-hashed)
- [cache](#dicts-external_dicts_dict_layout-cache)
- [range_hashed](#dicts-external_dicts_dict_layout-range_hashed)
- [complex_key_hashed](#dicts-external_dicts_dict_layout-complex_key_hashed)
- [complex_key_cache](#dicts-external_dicts_dict_layout-complex_key_cache)
- [ip_trie](#dicts-external_dicts_dict_layout-ip_trie)
- [flat]()
- [hashed]()
- [cache]()
- [range_hashed]()
- [complex_key_hashed]()
- [complex_key_cache]()
- [ip_trie]()
<a name="dicts-external_dicts_dict_layout-flat"></a>
@ -88,7 +88,7 @@
### complex_key_hashed
Тип размещения предназначен для использования с составными [ключами](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure). Аналогичен `hashed`.
Тип размещения предназначен для использования с составными [ключами](external_dicts_dict_structure.md). Аналогичен `hashed`.
Пример конфигурации:
@ -120,7 +120,7 @@
+---------------+---------------------+-------------------+--------+
```
Чтобы использовать выборку по диапазонам дат, необходимо в [structure](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure) определить элементы `range_min`, `range_max`.
Чтобы использовать выборку по диапазонам дат, необходимо в [structure](external_dicts_dict_structure.md) определить элементы `range_min`, `range_max`.
Пример:
@ -191,13 +191,13 @@
При поиске в словаре сначала просматривается кэш. На каждый блок данных, все не найденные в кэше или устаревшие ключи запрашиваются у источника с помощью `SELECT attrs... FROM db.table WHERE id IN (k1, k2, ...)`. Затем, полученные данные записываются в кэш.
Для cache-словарей может быть задано время устаревания [lifetime](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime) данных в кэше. Если от загрузки данных в ячейке прошло больше времени, чем `lifetime`, то значение не используется, и будет запрошено заново при следующей необходимости его использовать.
Для cache-словарей может быть задано время устаревания [lifetime](external_dicts_dict_lifetime.md) данных в кэше. Если от загрузки данных в ячейке прошло больше времени, чем `lifetime`, то значение не используется, и будет запрошено заново при следующей необходимости его использовать.
Это наименее эффективный из всех способов размещения словарей. Скорость работы кэша очень сильно зависит от правильности настройки и сценария использования. Словарь типа cache показывает высокую производительность лишь при достаточно больших hit rate-ах (рекомендуется 99% и выше). Посмотреть средний hit rate можно в таблице `system.dictionaries`.
Чтобы увеличить производительность кэша, используйте подзапрос с `LIMIT`, а снаружи вызывайте функцию со словарём.
Поддерживаются [источники](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources): MySQL, ClickHouse, executable, HTTP.
Поддерживаются [источники](external_dicts_dict_sources.md): MySQL, ClickHouse, executable, HTTP.
Пример настройки:
@ -224,7 +224,7 @@
### complex_key_cache
Тип размещения предназначен для использования с составными [ключами](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure). Аналогичен `cache`.
Тип размещения предназначен для использования с составными [ключами](external_dicts_dict_structure.md). Аналогичен `cache`.
<a name="dicts-external_dicts_dict_layout-ip_trie"></a>

View File

@ -33,7 +33,7 @@ ClickHouse периодически обновляет словари. Инте
</dictionary>
```
При обновлении словарей сервер ClickHouse применяет различную логику в зависимости от типа [источника](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources):
При обновлении словарей сервер ClickHouse применяет различную логику в зависимости от типа [источника](external_dicts_dict_sources.md):
> - У текстового файла проверяется время модификации. Если время изменилось по отношению к запомненному ранее, то словарь обновляется.
> - Для таблиц типа MyISAM, время модификации проверяется запросом `SHOW TABLE STATUS`.
@ -42,7 +42,7 @@ ClickHouse периодически обновляет словари. Инте
Для источников MySQL (InnoDB), ODBC и ClickHouse можно настроить запрос, который позволит обновлять словари только в случае их фактического изменения, а не каждый раз. Чтобы это сделать необходимо выполнить следующие условия/действия:
> - В таблице словаря должно быть поле, которое гарантированно изменяется при обновлении данных в источнике.
> - В настройках источника указывается запрос, который получает изменяющееся поле. Результат запроса сервер ClickHouse интерпретирует как строку и если эта строка изменилась по отношению к предыдущему состоянию, то словарь обновляется. Запрос следует указывать в поле `<invalidate_query>` настроек [источника](external_dicts_dict_sources.md#dicts-external_dicts_dict_sources).
> - В настройках источника указывается запрос, который получает изменяющееся поле. Результат запроса сервер ClickHouse интерпретирует как строку и если эта строка изменилась по отношению к предыдущему состоянию, то словарь обновляется. Запрос следует указывать в поле `<invalidate_query>` настроек [источника](external_dicts_dict_sources.md).
Пример настройки:

View File

@ -25,14 +25,14 @@
Типы источников (`source_type`):
- [Локальный файл](#dicts-external_dicts_dict_sources-local_file)
- [Исполняемый файл](#dicts-external_dicts_dict_sources-executable)
- [HTTP(s)](#dicts-external_dicts_dict_sources-http)
- [Локальный файл]()
- [Исполняемый файл]()
- [HTTP(s)]()
- СУБД:
- [ODBC](#dicts-external_dicts_dict_sources-odbc)
- [MySQL](#dicts-external_dicts_dict_sources-mysql)
- [ClickHouse](#dicts-external_dicts_dict_sources-clickhouse)
- [MongoDB](#dicts-external_dicts_dict_sources-mongodb)
- [ODBC]()
- [MySQL]()
- [ClickHouse]()
- [MongoDB]()
<a name="dicts-external_dicts_dict_sources-local_file"></a>
@ -58,7 +58,7 @@
## Исполняемый файл
Работа с исполняемым файлом зависит от [размещения словаря в памяти](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout). Если тип размещения словаря `cache` и `complex_key_cache`, то ClickHouse запрашивает необходимые ключи, отправляя запрос в `STDIN` исполняемого файла.
Работа с исполняемым файлом зависит от [размещения словаря в памяти](external_dicts_dict_layout.md). Если тип размещения словаря `cache` и `complex_key_cache`, то ClickHouse запрашивает необходимые ключи, отправляя запрос в `STDIN` исполняемого файла.
Пример настройки:
@ -80,7 +80,7 @@
## HTTP(s)
Работа с HTTP(s) сервером зависит от [размещения словаря в памяти](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout). Если тип размещения словаря `cache` и `complex_key_cache`, то ClickHouse запрашивает необходимые ключи, отправляя запрос методом `POST`.
Работа с HTTP(s) сервером зависит от [размещения словаря в памяти](external_dicts_dict_layout.md). Если тип размещения словаря `cache` и `complex_key_cache`, то ClickHouse запрашивает необходимые ключи, отправляя запрос методом `POST`.
Пример настройки:
@ -93,7 +93,7 @@
</source>
```
Чтобы ClickHouse смог обратиться к HTTPS-ресурсу, необходимо [настроить openSSL](../../operations/server_settings/settings.md#server_settings-openSSL) в конфигурации сервера.
Чтобы ClickHouse смог обратиться к HTTPS-ресурсу, необходимо [настроить openSSL](../../operations/server_settings/settings.md) в конфигурации сервера.
Поля настройки:
@ -122,7 +122,7 @@
- `db` - имя базы данных. Не указывать, если имя базы задано в параметрах. `<connection_string>`.
- `table` - имя таблицы и схемы, если она есть.
- `connection_string` - строка соединения.
- `invalidate_query` - запрос для проверки статуса словаря. Необязательный параметр. Читайте подробнее в разделе [Обновление словарей](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime).
- `invalidate_query` - запрос для проверки статуса словаря. Необязательный параметр. Читайте подробнее в разделе [Обновление словарей](external_dicts_dict_lifetime.md).
ClickHouse получает от ODBC-драйвера информацию о квотировании и квотирует настройки в запросах к драйверу, поэтому имя таблицы нужно указывать в соответствии с регистром имени таблицы в базе данных.
@ -344,7 +344,7 @@ SELECT * FROM odbc('DSN=gregtest;Servername=some-server.com', 'test_db');
- `db` - имя базы данных.
- `table` - имя таблицы.
- `where` - условие выбора. Необязательный параметр.
- `invalidate_query` - запрос для проверки статуса словаря. Необязательный параметр. Читайте подробнее в разделе [Обновление словарей](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime).
- `invalidate_query` - запрос для проверки статуса словаря. Необязательный параметр. Читайте подробнее в разделе [Обновление словарей](external_dicts_dict_lifetime.md).
MySQL можно подключить на локальном хосте через сокеты, для этого необходимо задать `host` и `socket`.
@ -387,14 +387,14 @@ MySQL можно подключить на локальном хосте чер
Поля настройки:
- `host` - хост ClickHouse. Если host локальный, то запрос выполняется без сетевого взаимодействия. Чтобы повысить отказоустойчивость решения, можно создать таблицу типа [Distributed](../../operations/table_engines/distributed.md#table_engines-distributed) и прописать её в дальнейших настройках.
- `host` - хост ClickHouse. Если host локальный, то запрос выполняется без сетевого взаимодействия. Чтобы повысить отказоустойчивость решения, можно создать таблицу типа [Distributed](../../operations/table_engines/distributed.md) и прописать её в дальнейших настройках.
- `port` - порт сервера ClickHouse.
- `user` - имя пользователя ClickHouse.
- `password` - пароль пользователя ClickHouse.
- `db` - имя базы данных.
- `table` - имя таблицы.
- `where` - условие выбора. Может отсутствовать.
- `invalidate_query` - запрос для проверки статуса словаря. Необязательный параметр. Читайте подробнее в разделе [Обновление словарей](external_dicts_dict_lifetime.md#dicts-external_dicts_dict_lifetime).
- `invalidate_query` - запрос для проверки статуса словаря. Необязательный параметр. Читайте подробнее в разделе [Обновление словарей](external_dicts_dict_lifetime.md).
<a name="dicts-external_dicts_dict_sources-mongodb"></a>

View File

@ -25,8 +25,8 @@
В структуре описываются столбцы:
- `<id>` - [ключевой столбец](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-key).
- `<attribute>` - [столбец данных](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-attributes). Столбцов может быть много.
- `<id>` - [ключевой столбец](external_dicts_dict_structure.md).
- `<attribute>` - [столбец данных](external_dicts_dict_structure.md). Столбцов может быть много.
<a name="dicts-external_dicts_dict_structure-key"></a>
@ -60,12 +60,12 @@ ClickHouse поддерживает следующие виды ключей:
### Составной ключ
Ключом может быть кортеж (`tuple`) из полей произвольных типов. [layout](external_dicts_dict_layout.md#dicts-external_dicts_dict_layout) в этом случае должен быть `complex_key_hashed` или `complex_key_cache`.
Ключом может быть кортеж (`tuple`) из полей произвольных типов. [layout](external_dicts_dict_layout.md) в этом случае должен быть `complex_key_hashed` или `complex_key_cache`.
!!! tip "Совет"
Cоставной ключ может состоять из одного элемента. Это даёт возможность использовать в качестве ключа, например, строку.
Структура ключа задаётся в элементе `<key>`. Поля ключа задаются в том же формате, что и [атрибуты](external_dicts_dict_structure.md#dicts-external_dicts_dict_structure-attributes) словаря. Пример:
Структура ключа задаётся в элементе `<key>`. Поля ключа задаются в том же формате, что и [атрибуты](external_dicts_dict_structure.md) словаря. Пример:
```xml
<structure>

Some files were not shown because too many files have changed in this diff Show More