Java Client

## Insert API[​](#insert-api "Direct link to Insert API")

### insert(String tableName, InputStream data, ClickHouseFormat format)[​](#insertstring-tablename-inputstream-data-clickhouseformat-format "Direct link to 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**

```
CompletableFuture<InsertResponse> insert(String tableName, InputStream data, ClickHouseFormat format, InsertSettings settings)
CompletableFuture<InsertResponse> insert(String tableName, InputStream data, ClickHouseFormat format)
```

**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**

```
try (InputStream dataStream = getDataStream()) {
    try (InsertResponse response = client.insert(TABLE_NAME, dataStream, ClickHouseFormat.JSONEachRow,
            insertSettings).get(3, TimeUnit.SECONDS)) {

        log.info("Insert finished: {} rows written", response.getMetrics().getMetric(ServerMetrics.NUM_ROWS_WRITTEN).getLong());
    } catch (Exception e) {
        log.error("Failed to write JSONEachRow data", e);
        throw new RuntimeException(e);
    }
}
```

### insert(String tableName, List<?> data, InsertSettings settings)[​](#insertstring-tablename-listlt-data-insertsettings-settings "Direct link to 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**

```
client.insert(String tableName, List<?> data, InsertSettings settings)
client.insert(String tableName, List<?> data)
```

**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**

```
// Important step (done once) - register class to pre-compile object serializer according to the table schema.
client.register(ArticleViewEvent.class, client.getTableSchema(TABLE_NAME));

List<ArticleViewEvent> events = loadBatch();

try (InsertResponse response = client.insert(TABLE_NAME, events).get()) {
    // handle response, then it will be closed and connection that served request will be released.
}
```

### InsertSettings[​](#insertsettings "Direct link to 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 isn't a server setting. | | | | | | | | | | | | | | | |

### InsertResponse[​](#insertresponse "Direct link to InsertResponse")

Response object that holds result of insert operation. It is only available if the client got response from a server.

Note

This object should be closed as soon as possible to release a connection because the connection can't 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-api "Direct link to Query API")

### query(String sqlQuery)[​](#querystring-sqlquery "Direct link to 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**

```
CompletableFuture<QueryResponse> query(String sqlQuery, QuerySettings settings)
CompletableFuture<QueryResponse> query(String sqlQuery)
```

**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**

```
final String sql = "select * from " + TABLE_NAME + " where title <> '' limit 10";

// Default format is RowBinaryWithNamesAndTypesFormatReader so reader have all information about columns
try (QueryResponse response = client.query(sql).get(3, TimeUnit.SECONDS);) {

    // Create a reader to access the data in a convenient way
    ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response);

    while (reader.hasNext()) {
        reader.next(); // Read the next record from stream and parse it

        // get values
        double id = reader.getDouble("id");
        String title = reader.getString("title");
        String url = reader.getString("url");

        // collecting data
    }
} catch (Exception e) {
    log.error("Failed to read data", e);
}

// put business logic outside of the reading block to release http connection asap.
```

### query(String sqlQuery, Map<String, Object> queryParams, QuerySettings settings)[​](#querystring-sqlquery-mapltstring-object-queryparams-querysettings-settings "Direct link to 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**

```
CompletableFuture<QueryResponse> query(String sqlQuery, Map<String, Object> queryParams, QuerySettings settings)
```

**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**

```
// define parameters. They will be sent to the server along with the request.
Map<String, Object> queryParams = new HashMap<>();
queryParams.put("param1", 2);

try (QueryResponse response =
        client.query("SELECT * FROM " + table + " WHERE col1 >= {param1:UInt32}", queryParams, new QuerySettings()).get()) {

    // Create a reader to access the data in a convenient way
    ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response);

    while (reader.hasNext()) {
        reader.next(); // Read the next record from stream and parse it

        // reading data
    }