ArcticDB_demo_write_as_arrow
View in Github | Open in Google ColabArcticDB Write Arrow demo¶
This notebook demonstrates ArcticDB's support for writing Arrow-native data
directly: PyArrow Table, RecordBatch, Array and ChunkedArray objects and Polars DataFrame and Series
objects, without going through Pandas.
For details on ArcticDB's Arrow-based read paths (OutputFormat.PYARROW / OutputFormat.POLARS,
record batch structure on read, configurable string formats, Pandas/Arrow round-tripping) see the
companion notebook
ArcticDB_demo_read_as_arrow.ipynb. This notebook focuses
on writing Arrow data.
Notebook structure:
- Setup
- Writing Polars Primitives -
pl.DataFrame,pl.Series, theindex_columnargument, and how a timeseries index speeds update_rangequeries - Writing PyArrow Primitives -
pa.Table, one-dimensional arrays, and how record batch structure on write relates to storage - String Formats - variable-length vs. categorical/dictionary-encoded strings
- Pandas Interoperability - reading and combining data written from Pandas and Arrow
- Performance Benchmarks
Setup¶
import timeit
from datetime import datetime
import numpy as np
import pandas as pd
import polars as pl
import pyarrow as pa
from arcticdb import Arctic, OutputFormat, ArrowOutputStringFormat
from arcticdb.exceptions import UserInputException, SchemaException, UnsortedDataException
ac = Arctic("lmdb://tmp/arrow_writes_demo")
ac.delete_library("arrow_writes")
lib = ac.create_library("arrow_writes", output_format=OutputFormat.POLARS)
The library above is created with output_format=OutputFormat.POLARS, so unless a cell overrides
it explicitly, every read below returns a Polars object. Two kinds of cells override this default:
ones that inspect PyArrow-specific structure (record batches) need OutputFormat.PYARROW, and the
Pandas Interoperability section needs OutputFormat.PANDAS to make its point.
Writing Polars Primitives¶
All writing methods like Library.write, append, update and stage accept a pl.DataFrame directly.
Writing a Polars DataFrame¶
df = pl.DataFrame({
"col_int": np.arange(10, dtype=np.int64),
"col_float": np.arange(10, 20, dtype=np.float64),
"col_str": [f"value_{i}" for i in range(10)],
})
lib.write("polars_basic", df)
lib.read("polars_basic").data
| col_int | col_float | col_str |
|---|---|---|
| i64 | f64 | str |
| 0 | 10.0 | "value_0" |
| 1 | 11.0 | "value_1" |
| 2 | 12.0 | "value_2" |
| 3 | 13.0 | "value_3" |
| 4 | 14.0 | "value_4" |
| 5 | 15.0 | "value_5" |
| 6 | 16.0 | "value_6" |
| 7 | 17.0 | "value_7" |
| 8 | 18.0 | "value_8" |
| 9 | 19.0 | "value_9" |
By default all arrow data is written without an index. To enable a timeseries index see below.
The index_column argument¶
index_column is a boolean flag. When True, the first column
of the table is treated as a timeseries index. The column must:
- be the first column in the frame,
- have a timestamp dtype, and
- already be sorted in ascending order. (If
validate_indexisTruethis will be explicitly validated)
Only nanosecond-precision timestamps (pa.timestamp("ns") / Polars Datetime("ns")) are
supported, both as an index and as any other column. Other units such as pa.timestamp("us")
raise a SchemaException.
ts_df = pl.DataFrame({
"timestamp": pl.datetime_range(datetime(2025, 1, 1), datetime(2025, 1, 10), interval="1d", eager=True, time_unit="ns"),
"value": np.arange(10, dtype=np.float64),
})
lib.write("polars_indexed", ts_df, index_column=True)
lib.read("polars_indexed").data
| timestamp | value |
|---|---|
| datetime[ns] | f64 |
| 2025-01-01 00:00:00 | 0.0 |
| 2025-01-02 00:00:00 | 1.0 |
| 2025-01-03 00:00:00 | 2.0 |
| 2025-01-04 00:00:00 | 3.0 |
| 2025-01-05 00:00:00 | 4.0 |
| 2025-01-06 00:00:00 | 5.0 |
| 2025-01-07 00:00:00 | 6.0 |
| 2025-01-08 00:00:00 | 7.0 |
| 2025-01-09 00:00:00 | 8.0 |
| 2025-01-10 00:00:00 | 9.0 |
index_column also works with append. It must be passed to every append that takes Arrow
input - it is not remembered from the original write:
t0 = pl.DataFrame({
"timestamp": pl.datetime_range(datetime(2025, 1, 1), datetime(2025, 1, 2), interval="1d", eager=True, time_unit="ns"),
"value": [0.0, 1.0],
})
t1 = pl.DataFrame({
"timestamp": pl.datetime_range(datetime(2025, 1, 3), datetime(2025, 1, 4), interval="1d", eager=True, time_unit="ns"),
"value": [2.0, 3.0],
})
lib.write("polars_indexed_append", t0, index_column=True)
lib.append("polars_indexed_append", t1, index_column=True)
lib.read("polars_indexed_append").data
| timestamp | value |
|---|---|
| datetime[ns] | f64 |
| 2025-01-01 00:00:00 | 0.0 |
| 2025-01-02 00:00:00 | 1.0 |
| 2025-01-03 00:00:00 | 2.0 |
| 2025-01-04 00:00:00 | 3.0 |
update always requires a timeseries index, so it takes no index_column argument and always treats the
first column of Arrow input as the index:
t_update = pl.DataFrame({
"timestamp": pl.datetime_range(datetime(2025, 1, 2), datetime(2025, 1, 2), interval="1d", eager=True, time_unit="ns"),
"value": [99.0],
})
lib.update("polars_indexed_append", t_update)
lib.read("polars_indexed_append").data
| timestamp | value |
|---|---|
| datetime[ns] | f64 |
| 2025-01-01 00:00:00 | 0.0 |
| 2025-01-02 00:00:00 | 99.0 |
| 2025-01-03 00:00:00 | 2.0 |
| 2025-01-04 00:00:00 | 3.0 |
A few invalid uses of index_column and the errors they raise:
# First column is not a timestamp
try:
lib.write("bad_index", pl.DataFrame({"not_a_timestamp": [1, 2, 3]}), index_column=True)
except UserInputException as e:
print(f"UserInputException: {e}")
# No columns at all
try:
lib.write("empty_index", pa.table({}), index_column=True)
except SchemaException as e:
print(f"SchemaException: {e}")
# Unsorted index with validation
try:
unsorted_df = pl.DataFrame({
"ts": pl.Series([datetime(2025, 1, 1), datetime(2025, 1, 3), datetime(2025, 1, 2)], dtype=pl.Datetime("ns")),
})
lib.write("unsorted_index", unsorted_df, index_column=True, validate_index=True)
except UnsortedDataException as e:
print(f"UnsortedDataException: {e}")
UserInputException: E_INVALID_USER_ARGUMENT Specified Arrow index column has non-time type INT64 SchemaException: E_COLUMN_DOESNT_EXIST Cannot use index_column=True on a table with no columns UnsortedDataException: E_UNSORTED_DATA When calling write with validate_index enabled, input data must be sorted
Performance: Using an index column allows efficient processing like date_range filtering¶
When a symbol has a timeseries index, ArcticDB allows using efficient date_range filter which uses the index structure.
This allows more efficient filtering than doing a similar filter in memory.
N = 2_000_000
timestamps = pl.datetime_range(
pd.Timestamp("2020-01-01"),
pd.Timestamp("2020-01-01") + pd.Timedelta(seconds=N - 1),
interval="1s",
eager=True,
time_unit="ns",
)
values = np.random.randn(N)
lib.write("dr_indexed", pl.DataFrame({"ts": timestamps, "value": values}), index_column=True)
lib.write("dr_plain", pl.DataFrame({"ts": timestamps, "value": values}))
start_q = pd.Timestamp("2020-01-01") + pd.Timedelta(hours=1)
end_q = pd.Timestamp("2020-01-01") + pd.Timedelta(hours=1, minutes=5)
# With a timeseries index: date_range is pushed down to storage
indexed_time = timeit.timeit(
lambda: lib.read("dr_indexed", date_range=(start_q, end_q)).data,
number=20,
) / 20
# Without an index: read the whole symbol, then filter client-side with Polars
def read_all_then_filter():
full = lib.read("dr_plain", output_format=OutputFormat.POLARS).data
return full.filter((pl.col("ts") >= start_q) & (pl.col("ts") <= end_q))
plain_time = timeit.timeit(read_all_then_filter, number=20) / 20
print(f"Indexed date_range read: {indexed_time * 1000:.2f} ms")
print(f"Unindexed read-all + filter: {plain_time * 1000:.2f} ms")
print(f"Speedup: {plain_time / indexed_time:.1f}x")
Indexed date_range read: 2.92 ms Unindexed read-all + filter: 9.72 ms Speedup: 3.3x
Writing a Polars Series¶
A pl.Series is written as a single column and reads back as a pl.Series, keeping its name.
lib.write("polars_series", pl.Series("value", [1, 2, 3]))
lib.read("polars_series").data
| value |
|---|
| i64 |
| 1 |
| 2 |
| 3 |
Writing PyArrow Primitives¶
pyarrow.Table and pyarrow.Array are also supported Arrow write input and works in an identical way to Polars writes.
Writing a pa.Table¶
table = pa.table({
"col_int": pa.array(np.arange(10, dtype=np.int64)),
"col_str": pa.array([f"value_{i}" for i in range(10)]),
})
lib.write("arrow_basic", table)
lib.read("arrow_basic").data
| col_int | col_str |
|---|---|
| i64 | str |
| 0 | "value_0" |
| 1 | "value_1" |
| 2 | "value_2" |
| 3 | "value_3" |
| 4 | "value_4" |
| 5 | "value_5" |
| 6 | "value_6" |
| 7 | "value_7" |
| 8 | "value_8" |
| 9 | "value_9" |
Record Batch Structure¶
A pa.Table can be built from multiple pa.RecordBatch objects via pa.Table.from_batches(...).
ArcticDB's on-disk row-slicing is independent of the input record-batch boundaries: writing
recombines the input into ArcticDB's own row-slices (by default up to ~100k rows per segment), and
reading back returns one record batch per on-disk row-slice, not one per input batch. This example
writes 3 batches of 60k rows (180k rows total) to show both effects at once: the 3 input batches
are combined, and the combined data is then resliced at the ~100k row boundary rather than at the
original 60k/120k batch boundaries.
N_PER_BATCH = 60_000
rb0 = pa.RecordBatch.from_arrays([pa.array(np.arange(0 * N_PER_BATCH, 1 * N_PER_BATCH))], names=["col"])
rb1 = pa.RecordBatch.from_arrays([pa.array(np.arange(1 * N_PER_BATCH, 2 * N_PER_BATCH))], names=["col"])
rb2 = pa.RecordBatch.from_arrays([pa.array(np.arange(2 * N_PER_BATCH, 3 * N_PER_BATCH))], names=["col"])
multi_batch_table = pa.Table.from_batches([rb0, rb1, rb2])
print(f"Input table has {len(multi_batch_table.to_batches())} record batches, {multi_batch_table.num_rows} rows total")
lib.write("multi_batch_input", multi_batch_table)
read_back = lib.read("multi_batch_input", output_format=OutputFormat.PYARROW).data
print(f"Read back has {len(read_back.to_batches())} record batch(es)")
assert multi_batch_table.equals(read_back)
Input table has 3 record batches, 180000 rows total Read back has 2 record batch(es)
The same reslicing applies across separate write/append calls too - see the
Record Batch Structure section of the read-Arrow notebook for a
full breakdown of how row-slices map to record batches on read.
Writing one-dimensional arrays and record batches¶
A pa.Array or pa.ChunkedArray is written as a single column and reads back as a
pa.ChunkedArray with OutputFormat.PYARROW. A pa.RecordBatch is written like a pa.Table.
lib.write("arrow_array", pa.chunked_array([[1, 2], [3]]))
print(lib.read("arrow_array", output_format=OutputFormat.PYARROW).data)
lib.write("arrow_record_batch", pa.RecordBatch.from_pydict({"col": [1, 2, 3]}))
lib.read("arrow_record_batch", output_format=OutputFormat.PYARROW).data
[
[
1,
2,
3
]
]
pyarrow.Table col: int64 ---- col: [[1,2,3]]
String Formats¶
ArcticDB accepts writing both variable length and dictionary encoded (categorical) arrow strings.
Variable-length strings¶
strings_table = pa.table({"category": pa.array(["A", "B", "A", "B", "A"], type=pa.large_string())})
lib.write("strings_plain", strings_table)
lib.read("strings_plain").data
| category |
|---|
| str |
| "A" |
| "B" |
| "A" |
| "B" |
| "A" |
The same works via a Polars string column:
strings_df = pl.DataFrame({"category": ["A", "B", "A", "B", "A"]})
lib.write("strings_plain_polars", strings_df)
lib.read("strings_plain_polars").data
| category |
|---|
| str |
| "A" |
| "B" |
| "A" |
| "B" |
| "A" |
Categorical / dictionary-encoded strings¶
PyArrow's dictionary_encode() and Polars' pl.Categorical dtype are both accepted. Only
int32/uint32 keys over large_string pyarrow dictionary encodings are supported - other key/value combinations raise
a SchemaException.
dictionary_encoded = pa.array(["A", "B", "A", "B", "A"], type=pa.large_string()).dictionary_encode()
print(f"Input dtype: {dictionary_encoded.type}")
cat_table = pa.table({"category": dictionary_encoded})
lib.write("strings_categorical", cat_table)
lib.read("strings_categorical").data
Input dtype: dictionary<values=large_string, indices=int32, ordered=0>
| category |
|---|
| cat |
| "A" |
| "B" |
| "A" |
| "B" |
| "A" |
Polars' native Categorical dtype works the same way:
cat_df = pl.DataFrame({"category": pl.Series(["A", "B", "A", "B", "A"], dtype=pl.Categorical)})
lib.write("strings_categorical_polars", cat_df)
lib.read("strings_categorical_polars").data.dtypes
[Categorical]
ArcticDB stores the string format each column was written with, so dictionary-encoded data reads
back as dictionary-encoded by default. arrow_string_format_default overrides this on read:
default_read = lib.read("strings_categorical", output_format=OutputFormat.PYARROW).data
print(f"Default read-back dtype: {default_read.schema.field('category').type}")
large_string_read = lib.read(
"strings_categorical",
output_format=OutputFormat.PYARROW,
arrow_string_format_default=ArrowOutputStringFormat.LARGE_STRING,
).data
print(f"Explicit large_string read-back dtype: {large_string_read.schema.field('category').type}")
Default read-back dtype: dictionary<values=large_string, indices=int32, ordered=0> Explicit large_string read-back dtype: large_string
See the Configurable String Formats section of the read-Arrow notebook for the full set of read-time options.
Pandas Interoperability¶
The storage format does not depend on whether data was written from Pandas or from Arrow. A symbol
written from a pd.DataFrame can be read as Arrow or Polars, a symbol written from a pa.Table or
pl.DataFrame can be read as Pandas, and append, update, stage and concat can combine data
from both.
Write Pandas, read Arrow¶
pandas_df = pd.DataFrame(
{"value": np.arange(3, dtype=np.float64)},
index=pd.date_range("2025-01-01", periods=3, name="timestamp"),
)
lib.write("pandas_written", pandas_df)
lib.read("pandas_written").data
| timestamp | value |
|---|---|
| datetime[ns] | f64 |
| 2025-01-01 00:00:00 | 0.0 |
| 2025-01-02 00:00:00 | 1.0 |
| 2025-01-03 00:00:00 | 2.0 |
Write Arrow, read Pandas¶
polars_df = pl.DataFrame({
"timestamp": pl.datetime_range(datetime(2025, 1, 1), datetime(2025, 1, 3), interval="1d", eager=True, time_unit="ns"),
"value": [0.0, 1.0, 2.0],
})
lib.write("polars_written", polars_df, index_column=True)
lib.read("polars_written", output_format=OutputFormat.PANDAS).data
| value | |
|---|---|
| timestamp | |
| 2025-01-01 | 0.0 |
| 2025-01-02 | 1.0 |
| 2025-01-03 | 2.0 |
Combining Pandas and Arrow¶
A symbol written from Pandas can be appended to and updated with Arrow data, and vice versa. The column names, including the index name, must match.
lib.write("mixed", pandas_df)
lib.append("mixed", pl.DataFrame({
"timestamp": pl.datetime_range(datetime(2025, 1, 4), datetime(2025, 1, 5), interval="1d", eager=True, time_unit="ns"),
"value": [3.0, 4.0],
}), index_column=True)
lib.update("mixed", pa.table({
"timestamp": pa.array([pd.Timestamp("2025-01-02")], type=pa.timestamp("ns")),
"value": [99.0],
}))
lib.read("mixed", output_format=OutputFormat.PANDAS).data
| value | |
|---|---|
| timestamp | |
| 2025-01-01 | 0.0 |
| 2025-01-02 | 99.0 |
| 2025-01-03 | 2.0 |
| 2025-01-04 | 3.0 |
| 2025-01-05 | 4.0 |
Column names which need renaming¶
Pandas allows column and index names that Arrow and Polars do not: unnamed indexes and MultiIndex
levels, duplicate column names and non-string names. When such data is read as Arrow, ArcticDB
assigns Arrow compatible names (__index__, __index_level_N__, _col_ for a duplicate col,
"5" for 5). Reading back as Pandas restores the original names. See the
Pandas Interoperability and Column Naming section of the
read-Arrow notebook for the full set of rules.
odd_names_df = pd.DataFrame(
np.arange(6).reshape(2, 3),
columns=["col", "col", 5],
index=pd.date_range("2025-01-01", periods=2),
)
lib.write("odd_names", odd_names_df)
lib.read("odd_names").data
| __index__ | col | _col_ | 5 |
|---|---|---|---|
| datetime[ns] | i64 | i64 | i64 |
| 2025-01-01 00:00:00 | 0 | 1 | 2 |
| 2025-01-02 00:00:00 | 3 | 4 | 5 |
These names exist only on read. The stored names are still the Pandas ones, so Arrow data cannot be appended under the names shown above:
new_rows = pl.DataFrame({
"__index__": pl.datetime_range(datetime(2025, 1, 3), datetime(2025, 1, 3), interval="1d", eager=True, time_unit="ns"),
"col": [6],
"_col_": [7],
"5": [8],
})
try:
lib.append("odd_names", new_rows, index_column=True)
except SchemaException as e:
print(f"SchemaException: {e}")
SchemaException: E_DESCRIPTOR_MISMATCH Cannot append (symbol 'odd_names'): index names must match, '__index__' is named on one side only
rename_columns_arrow_compat writes a new version in which the stored names are Arrow compatible.
index_columns names the index explicitly instead of using __index__. After the rename the
symbol can be combined with Arrow data:
lib.rename_columns_arrow_compat("odd_names", index_columns="timestamp")
lib.append("odd_names", new_rows.rename({"__index__": "timestamp"}), index_column=True)
lib.read("odd_names").data
| timestamp | col | _col_ | 5 |
|---|---|---|---|
| datetime[ns] | i64 | i64 | i64 |
| 2025-01-01 00:00:00 | 0 | 1 | 2 |
| 2025-01-02 00:00:00 | 3 | 4 | 5 |
| 2025-01-03 00:00:00 | 6 | 7 | 8 |
The same applies to an unnamed MultiIndex, with one name per level:
multiindex_df = pd.DataFrame(
{"price": [1, 2, 3, 4]},
index=pd.MultiIndex.from_arrays([pd.to_datetime(["2025-01-01"] * 2 + ["2025-01-02"] * 2), ["A", "B"] * 2]),
)
lib.write("multiindex", multiindex_df)
print(lib.read("multiindex").data.columns)
lib.rename_columns_arrow_compat("multiindex", index_columns=["timestamp", "ticker"])
lib.read("multiindex").data
['__index_level_0__', '__index_level_1__', 'price']
| timestamp | ticker | price |
|---|---|---|
| datetime[ns] | str | i64 |
| 2025-01-01 00:00:00 | "A" | 1 |
| 2025-01-01 00:00:00 | "B" | 2 |
| 2025-01-02 00:00:00 | "A" | 3 |
| 2025-01-02 00:00:00 | "B" | 4 |
Performance Benchmarks¶
Arrow writes have roughly the same performance as pandas for numeric types. For string types Arrow is slightly faster in general and is significantly faster if unicode characters are involved. On write the GIL is not required (no python strings need allocating unlike the read side), unless non-ascii characters appear in the pandas strings, then the GIL is acquired for decoding them.
Benchmark: Numeric Data¶
df_numeric_pandas = pd.DataFrame({
f"col_{i}": np.random.randn(1_000_000) for i in range(10)
})
df_numeric_polars = pl.from_pandas(df_numeric_pandas)
pandas_time = timeit.timeit(lambda: lib.write("bench_numeric_pandas", df_numeric_pandas), number=5) / 5
polars_time = timeit.timeit(lambda: lib.write("bench_numeric_polars", df_numeric_polars), number=5) / 5
print(f"Pandas write: {pandas_time * 1000:.1f} ms")
print(f"Polars write: {polars_time * 1000:.1f} ms")
print(f"Speedup: {pandas_time / polars_time:.2f}x")
Pandas write: 106.7 ms Polars write: 100.6 ms Speedup: 1.06x
Benchmark: String Data¶
df_strings_pandas = pd.DataFrame({
f"col_{i}": np.random.randn(200_000).astype(str) for i in range(10)
})
df_strings_polars = pl.from_pandas(df_strings_pandas)
pandas_time = timeit.timeit(lambda: lib.write("bench_strings_pandas", df_strings_pandas), number=5) / 5
polars_time = timeit.timeit(lambda: lib.write("bench_strings_polars", df_strings_polars), number=5) / 5
print(f"Pandas write: {pandas_time * 1000:.1f} ms")
print(f"Polars write: {polars_time * 1000:.1f} ms")
print(f"Speedup: {pandas_time / polars_time:.2f}x")
Pandas write: 311.0 ms Polars write: 281.1 ms Speedup: 1.11x
Benchmark: Unicode String Data¶
The pandas write decodes the unicode strings via PyUnicode_AsUTF8String (which requires the GIL).
Arrow/Polars strings are already UTF-8 encoded buffers, so it can work significantly faster without acquiring the GIL
UNICODE_POOL = np.array([f"café_日本語_données_{i}_🚀" for i in range(1000)])
df_unicode_pandas = pd.DataFrame({
f"col_{i}": np.random.choice(UNICODE_POOL, size=200_000) for i in range(10)
})
df_unicode_polars = pl.from_pandas(df_unicode_pandas)
pandas_time = timeit.timeit(lambda: lib.write("bench_unicode_pandas", df_unicode_pandas), number=5) / 5
polars_time = timeit.timeit(lambda: lib.write("bench_unicode_polars", df_unicode_polars), number=5) / 5
print(f"Pandas write: {pandas_time * 1000:.1f} ms")
print(f"Polars write: {polars_time * 1000:.1f} ms")
print(f"Speedup: {pandas_time / polars_time:.2f}x")
Pandas write: 218.7 ms Polars write: 56.2 ms Speedup: 3.89x