Java Client
Java client library to communicate with a DB server through its protocols. The current implementation only supports the HTTP interface. The library provides its own API to send requests to a server. The library also provides tools to work with different binary data formats (RowBinary* & Native*).
Setup
- 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
Initialization
The Client object is initialized by com.clickhouse.client.api.Client.Builder#build(). Each client has its own context and no objects are shared between them.
The Builder has configuration methods for convenient setup.
Example:
Client is AutoCloseable and should be closed when not needed anymore.
Authentication
Authentication is configured per client at the initialization phase. There are three authentication methods supported: by password, by access token, by SSL Client Certificate.
Authentication by a password requires setting user name password by calling setUsername(String) and setPassword(String):
Authentication by an access token requires setting access token by calling setAccessToken(String):
Authentication by a SSL Client Certificate require setting username, enabling SSL Authentication, setting a client certificate and a client key by calling setUsername(String), useSSLAuthentication(boolean), setClientCertificate(String) and setClientKey(String) accordingly:
SSL Authentication may be hard to troubleshoot on production because many errors from SSL libraries provide not enough information. For example, if client certificate and key do not match then server will terminate connection immediately (in case of HTTP it will be connection initiation stage where no HTTP requests are send so no response is sent).
Please use tools like openssl to verify certificates and keys:
- check key integrity:
openssl rsa -in [key-file.key] -check -noout - check client certificate has matching CN for a user:
- get CN from an user certificate -
openssl x509 -noout -subject -in [user.cert] - verify same value is set in database
select name, auth_type, auth_params from system.users where auth_type = 'ssl_certificate'(query will outputauth_paramswith something like{"common_names":["some_user"]})
- get CN from an user certificate -
Configuration
All settings are defined by instance methods (a.k.a configuration methods) that make the scope and context of each value clear. Major configuration parameters are defined in one scope (client or operation) and do not override each other.
Configuration is defined during client creation. See com.clickhouse.client.api.Client.Builder.
Client Configuration
- Connection & Endpoints
- Authentication
- Timeouts & Retry
- Socket Options
- Compression
- SSL/Security
- Proxy
- HTTP & Headers
- Server Settings
- Timezone
- Advanced
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
addEndpoint(String endpoint) | endpoint - URL formatted server address | Adds a server endpoint to list of available servers. Currently only one endpoint is supported. | none | none |
addEndpoint(Protocol protocol, String host, int port, boolean secure) | protocol - connection protocolhost - IP or hostnamesecure - use HTTPS | Adds a server endpoint to list of available servers. Currently only one endpoint is supported. | none | none |
enableConnectionPool(boolean enable) | enable - flag to enable/disable | Sets if a connection pool is enabled | true | connection_pool_enabled |
setMaxConnections(int maxConnections) | maxConnections - number of connections | Sets how many connections can a client open to each server endpoint. | 10 | max_open_connections |
setConnectionTTL(long timeout, ChronoUnit unit) | timeout - timeout valueunit - time unit | Sets connection TTL after which connection will be considered as not active | -1 | connection_ttl |
setKeepAliveTimeout(long timeout, ChronoUnit unit) | timeout - timeout valueunit - time unit | Sets HTTP connection keep-alive timeout. Set to 0 to disable Keep-Alive. | - | http_keep_alive_timeout |
setConnectionReuseStrategy(ConnectionReuseStrategy strategy) | strategy - LIFO or FIFO | Selects which strategy connection pool should use | FIFO | connection_reuse_strategy |
setDefaultDatabase(String database) | database - name of a database | Sets default database. | default | database |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
setUsername(String username) | username - username for authentication | Sets username for an authentication method that is selected by further configuration | default | user |
setPassword(String password) | password - secret value | Sets a secret for password authentication and effectively selects as authentication method | - | password |
setAccessToken(String accessToken) | accessToken - access token string | Sets an access token to authenticate with a sets corresponding authentication method | - | access_token |
useSSLAuthentication(boolean useSSLAuthentication) | useSSLAuthentication - flag to enable SSL auth | Sets SSL Client Certificate as an authentication method. | - | ssl_authentication |
useHTTPBasicAuth(boolean useBasicAuth) | useBasicAuth - flag to enable/disable | Sets if basic HTTP authentication should be used for user-password authentication. Resolves issues with passwords containing special characters. | true | http_use_basic_auth |
useBearerTokenAuth(String bearerToken) | bearerToken - an encoded bearer token | Specifies whether to use Bearer Authentication and what token to use. The token will be sent as is. | - | bearer_token |
| Method | Arguments | Description | Default | Key |
|---|---|---|---|---|
setConnectTimeout(long timeout, ChronoUnit unit) | timeout - timeout valueunit - time unit | Sets connection initiation timeout for any outgoing connection. | - | connection_timeout |
setConnectionRequestTimeout(long timeout, ChronoUnit unit) | timeout - timeout valueunit - time unit | Sets connection request timeout. This take effect only for getting connection from a pool. | 10000 | connection_request_timeout |
setSocketTimeout(long timeout, ChronoUnit unit) | timeout - timeout valueunit - time unit | Sets socket timeout that affects read and write operations | 0 | socket_timeout |
setExecutionTimeout(long timeout, ChronoUnit timeUnit) | timeout - timeout valuetimeUnit - time unit | Sets maximum execution timeout for queries | 0 | max_execution_time |
retryOnFailures(ClientFaultCause ...causes) | causes - enum constant of ClientFaultCause | Sets recoverable/retriable fault types. | NoHttpResponse,ConnectTimeout,ConnectionRequestTimeout | client_retry_on_failures |
setMaxRetries(int maxRetries) | maxRetries - number of retries | Sets maximum number of retries for failures defined by 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.
Common Definitions
ClickHouseFormat
Enum of supported formats. It includes all formats that ClickHouse supports.
raw- user should transcode raw datafull- the client can transcode data by itself and accepts a raw data stream-- operation not supported by ClickHouse for this format
This client version supports:
Insert API
insert(String tableName, InputStream data, ClickHouseFormat format)
Accepts data as an InputStream of bytes in the specified format. It is expected that data is encoded in the format.
Signatures
Parameters
tableName - a target table name.
data - an input stream of an encoded data.
format - a format in which the data is encoded.
settings - request settings.
Return value
Future of InsertResponse type - result of the operation and additional information like server side metrics.
Examples
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). |
Query API
query(String sqlQuery)
Sends sqlQuery as is. Response format is set by query settings. QueryResponse will hold a reference to the response stream that should be consumed by a reader for the supportig format.
Signatures
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
Usage Examples
Complete examples code is stored in the repo in a 'example` folder:
- client-v2 - main set of examples.
- demo-service - example of how to use the client in a Spring Boot application.
- demo-kotlin-service - example of how to use the client in Ktor (Kotlin) application.
Migration From V1 ( =< 0.7.x )
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.
- 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.