Java-клиент
Клиентская библиотека Java для связи с сервером БД через его протоколы. Текущая реализация поддерживает только HTTP-интерфейс. Библиотека предоставляет собственный API для отправки запросов на сервер. Библиотека также предоставляет инструменты для работы с различными форматами бинарных данных (RowBinary* и Native*).
Установка
- Maven Central (project web page): https://mvnrepository.com/artifact/com.clickhouse/client-v2
- Nightly builds (repository link): https://central.sonatype.com/repository/maven-snapshots/
- Old Nightly builds artifactory (repository link): https://s01.oss.sonatype.org/content/repositories/snapshots/
- Maven
- Gradle (Kotlin)
- Gradle
Инициализация
Объект Client инициализируется методом com.clickhouse.client.api.Client.Builder#build(). Каждый клиент имеет свой собственный контекст, и объекты не разделяются между ними.
Builder имеет методы конфигурации для удобной настройки.
Пример:
Client реализует AutoCloseable и должен быть закрыт, когда больше не нужен.
Аутентификация
Аутентификация настраивается для каждого клиента на этапе инициализации. Поддерживаются три метода аутентификации: по паролю, по токену доступа, по SSL-сертификату клиента.
Аутентификация по паролю требует установки имени пользователя и пароля путем вызова setUsername(String) и setPassword(String):
Аутентификация по токену доступа требует установки токена доступа путем вызова setAccessToken(String):
Аутентификация по SSL-сертификату клиента требует установки имени пользователя, включения SSL-аутентификации, установки клиентского сертификата и клиентского ключа путем вызова методов setUsername(String), useSSLAuthentication(boolean), setClientCertificate(String) и setClientKey(String) соответственно:
SSL-аутентификацию может быть сложно диагностировать в продакшене, потому что многие ошибки из SSL-библиотек не предоставляют достаточно информации. Например, если клиентский сертификат и ключ не совпадают, сервер немедленно завершит соединение (в случае HTTP это будет этап инициации соединения, где HTTP-запросы еще не отправляются, поэтому ответ не отправляется).
Пожалуйста, используйте инструменты вроде openssl для проверки сертификатов и ключей:
- проверить целостность ключа:
openssl rsa -in [key-file.key] -check -noout - проверить, что клиентский сертификат имеет соответствующий CN для пользователя:
- получить CN из пользовательского сертификата -
openssl x509 -noout -subject -in [user.cert] - проверить, что то же значение установлено в базе данных
select name, auth_type, auth_params from system.users where auth_type = 'ssl_certificate'(запрос выведетauth_paramsс чем-то вроде{"common_names":["some_user"]})
- получить CN из пользовательского сертификата -
Конфигурация
Все настройки определяются методами экземпляра (также известными как методы конфигурации), которые делают область действия и контекст каждого значения понятными. Основные параметры конфигурации определены в одной области (клиент или операция) и не переопределяют друг друга.
Конфигурация определяется при создании клиента. См. com.clickhouse.client.api.Client.Builder.
Конфигурация клиента
- Соединение и конечные точки
- Аутентификация
- Тайм-ауты и повторы
- Socket Options
- Compression
- SSL/Security
- Proxy
- HTTP & Headers
- Server Settings
- Timezone
- Advanced
| Метод | Аргументы | Описание | По умолчанию | Ключ |
|---|---|---|---|---|
addEndpoint(String endpoint) | endpoint - адрес сервера в формате URL | Добавляет конечную точку сервера в список доступных серверов. В настоящее время поддерживается только одна конечная точка. | none | none |
addEndpoint(Protocol protocol, String host, int port, boolean secure) | protocol - протокол подключенияhost - IP или имя хостаsecure - использовать HTTPS | Добавляет конечную точку сервера в список доступных серверов. В настоящее время поддерживается только одна конечная точка. | none | none |
enableConnectionPool(boolean enable) | enable - флаг для включения/отключения | Устанавливает, включен ли пул соединений | true | connection_pool_enabled |
setMaxConnections(int maxConnections) | maxConnections - количество соединений | Устанавливает, сколько соединений может открыть клиент к каждой конечной точке сервера. | 10 | max_open_connections |
setConnectionTTL(long timeout, ChronoUnit unit) | timeout - значение тайм-аутаunit - единица времени | Устанавливает TTL соединения, после которого соединение будет считаться неактивным | -1 | connection_ttl |
setKeepAliveTimeout(long timeout, ChronoUnit unit) | timeout - значение тайм-аутаunit - единица времени | Устанавливает тайм-аут keep-alive HTTP-соединения. Установите 0, чтобы отключить Keep-Alive. | - | http_keep_alive_timeout |
setConnectionReuseStrategy(ConnectionReuseStrategy strategy) | strategy - LIFO или FIFO | Выбирает стратегию, которую должен использовать пул соединений | FIFO | connection_reuse_strategy |
setDefaultDatabase(String database) | database - имя базы данных | Устанавливает базу данных по умолчанию. | default | database |
| Метод | Аргументы | Описание | По умолчанию | Ключ |
|---|---|---|---|---|
setUsername(String username) | username - имя пользователя для аутентификации | Устанавливает имя пользователя для метода аутентификации, который выбирается дальнейшей конфигурацией | default | user |
setPassword(String password) | password - секретное значение | Устанавливает секрет для аутентификации по паролю и фактически выбирает этот метод аутентификации | - | password |
setAccessToken(String accessToken) | accessToken - строка токена доступа | Устанавливает токен доступа для аутентификации и соответствующий метод аутентификации | - | access_token |
useSSLAuthentication(boolean useSSLAuthentication) | useSSLAuthentication - флаг для включения SSL-аутентификации | Устанавливает SSL-сертификат клиента в качестве метода аутентификации. | - | ssl_authentication |
useHTTPBasicAuth(boolean useBasicAuth) | useBasicAuth - флаг для включения/отключения | Устанавливает, следует ли использовать базовую HTTP-аутентификацию для аутентификации пользователь-пароль. Решает проблемы с паролями, содержащими специальные символы. | true | http_use_basic_auth |
useBearerTokenAuth(String bearerToken) | bearerToken - закодированный bearer-токен | Указывает, использовать ли Bearer-аутентификацию и какой токен использовать. Токен будет отправлен как есть. | - | bearer_token |
| Метод | Аргументы | Описание | По умолчанию | Ключ |
|---|---|---|---|---|
setConnectTimeout(long timeout, ChronoUnit unit) | timeout - значение тайм-аутаunit - единица времени | Устанавливает тайм-аут инициации соединения для любого исходящего соединения. | - | connection_timeout |
setConnectionRequestTimeout(long timeout, ChronoUnit unit) | timeout - значение тайм-аутаunit - единица времени | Устанавливает тайм-аут запроса соединения. Это действует только для получения соединения из пула. | 10000 | connection_request_timeout |
setSocketTimeout(long timeout, ChronoUnit unit) | timeout - значение тайм-аутаunit - единица времени | Устанавливает тайм-аут сокета, который влияет на операции чтения и записи | 0 | socket_timeout |
setExecutionTimeout(long timeout, ChronoUnit timeUnit) | timeout - значение тайм-аутаtimeUnit - единица времени | Устанавливает максимальный тайм-аут выполнения для запросов | 0 | max_execution_time |
retryOnFailures(ClientFaultCause ...causes) | causes - константа enum ClientFaultCause | Устанавливает типы восстанавливаемых/повторяемых сбоев. | NoHttpResponse ConnectTimeout ConnectionRequestTimeout | client_retry_on_failures |
setMaxRetries(int maxRetries) | maxRetries - количество повторов | Устанавливает максимальное количество повторов для сбоев, определенных retryOnFailures | 3 | retry |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
setSocketRcvbuf(long size) | size - size in bytes | Sets TCP socket receive buffer. This buffer out of the JVM memory. | 8196 | socket_rcvbuf |
setSocketSndbuf(long size) | size - size in bytes | Sets TCP socket send buffer. This buffer out of the JVM memory. | 8196 | socket_sndbuf |
setSocketKeepAlive(boolean value) | value - flag to enable/disable | Sets option SO_KEEPALIVE for every TCP socket. TCP Keep Alive enables mechanism that will check liveness of the connection. | - | socket_keepalive |
setSocketTcpNodelay(boolean value) | value - flag to enable/disable | Sets option SO_NODELAY for every TCP socket. This TCP option will make socket to push data as soon as possible. | - | socket_tcp_nodelay |
setSocketLinger(int secondsToWait) | secondsToWait - number of seconds | Set linger time for every TCP socket created by the client. | - | socket_linger |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
compressServerResponse(boolean enabled) | enabled - flag to enable/disable | Sets if server should compress its responses. | true | compress |
compressClientRequest(boolean enabled) | enabled - flag to enable/disable | Sets if client should compress its requests. | false | decompress |
useHttpCompression(boolean enabled) | enabled - flag to enable/disable | Sets if HTTP compression should be used for client/server communications if corresponding options are enabled | - | - |
appCompressedData(boolean enabled) | enabled - flag to enable/disable | Tell client that compression will be handled by application. | false | app_compressed_data |
setLZ4UncompressedBufferSize(int size) | size - size in bytes | Sets size of a buffer that will receive uncompressed portion of a data stream. | 65536 | compression.lz4.uncompressed_buffer_size |
disableNativeCompression | disable - flag to disable | Disable native compression. If set to true then native compression will be disabled. | false | disable_native_compression |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
setSSLTrustStore(String path) | path - file path on local system | Sets if client should use SSL truststore for server host validation. | - | trust_store |
setSSLTrustStorePassword(String password) | password - secret value | Sets password to be used to unlock SSL truststore specified by setSSLTrustStore | - | key_store_password |
setSSLTrustStoreType(String type) | type - truststore type name | Sets type of the truststore specified by setSSLTrustStore. | - | key_store_type |
setRootCertificate(String path) | path - file path on local system | Sets if client should use specified root (CA) certificate for server host to validation. | - | sslrootcert |
setClientCertificate(String path) | path - file path on local system | Sets client certificate path to be used while initiating SSL connection and to be used by SSL authentication. | - | sslcert |
setClientKey(String path) | path - file path on local system | Sets client private key to be used for encrypting SSL communication with a server. | - | ssl_key |
sslSocketSNI(String sni) | sni - server name string | Sets server name to be used for SNI (Server Name Indication) in SSL/TLS connection. | - | ssl_socket_sni |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
addProxy(ProxyType type, String host, int port) | type - proxy typehost - proxy hostname or IPport - proxy port | Sets proxy to be used for communication with a server. | - | proxy_type, proxy_host, proxy_port |
setProxyCredentials(String user, String pass) | user - proxy usernamepass - password | Sets user credentials to authenticate with a proxy. | - | proxy_user, proxy_password |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
setHttpCookiesEnabled(boolean enabled) | enabled - flag to enable/disable | Set if HTTP cookies should be remembered and sent to server back. | - | - |
httpHeader(String key, String value) | key - HTTP header keyvalue - string value | Sets value for a single HTTP header. Previous value is overridden. | none | none |
httpHeader(String key, Collection values) | key - HTTP header keyvalues - list of string values | Sets values for a single HTTP header. Previous value is overridden. | none | none |
httpHeaders(Map headers) | headers - map with HTTP headers | Sets multiple HTTP header values at a time. | none | none |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
serverSetting(String name, String value) | name - setting namevalue - setting value | Sets what settings to pass to server along with each query. Individual operation settings may override it. List of settings | none | none |
serverSetting(String name, Collection values) | name - setting namevalues - setting values | Sets what settings to pass to server with multiple values, for example roles | none | none |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
useServerTimeZone(boolean useServerTimeZone) | useServerTimeZone - flag to enable/disable | Sets if client should use server timezone when decoding DateTime and Date column values. | true | use_server_time_zone |
useTimeZone(String timeZone) | timeZone - java valid timezone ID | Sets if specified timezone should be used when decoding DateTime and Date column values. Will override server timezone. | - | use_time_zone |
setServerTimeZone(String timeZone) | timeZone - java valid timezone ID | Sets server side timezone. UTC timezone will be used by default. | UTC | server_time_zone |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
setOption(String key, String value) | key - configuration option keyvalue - option value | Sets raw value of client options. Useful when reading configuration from properties files. | - | - |
useAsyncRequests(boolean async) | async - flag to enable/disable | Sets if client should execute request in a separate thread. Disabled by default because application knows better how to organize multi-threaded tasks. | false | async |
setSharedOperationExecutor(ExecutorService executorService) | executorService - executor service instance | Sets executor service for operation tasks. | none | none |
setClientNetworkBufferSize(int size) | size - size in bytes | Sets size of a buffer in application memory space that is used to copy data between socket and application. | 300000 | client_network_buffer_size |
allowBinaryReaderToReuseBuffers(boolean reuse) | reuse - flag to enable/disable | If enabled, reader will use preallocated buffers to do numbers transcoding. Reduces GC pressure for numeric data. | - | - |
columnToMethodMatchingStrategy(ColumnToMethodMatchingStrategy strategy) | strategy - matching strategy implementation | Sets custom strategy to be used for matching DTO class fields and DB columns when registering DTO. | none | none |
setClientName(String clientName) | clientName - application name string | Sets additional information about calling application. Will be passed as User-Agent header. | - | client_name |
registerClientMetrics(Object registry, String name) | registry - Micrometer registry instancename - metrics group name | Registers sensors with Micrometer (https://micrometer.io/) registry instance. | - | - |
setServerVersion(String version) | version - server version string | Sets server version to avoid version detection. | - | server_version |
typeHintMapping(Map typeHintMapping) | typeHintMapping - map of type hints | Sets type hint mapping for ClickHouse types. For example, to make multidimensional arrays be present as Java containers. | - | type_hint_mapping |
Server Settings
Server side settings can be set on the client level once while creation (see serverSetting method of the Builder) and on operation level (see serverSetting for operation settings class).
⚠️ When options are set via setOption method (either the Client.Builder or operation settings class) then server settings name should be prefixed with clickhouse_setting_. The com.clickhouse.client.api.ClientConfigProperties#serverSetting() may be handy in this case.
Custom HTTP Header
Custom HTTP headers can be set for all operations (client level) or a single one (operation level).
When options are set via setOption method (either the Client.Builder or operation settings class) then custom header name should be prefixed with http_header_. Method com.clickhouse.client.api.ClientConfigProperties#httpHeader() may be handy in this case.
Общие определения
ClickHouseFormat
Перечисление поддерживаемых форматов. Включает все форматы, которые поддерживает ClickHouse.
raw- пользователь должен перекодировать сырые данныеfull- клиент может перекодировать данные самостоятельно и принимает поток сырых данных-- операция не поддерживается ClickHouse для этого формата
Эта версия клиента поддерживает:
API для вставки
insert(String tableName, InputStream data, ClickHouseFormat format)
Принимает данные как InputStream байтов в указанном формате. Ожидается, что data закодированы в format.
Сигнатуры
Параметры
tableName - имя целевой таблицы.
data - входной поток закодированных данных.
format - формат, в котором закодированы данные.
settings - настройки запроса.
Возвращаемое значение
Future типа InsertResponse - результат операции и дополнительная информация, такая как метрики на стороне сервера.
Примеры
insert(String tableName, List<?> data, InsertSettings settings)
Sends a write request to database. The list of objects is converted into an efficient format and then is sent to a server. The class of the list items should be registered up-front using register(Class, TableSchema) method.
Signatures
Parameters
tableName - name of the target table.
data - collection DTO (Data Transfer Object) objects.
settings - request settings.
Return value
Future of InsertResponse type - the result of the operation and additional information like server side metrics.
Examples
InsertSettings
Configuration options for insert operations.
Configuration methods
| Method | Description |
|---|---|
setQueryId(String queryId) | Sets query ID that will be assigned to the operation. Default: null. |
setDeduplicationToken(String token) | Sets the deduplication token. This token will be sent to the server and can be used to identify the query. Default: null. |
setInputStreamCopyBufferSize(int size) | Copy buffer size. The buffer is used during write operations to copy data from user-provided input stream to an output stream. Default: 8196. |
serverSetting(String name, String value) | Sets individual server settings for an operation. |
serverSetting(String name, Collection values) | Sets individual server settings with multiple values for an operation. Items of the collection should be String values. |
setDBRoles(Collection dbRoles) | Sets DB roles to be set before executing an operation. Items of the collection should be String values. |
setOption(String option, Object value) | Sets a configuration option in raw format. This is not a server setting. |
InsertResponse
Response object that holds result of insert operation. It is only available if the client got response from a server.
This object should be closed as soon as possible to release a connection because the connection cannot be re-used until all data of previous response is fully read.
| Method | Description |
|---|---|
OperationMetrics getMetrics() | Returns object with operation metrics. |
String getQueryId() | Returns query ID assigned for the operation by the application (through operation settings or by server). |
API для запросов
query(String sqlQuery)
Отправляет sqlQuery как есть. Формат ответа задается настройками запроса. QueryResponse будет содержать ссылку на поток ответа, который должен быть обработан читателем для поддерживаемого формата.
Сигнатуры
Parameters
sqlQuery - a single SQL statement. The Query is sent as is to a server.
settings - request settings.
Return value
Future of QueryResponse type - a result dataset and additional information like server side metrics. The Response object should be closed after consuming the dataset.
Examples
query(String sqlQuery, Map<String, Object> queryParams, QuerySettings settings)
Sends sqlQuery as is. Additionally will send query parameters so the server can compile the SQL expression.
Signatures
Parameters
sqlQuery - sql expression with placeholders {}.
queryParams - map of variables to complete the sql expression on server.
settings - request settings.
Return value
Future of QueryResponse type - a result dataset and additional information like server side metrics. The Response object should be closed after consuming the dataset.
Examples
queryAll(String sqlQuery)
Queries a data in RowBinaryWithNamesAndTypes format. Returns the result as a collection. Read performance is the same as with the reader but more memory is required to hold the whole dataset.
Signatures
Parameters
sqlQuery - sql expression to query data from a server.
Return value
Complete dataset represented by a list of GenericRecord objects that provide access in row style for the result data.
Examples
QuerySettings
Configuration options for query operations.
Configuration methods
| Method | Description |
|---|---|
setQueryId(String queryId) | Sets query ID that will be assigned to the operation. |
setFormat(ClickHouseFormat format) | Sets response format. See RowBinaryWithNamesAndTypes for the full list. |
setMaxExecutionTime(Integer maxExecutionTime) | Sets operation execution time on server. Will not affect read timeout. |
waitEndOfQuery(Boolean waitEndOfQuery) | Requests the server to wait for the end of the query before sending a response. |
setUseServerTimeZone(Boolean useServerTimeZone) | Server timezone (see client config) will be used to parse date/time types in the result of an operation. Default false. |
setUseTimeZone(String timeZone) | Requests server to use timeZone for time conversion. See session_timezone. |
serverSetting(String name, String value) | Sets individual server settings for an operation. |
serverSetting(String name, Collection values) | Sets individual server settings with multiple values for an operation. Items of the collection should be String values. |
setDBRoles(Collection dbRoles) | Sets DB roles to be set before executing an operation. Items of the collection should be String values. |
setOption(String option, Object value) | Sets a configuration option in raw format. This is not a server setting. |
QueryResponse
Response object that holds result of query execution. It is only available if the client got a response from a server.
This object should be closed as soon as possible to release a connection because the connection cannot be re-used until all data of previous response is fully read.
| Method | Description |
|---|---|
ClickHouseFormat getFormat() | Returns a format in which data in the response is encoded. |
InputStream getInputStream() | Returns uncompressed byte stream of data in the specified format. |
OperationMetrics getMetrics() | Returns object with operation metrics. |
String getQueryId() | Returns query ID assigned for the operation by the application (through operation settings or by server). |
TimeZone getTimeZone() | Returns timezone that should be used for handling Date/DateTime types in the response. |
Examples
- Example code is available in repo
- Reference Spring Service implementation
Common API
getTableSchema(String table)
Fetches table schema for the table.
Signatures
Parameters
table - table name for which schema data should be fetched.
database - database where the target table is defined.
Return value
Returns a TableSchema object with list of table columns.
getTableSchemaFromQuery(String sql)
Fetches schema from a SQL statement.
Signatures
Parameters
sql - "SELECT" SQL statement which schema should be returned.
Return value
Returns a TableSchema object with columns matching the sql expression.
TableSchema
register(Class<?> clazz, TableSchema schema)
Compiles serialization and deserialization layer for the Java Class to use for writing/reading data with schema. The method will create a serializer and deserializer for the pair getter/setter and corresponding column.
Column match is found by extracting its name from a method name. For example, getFirstName will be for the column first_name or firstname.
Signatures
Parameters
clazz - Class representing the POJO used to read/write data.
schema - Data schema to use for matching with POJO properties.
Examples
Примеры использования
Полный код примеров хранится в репозитории в папке 'example':
- client-v2 - основной набор примеров.
- demo-service - пример использования клиента в приложении Spring Boot.
- demo-kotlin-service - пример использования клиента в приложении Ktor (Kotlin).
Руководство по миграции
Old client (V1) was using com.clickhouse.client.ClickHouseClient#builder as start point. The new client (V2) uses similar pattern with com.clickhouse.client.api.Client.Builder. Main
differences are:
- no service loader is used to grab implementation. The
com.clickhouse.client.api.Clientis facade class for all kinds of implementation in the future. - a fewer sources of configuration: one is provided to the builder and one is with operation settings (
QuerySettings,InsertSettings). Previous version had configuration per node and was loading env. variables in some cases.
Configuration Parameters Match
There are 3 enum classes related to configuration in V1:
com.clickhouse.client.config.ClickHouseDefaults- configuration parameters that supposed to be set in most use cases. LikeUSERandPASSWORD.com.clickhouse.client.config.ClickHouseClientOption- configuration parameters specific for the client. LikeHEALTH_CHECK_INTERVAL.com.clickhouse.client.http.config.ClickHouseHttpOption- configuration parameters specific for HTTP interface. LikeRECEIVE_QUERY_PROGRESS.
They were designed to group parameters and provide clear separation. However in some cases it lead to a confusion (is there a difference between com.clickhouse.client.config.ClickHouseDefaults#ASYNC and
com.clickhouse.client.config.ClickHouseClientOption#ASYNC). The new V2 client uses com.clickhouse.client.api.Client.Builder as single dictionary of all possible client configuration options.There is
com.clickhouse.client.api.ClientConfigProperties where all configuration parameter names are listed.
Table below shows what old options are supported in the new client and their new meaning.
Legend: ✔ = supported, ✗ = dropped
- Connection & Auth
- SSL & Security
- Socket Options
- Compression
- Proxy
- Timeouts & Retry
- Timezone
- Buffers & Performance
- Threading & Async
- HTTP & Headers
- Format & Query
- Node Discovery & Load Balancing
- Miscellaneous
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseDefaults#HOST | Client.Builder#addEndpoint | |
ClickHouseDefaults#PROTOCOL | ✗ | Only HTTP supported in V2 |
ClickHouseDefaults#DATABASEClickHouseClientOption#DATABASE | Client.Builder#setDefaultDatabase | |
ClickHouseDefaults#USER | Client.Builder#setUsername | |
ClickHouseDefaults#PASSWORD | Client.Builder#setPassword | |
ClickHouseClientOption#CONNECTION_TIMEOUT | Client.Builder#setConnectTimeout | |
ClickHouseClientOption#CONNECTION_TTL | Client.Builder#setConnectionTTL | |
ClickHouseHttpOption#MAX_OPEN_CONNECTIONS | Client.Builder#setMaxConnections | |
ClickHouseHttpOption#KEEP_ALIVEClickHouseHttpOption#KEEP_ALIVE_TIMEOUT | Client.Builder#setKeepAliveTimeout | |
ClickHouseHttpOption#CONNECTION_REUSE_STRATEGY | Client.Builder#setConnectionReuseStrategy | |
ClickHouseHttpOption#USE_BASIC_AUTHENTICATION | Client.Builder#useHTTPBasicAuth |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseDefaults#SSL_CERTIFICATE_TYPE | ✗ | |
ClickHouseDefaults#SSL_KEY_ALGORITHM | ✗ | |
ClickHouseDefaults#SSL_PROTOCOL | ✗ | |
ClickHouseClientOption#SSL | ✗ | See Client.Builder#addEndpoint |
ClickHouseClientOption#SSL_MODE | ✗ | |
ClickHouseClientOption#SSL_ROOT_CERTIFICATE | Client.Builder#setRootCertificate | SSL Auth should be enabled by useSSLAuthentication |
ClickHouseClientOption#SSL_CERTIFICATE | Client.Builder#setClientCertificate | |
ClickHouseClientOption#SSL_KEY | Client.Builder#setClientKey | |
ClickHouseClientOption#KEY_STORE_TYPE | Client.Builder#setSSLTrustStoreType | |
ClickHouseClientOption#TRUST_STORE | Client.Builder#setSSLTrustStore | |
ClickHouseClientOption#KEY_STORE_PASSWORD | Client.Builder#setSSLTrustStorePassword | |
ClickHouseClientOption#SSL_SOCKET_SNI | Client.Builder#sslSocketSNI | |
ClickHouseClientOption#CUSTOM_SOCKET_FACTORY | ✗ | |
ClickHouseClientOption#CUSTOM_SOCKET_FACTORY_OPTIONS | ✗ | See Client.Builder#sslSocketSNI to set SNI |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseClientOption#SOCKET_TIMEOUT | Client.Builder#setSocketTimeout | |
ClickHouseClientOption#SOCKET_REUSEADDR | Client.Builder#setSocketReuseAddress | |
ClickHouseClientOption#SOCKET_KEEPALIVE | Client.Builder#setSocketKeepAlive | |
ClickHouseClientOption#SOCKET_LINGER | Client.Builder#setSocketLinger | |
ClickHouseClientOption#SOCKET_IP_TOS | ✗ | |
ClickHouseClientOption#SOCKET_TCP_NODELAY | Client.Builder#setSocketTcpNodelay | |
ClickHouseClientOption#SOCKET_RCVBUF | Client.Builder#setSocketRcvbuf | |
ClickHouseClientOption#SOCKET_SNDBUF | Client.Builder#setSocketSndbuf |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseClientOption#COMPRESS | Client.Builder#compressServerResponse | See also useHttpCompression |
ClickHouseClientOption#DECOMPRESS | Client.Builder#compressClientRequest | See also useHttpCompression |
ClickHouseClientOption#COMPRESS_ALGORITHM | ✗ | LZ4 for non-http. Http uses Accept-Encoding |
ClickHouseClientOption#DECOMPRESS_ALGORITHM | ✗ | LZ4 for non-http. Http uses Content-Encoding |
ClickHouseClientOption#COMPRESS_LEVEL | ✗ | |
ClickHouseClientOption#DECOMPRESS_LEVEL | ✗ |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseClientOption#PROXY_TYPE | Client.Builder#addProxy | |
ClickHouseClientOption#PROXY_HOST | Client.Builder#addProxy | |
ClickHouseClientOption#PROXY_PORT | Client.Builder#addProxy | |
ClickHouseClientOption#PROXY_USERNAME | Client.Builder#setProxyCredentials | |
ClickHouseClientOption#PROXY_PASSWORD | Client.Builder#setProxyCredentials |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseClientOption#MAX_EXECUTION_TIME | Client.Builder#setExecutionTimeout | |
ClickHouseClientOption#RETRY | Client.Builder#setMaxRetries | See also retryOnFailures |
ClickHouseHttpOption#AHC_RETRY_ON_FAILURE | Client.Builder#retryOnFailures | |
ClickHouseClientOption#FAILOVER | ✗ | |
ClickHouseClientOption#REPEAT_ON_SESSION_LOCK | ✗ | |
ClickHouseClientOption#SESSION_ID | ✗ | |
ClickHouseClientOption#SESSION_CHECK | ✗ | |
ClickHouseClientOption#SESSION_TIMEOUT | ✗ |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseDefaults#SERVER_TIME_ZONEClickHouseClientOption#SERVER_TIME_ZONE | Client.Builder#setServerTimeZone | |
ClickHouseClientOption#USE_SERVER_TIME_ZONE | Client.Builder#useServerTimeZone | |
ClickHouseClientOption#USE_SERVER_TIME_ZONE_FOR_DATES | ||
ClickHouseClientOption#USE_TIME_ZONE | Client.Builder#useTimeZone |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseClientOption#BUFFER_SIZE | Client.Builder#setClientNetworkBufferSize | |
ClickHouseClientOption#BUFFER_QUEUE_VARIATION | ✗ | |
ClickHouseClientOption#READ_BUFFER_SIZE | ✗ | |
ClickHouseClientOption#WRITE_BUFFER_SIZE | ✗ | |
ClickHouseClientOption#REQUEST_CHUNK_SIZE | ✗ | |
ClickHouseClientOption#REQUEST_BUFFERING | ✗ | |
ClickHouseClientOption#RESPONSE_BUFFERING | ✗ | |
ClickHouseClientOption#MAX_BUFFER_SIZE | ✗ | |
ClickHouseClientOption#MAX_QUEUED_BUFFERS | ✗ | |
ClickHouseClientOption#MAX_QUEUED_REQUESTS | ✗ | |
ClickHouseClientOption#REUSE_VALUE_WRAPPER | ✗ |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseDefaults#ASYNCClickHouseClientOption#ASYNC | Client.Builder#useAsyncRequests | |
ClickHouseDefaults#MAX_SCHEDULER_THREADS | ✗ | see setSharedOperationExecutor |
ClickHouseDefaults#MAX_THREADS | ✗ | see setSharedOperationExecutor |
ClickHouseDefaults#THREAD_KEEPALIVE_TIMEOUT | see setSharedOperationExecutor | |
ClickHouseClientOption#MAX_THREADS_PER_CLIENT | ✗ | |
ClickHouseClientOption#MAX_CORE_THREAD_TTL | ✗ |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseHttpOption#CUSTOM_HEADERS | Client.Builder#httpHeaders | |
ClickHouseHttpOption#CUSTOM_PARAMS | ✗ | See Client.Builder#serverSetting |
ClickHouseClientOption#CLIENT_NAME | Client.Builder#setClientName | |
ClickHouseHttpOption#CONNECTION_PROVIDER | ✗ | |
ClickHouseHttpOption#DEFAULT_RESPONSE | ✗ | |
ClickHouseHttpOption#SEND_HTTP_CLIENT_ID | ✗ | |
ClickHouseHttpOption#AHC_VALIDATE_AFTER_INACTIVITY | ✗ | Always enabled when Apache Http Client is used |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseDefaults#FORMATClickHouseClientOption#FORMAT | ✗ | Moved to operation settings (QuerySettings and InsertSettings) |
ClickHouseClientOption#QUERY_ID | ✗ | See QuerySettings and InsertSettings |
ClickHouseClientOption#LOG_LEADING_COMMENT | ✗ | See QuerySettings#logComment and InsertSettings#logComment |
ClickHouseClientOption#MAX_RESULT_ROWS | ✗ | Is server side setting |
ClickHouseClientOption#RESULT_OVERFLOW_MODE | ✗ | Is server side setting |
ClickHouseHttpOption#RECEIVE_QUERY_PROGRESS | ✗ | Server side setting |
ClickHouseHttpOption#WAIT_END_OF_QUERY | ✗ | Server side setting |
ClickHouseHttpOption#REMEMBER_LAST_SET_ROLES | Client#setDBRoles | Runtime config now. See also QuerySettings#setDBRoles and InsertSettings#setDBRoles |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseClientOption#AUTO_DISCOVERY | ✗ | |
ClickHouseClientOption#LOAD_BALANCING_POLICY | ✗ | |
ClickHouseClientOption#LOAD_BALANCING_TAGS | ✗ | |
ClickHouseClientOption#HEALTH_CHECK_INTERVAL | ✗ | |
ClickHouseClientOption#HEALTH_CHECK_METHOD | ✗ | |
ClickHouseClientOption#NODE_DISCOVERY_INTERVAL | ✗ | |
ClickHouseClientOption#NODE_DISCOVERY_LIMIT | ✗ | |
ClickHouseClientOption#NODE_CHECK_INTERVAL | ✗ | |
ClickHouseClientOption#NODE_GROUP_SIZE | ✗ | |
ClickHouseClientOption#CHECK_ALL_NODES | ✗ |
| V1 Configuration | V2 Builder Method | Comments |
|---|---|---|
ClickHouseDefaults#AUTO_SESSION | ✗ | Session support will be reviewed |
ClickHouseDefaults#BUFFERING | ✗ | |
ClickHouseDefaults#MAX_REQUESTS | ✗ | |
ClickHouseDefaults#ROUNDING_MODE | ||
ClickHouseDefaults#SERVER_VERSIONClickHouseClientOption#SERVER_VERSION | Client.Builder#setServerVersion | |
ClickHouseDefaults#SRV_RESOLVE | ✗ | |
ClickHouseClientOption#CUSTOM_SETTINGS | ||
ClickHouseClientOption#PRODUCT_NAME | ✗ | Use client name |
ClickHouseClientOption#RENAME_RESPONSE_COLUMN | ✗ | |
ClickHouseClientOption#SERVER_REVISION | ✗ | |
ClickHouseClientOption#TRANSACTION_TIMEOUT | ✗ | |
ClickHouseClientOption#WIDEN_UNSIGNED_TYPES | ✗ | |
ClickHouseClientOption#USE_BINARY_STRING | ✗ | |
ClickHouseClientOption#USE_BLOCKING_QUEUE | ✗ | |
ClickHouseClientOption#USE_COMPILATION | ✗ | |
ClickHouseClientOption#USE_OBJECTS_IN_ARRAYS | ✗ | |
ClickHouseClientOption#MAX_MAPPER_CACHE | ✗ | |
ClickHouseClientOption#MEASURE_REQUEST_TIME | ✗ |
General Differences
- Client V2 uses less proprietary classes to increase portability. For example, V2 works with any implementation of
java.io.InputStreamfor writing data to a server. - Client V2
asyncsettings isoffby default. It means no extra threads and more application control over client. This setting should beofffor majority of use cases. Enablingasyncwill create a separate thread for a request. It only make sense when using application controlled executor (seecom.clickhouse.client.api.Client.Builder#setSharedOperationExecutor)
Writing Data
- use any implementation of
java.io.InputStream. V1com.clickhouse.data.ClickHouseInputStreamis supported but NOT recommended. - once end of input stream is detected it handled accordingly. Previously output stream of a request should be closed.
V1 Insert TSV formatted data.
V2 Insert TSV formatted data.
- there is a single method to call. No need to create an additional request object.
- request body stream is closed automatically when all data is copied.
- new low-level API is available
com.clickhouse.client.api.Client#insert(java.lang.String, java.util.List<java.lang.String>, com.clickhouse.client.api.DataStreamWriter, com.clickhouse.data.ClickHouseFormat, com.clickhouse.client.api.insert.InsertSettings).com.clickhouse.client.api.DataStreamWriteris designed to implement custom data writing logic. For instance, reading data from a queue.
Reading Data
- Data is read in
RowBinaryWithNamesAndTypesformat by default. Currently only this format is supported when data binding is required. - Data can be read as a collection of records using
List<GenericRecord> com.clickhouse.client.api.Client#queryAll(java.lang.String)method. It will read data to a memory and release connection. No need for extra handling.GenericRecordgives access to data, implements some conversions.