Inserting data with ClickHouse Connect: Advanced usage
InsertContexts
ClickHouse Connect executes all inserts within anInsertContext. 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. 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 currently implemented for limited number of types. In most cases ClickHouse Connect will attempt to automatically determine the correct write format for a column by checking the type of the first (non-null) data value. For example, if inserting into aDateTime column, and the first insert value of the column is a Python integer, ClickHouse Connect will directly insert the integer value under the assumption that it’s actually an epoch second.
In most cases, it is unnecessary to override the write format for a data type, but the associated methods in the clickhouse_connect.datatypes.format package can be used to do so at a global level.
Write format options
Specialized insert methods
ClickHouse Connect provides specialized insert methods for common data formats:insert_df— Insert a Pandas DataFrame. Instead of a Python Sequence of Sequencesdataargument, the second parameter of this method requires adfargument that must be a Pandas DataFrame instance. ClickHouse Connect automatically processes the DataFrame as a column oriented datasource, so thecolumn_orientedparameter isn’t required or available.insert_arrow— Insert a PyArrow Table. ClickHouse Connect passes the Arrow table unmodified to the ClickHouse server for processing, so only thedatabaseandsettingsarguments are available in addition totableandarrow_table.insert_df_arrow— Insert an arrow-backed Pandas DataFrame or a Polars DataFrame. ClickHouse Connect will automatically determine if the DataFrame is a Pandas or Polars type. If Pandas, validation will be performed to ensure that each column’s dtype backend is Arrow-based and an error will be raised if any aren’t.
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)
Time zones
When inserting Pythondatetime.datetime objects into ClickHouse DateTime or DateTime64 columns, ClickHouse Connect automatically handles timezone information. Since ClickHouse stores all DateTime values internally as timezone-naive Unix timestamps (seconds or fractional seconds since the epoch), timezone conversion happens automatically on the client side during insertion.
Timezone-aware datetime objects
If you insert a timezone-aware Pythondatetime.datetime object, ClickHouse Connect will automatically call .timestamp() to convert it to a Unix timestamp, which correctly accounts for the timezone offset. This means you can insert datetime objects from any timezone, and they will be correctly stored as their UTC equivalent timestamp.
When using pytz, you must use the
localize() method to attach timezone information to a naive datetime. Passing tzinfo= directly to the datetime constructor will use incorrect historical offsets. For UTC, tzinfo=pytz.UTC works correctly. See pytz docs for more info.Timezone-naive datetime objects
If you insert a timezone-naive Pythondatetime.datetime object (one without tzinfo), the .timestamp() method will interpret it as being in the system’s local timezone. To avoid ambiguity, it’s recommended to:
- Always use timezone-aware datetime objects when inserting, or
- Ensure your system timezone is set to UTC, or
- Manually convert to epoch timestamps before inserting
DateTime columns with timezone metadata
ClickHouse columns can be defined with timezone metadata (e.g.,DateTime('America/Denver') or DateTime64(3, 'Asia/Tokyo')). This metadata doesn’t affect how data is stored (still as UTC timestamps), but it controls the timezone used when querying data back from ClickHouse.
When inserting into such columns, ClickHouse Connect converts your Python datetime to a Unix timestamp (accounting for its timezone if present). When you query the data back, ClickHouse Connect will return the datetime converted to the column’s timezone, regardless of what timezone you used when inserting.
File inserts
Theclickhouse_connect.driver.tools package includes the insert_file method that allows inserting data directly from the file system into an existing ClickHouse table. Parsing is delegated to the ClickHouse server. insert_file accepts the following parameters:
For files with inconsistent data or date/time values in an unusual format, settings that apply to data imports (such as
input_format_allow_errors_num and input_format_allow_errors_num) are recognized for this method.