Inserting data with ClickHouse Connect: Advanced usage
InsertContexts
ClickHouse Connect executes Native-format inserts, theinsert and insert_df methods, within an InsertContext. The insert_arrow, insert_df_arrow, and raw_insert methods send their payloads directly and don’t use one. The InsertContext includes all the values sent as arguments to the client insert method. In addition, when an InsertContext is originally constructed, ClickHouse Connect retrieves the data types for the insert columns required for efficient Native format inserts. By reusing the InsertContext for multiple inserts, this “pre-query” is avoided and inserts are executed more quickly and efficiently.
An InsertContext can be acquired using the client create_insert_context method. The method takes the same arguments as the insert function, except for context itself. Note that only the data property of InsertContexts should be modified for reuse. This is consistent with its intended purpose of providing a reusable object for repeated inserts of new data to the same table.
InsertContexts include mutable state that is updated during the insert process, so they’re not thread safe.
Write formats
Write formats are implemented for a limited number of types. In most cases ClickHouse Connect automatically determines the correct write format for a column from its first non-null data value. For example, when the first value for aDateTime column is an integer, the client treats it as an epoch second.
It is normally unnecessary to override a write format, but the methods in clickhouse_connect.datatypes.format can set one globally. Container wrappers such as Array, Nullable, and LowCardinality preserve the element type’s formatting behavior.
Write format options
Specialized insert methods
ClickHouse Connect provides specialized insert methods for common data formats:insert_df— Insert a Pandas DataFrame as column-oriented Native data. It also supports explicit column names/types or a reusableInsertContext.insert_arrow— Insert a PyArrow Table using the ClickHouse Arrow input format.insert_df_arrow— Insert an Arrow-backed Pandas DataFrame or a Polars DataFrame. Pandas columns must all use Arrow-backed dtypes.
database, settings, and per-request HTTP transport_settings.
A NumPy array is a valid Sequence of Sequences and can be used as the
data argument to the main insert method, so a specialized method isn’t required.Pandas DataFrame insert
PyArrow Table insert
Arrow-backed DataFrame insert (pandas 2.x)
Create a table from a PyArrow schema
create_table_from_arrow_schema builds a CREATE TABLE statement from common scalar Arrow fields. The mapping covers signed and unsigned integers, floating-point values, booleans, strings, dates, and timestamps. It intentionally creates non-nullable ClickHouse columns and raises TypeError for unsupported Arrow types, so review the generated DDL before executing it.
Time zones
When inserting Pythondatetime objects into DateTime or DateTime64 columns, ClickHouse Connect converts them to epoch values.
Timezone-aware datetime objects
Timezone-aware objects preserve the represented instant. The source timezone does not need to match the timezone declared on the ClickHouse column.ClickHouse Connect uses the standard library
zoneinfo module. The driver no longer depends on pytz.Timezone-naive datetime objects
The globalnaive_datetime_insert setting controls native Python object inserts of naive datetime values. It also applies to naive ISO strings accepted by DateTime64 columns.
"local"is the default in 1.x. Python interprets the value in the process timezone when.timestamp()is called. This preserves the existing behavior."server"interprets the value as wall time in the timezone declared by theDateTimeorDateTime64column. If the column has no timezone, it uses the server timezone reported when the client connected.
datetime objects or DateTime64 ISO strings is serialized, so the change applies to existing clients and reusable insert contexts.
"server", ClickHouse Connect attaches the target tzinfo before converting the value to an epoch. For IANA time zones, it follows the standard library rules for daylight saving transitions. A fall overlap uses the datetime’s fold value. The default fold=0 selects the offset before the transition, while fold=1 selects the offset after it. A spring gap uses the same offset selection and is not rejected or normalized.
Nonexistent spring gap wall times may not round trip through a wall-mode query parameter because ClickHouse text parsing can select a different offset. Use an aware datetime or a valid wall time when the instant matters.
The option only applies to native Python object inserts of datetime values and naive ISO strings accepted by DateTime64. Naive datetime64-dtype NumPy and Pandas columns keep their existing UTC wall time conversion.
To represent a specific instant independent of either mode, attach the intended timezone or provide an epoch integer explicitly.
datetime query parameters use the separate naive_datetime_binding setting. Its default "wall" mode sends the wall fields without host-local conversion. See the Parameters argument section.
DateTime columns with timezone metadata
ClickHouse columns can declare timezone metadata, for exampleDateTime('America/Denver') or DateTime64(3, 'Asia/Tokyo'). The metadata controls how values are presented when queried.
When inserting a timezone-aware value, ClickHouse Connect preserves the represented instant. For a naive value, the naive_datetime_insert setting controls whether the process timezone or column timezone is used. When queried, the result uses the column timezone unless a per-column override is supplied with the column_tzs argument. The query_tz argument doesn’t override a column’s declared timezone.
File inserts
clickhouse_connect.driver.tools.insert_file streams a local file into an existing table and delegates parsing to ClickHouse.
Input-format settings such as
input_format_allow_errors_ratio and input_format_allow_errors_num can be passed through settings.
AsyncClient, await insert_file_async with the same arguments:
raw_insert, so the file contents are held in memory.