Streaming, Serialization, and IPC

Writing and Reading Streams

Arrow defines two types of binary formats for serializing record batches:

  • Streaming format: for sending an arbitrary length sequence of record batches. The format must be processed from start to end, and does not support random access

  • File or Random Access format: for serializing a fixed number of record batches. Supports random access, and thus is very useful when used with memory maps

To follow this section, make sure to first read the section on Memory and IO.

Using streams

First, let’s create a small record batch:

In [1]: import pyarrow as pa

In [2]: data = [
   ...:     pa.array([1, 2, 3, 4]),
   ...:     pa.array(['foo', 'bar', 'baz', None]),
   ...:     pa.array([True, None, False, True])
   ...: ]
   ...: 

In [3]: batch = pa.record_batch(data, names=['f0', 'f1', 'f2'])

In [4]: batch.num_rows
Out[4]: 4

In [5]: batch.num_columns
Out[5]: 3

Now, we can begin writing a stream containing some number of these batches. For this we use RecordBatchStreamWriter, which can write to a writeable NativeFile object or a writeable Python object. For convenience, this one can be created with new_stream():

In [6]: sink = pa.BufferOutputStream()

In [7]: writer = pa.ipc.new_stream(sink, batch.schema)

Here we used an in-memory Arrow buffer stream, but this could have been a socket or some other IO sink.

When creating the StreamWriter, we pass the schema, since the schema (column names and types) must be the same for all of the batches sent in this particular stream. Now we can do:

In [8]: for i in range(5):
   ...:    writer.write_batch(batch)
   ...: 

In [9]: writer.close()

In [10]: buf = sink.getvalue()

In [11]: buf.size
Out[11]: 1984

Now buf contains the complete stream as an in-memory byte buffer. We can read such a stream with RecordBatchStreamReader or the convenience function pyarrow.ipc.open_stream:

In [12]: reader = pa.ipc.open_stream(buf)

In [13]: reader.schema
Out[13]: 
f0: int64
f1: string
f2: bool

In [14]: batches = [b for b in reader]

In [15]: len(batches)
Out[15]: 5

We can check the returned batches are the same as the original input:

In [16]: batches[0].equals(batch)
Out[16]: True

An important point is that if the input source supports zero-copy reads (e.g. like a memory map, or pyarrow.BufferReader), then the returned batches are also zero-copy and do not allocate any new memory on read.

Writing and Reading Random Access Files

The RecordBatchFileWriter has the same API as RecordBatchStreamWriter. You can create one with new_file():

In [17]: sink = pa.BufferOutputStream()

In [18]: writer = pa.ipc.new_file(sink, batch.schema)

In [19]: for i in range(10):
   ....:    writer.write_batch(batch)
   ....: 

In [20]: writer.close()

In [21]: buf = sink.getvalue()

In [22]: buf.size
Out[22]: 4226

The difference between RecordBatchFileReader and RecordBatchStreamReader is that the input source must have a seek method for random access. The stream reader only requires read operations. We can also use the open_file() method to open a file:

In [23]: reader = pa.ipc.open_file(buf)

Because we have access to the entire payload, we know the number of record batches in the file, and can read any at random:

In [24]: reader.num_record_batches
Out[24]: 10

In [25]: b = reader.get_batch(3)

In [26]: b.equals(batch)
Out[26]: True

Reading from Stream and File Format for pandas

The stream and file reader classes have a special read_pandas method to simplify reading multiple record batches and converting them to a single DataFrame output:

In [27]: df = pa.ipc.open_file(buf).read_pandas()

In [28]: df[:5]
Out[28]: 
   f0    f1     f2
0   1   foo   True
1   2   bar   None
2   3   baz  False
3   4  None   True
4   1   foo   True

Arbitrary Object Serialization

Warning

The custom serialization functionality is deprecated in pyarrow 2.0, and will be removed in a future version.

While the serialization functions in this section utilize the Arrow stream protocol internally, they do not produce data that is compatible with the above ipc.open_file and ipc.open_stream functions.

For arbitrary objects, you can use the standard library pickle functionality instead. For pyarrow objects, you can use the IPC serialization format through the pyarrow.ipc module, as explained above.

In pyarrow we are able to serialize and deserialize many kinds of Python objects. While not a complete replacement for the pickle module, these functions can be significantly faster, particular when dealing with collections of NumPy arrays.

As an example, consider a dictionary containing NumPy arrays:

In [29]: import numpy as np

In [30]: data = {
   ....:     i: np.random.randn(500, 500)
   ....:     for i in range(100)
   ....: }
   ....: 

We use the pyarrow.serialize function to convert this data to a byte buffer:

In [31]: buf = pa.serialize(data).to_buffer()

In [32]: type(buf)
Out[32]: pyarrow.lib.Buffer

In [33]: buf.size
Out[33]: 200028928

pyarrow.serialize creates an intermediate object which can be converted to a buffer (the to_buffer method) or written directly to an output stream.

pyarrow.deserialize converts a buffer-like object back to the original Python object:

In [34]: restored_data = pa.deserialize(buf)

In [35]: restored_data[0]
Out[35]: 
array([[-1.29998759, -1.33913634, -0.95397197, ..., -0.30801473,
         0.23324538, -0.41150941],
       [-0.8268925 , -1.01873809,  0.01694778, ...,  1.87295091,
        -0.61101027, -0.21171111],
       [ 0.46235894, -0.45549429,  0.57306186, ...,  0.00508744,
        -1.07905794,  0.13755155],
       ...,
       [-0.86868048,  0.20687941,  0.9710501 , ...,  0.58151042,
         0.46481304,  0.08002741],
       [-0.77986154, -0.67805805, -0.27608017, ..., -1.12197884,
         0.47550651, -0.35977747],
       [-0.88104763,  2.19388036,  0.85487201, ..., -1.52325484,
        -1.46887326,  1.44832259]])

When dealing with NumPy arrays, pyarrow.deserialize can be significantly faster than pickle because the resulting arrays are zero-copy references into the input buffer. The larger the arrays, the larger the performance savings.

Consider this example, we have for pyarrow.deserialize

In [36]: %timeit restored_data = pa.deserialize(buf)
5.84 ms +- 730 us per loop (mean +- std. dev. of 7 runs, 100 loops each)

And for pickle:

In [37]: import pickle

In [38]: pickled = pickle.dumps(data)

In [39]: %timeit unpickled_data = pickle.loads(pickled)
74.4 ms +- 3.42 ms per loop (mean +- std. dev. of 7 runs, 10 loops each)

We aspire to make these functions a high-speed alternative to pickle for transient serialization in Python big data applications.

Serializing Custom Data Types

If an unrecognized data type is encountered when serializing an object, pyarrow will fall back on using pickle for converting that type to a byte string. There may be a more efficient way, though.

Consider a class with two members, one of which is a NumPy array:

class MyData:
    def __init__(self, name, data):
        self.name = name
        self.data = data

We write functions to convert this to and from a dictionary with simpler types:

def _serialize_MyData(val):
    return {'name': val.name, 'data': val.data}

def _deserialize_MyData(data):
    return MyData(data['name'], data['data']

then, we must register these functions in a SerializationContext so that MyData can be recognized:

context = pa.SerializationContext()
context.register_type(MyData, 'MyData',
                      custom_serializer=_serialize_MyData,
                      custom_deserializer=_deserialize_MyData)

Lastly, we use this context as an additional argument to pyarrow.serialize:

buf = pa.serialize(val, context=context).to_buffer()
restored_val = pa.deserialize(buf, context=context)

The SerializationContext also has convenience methods serialize and deserialize, so these are equivalent statements:

buf = context.serialize(val).to_buffer()
restored_val = context.deserialize(buf)

Component-based Serialization

For serializing Python objects containing some number of NumPy arrays, Arrow buffers, or other data types, it may be desirable to transport their serialized representation without having to produce an intermediate copy using the to_buffer method. To motivate this, suppose we have a list of NumPy arrays:

In [40]: import numpy as np

In [41]: data = [np.random.randn(10, 10) for i in range(5)]

The call pa.serialize(data) does not copy the memory inside each of these NumPy arrays. This serialized representation can be then decomposed into a dictionary containing a sequence of pyarrow.Buffer objects containing metadata for each array and references to the memory inside the arrays. To do this, use the to_components method:

In [42]: serialized = pa.serialize(data)

In [43]: components = serialized.to_components()

The particular details of the output of to_components are not too important. The objects in the 'data' field are pyarrow.Buffer objects, which are zero-copy convertible to Python memoryview objects:

In [44]: memoryview(components['data'][0])
Out[44]: <memory at 0x7f8107873c40>

A memoryview can be converted back to a Arrow Buffer with pyarrow.py_buffer:

In [45]: mv = memoryview(components['data'][0])

In [46]: buf = pa.py_buffer(mv)

An object can be reconstructed from its component-based representation using deserialize_components:

In [47]: restored_data = pa.deserialize_components(components)

In [48]: restored_data[0]
Out[48]: 
array([[ 0.45956591, -0.37558124,  0.22367425,  1.29780652,  0.85789458,
         0.03660379,  1.26671926, -0.31458915, -0.54179666, -1.38694472],
       [-0.98538421, -1.6823949 ,  1.53218678,  1.5838421 , -0.06959235,
         1.74310795,  0.1911899 ,  0.2464995 ,  0.96869683,  0.86920856],
       [-1.03862796, -1.04614996,  1.32827407, -0.37767296,  0.45568096,
         0.88692798, -0.42061847,  1.05337907, -0.07631226,  0.37636149],
       [ 0.34611202,  1.43226442, -1.32263193,  0.11225455,  1.33385373,
         1.74288681,  0.88115343,  0.81463359,  1.34419506,  0.67854734],
       [-1.02442749,  1.83430853,  0.15033679,  0.53795673, -0.44252523,
        -0.90608807,  1.05831437, -1.25898334, -2.74132664,  0.31880112],
       [-0.94135003,  0.0772576 , -0.00390485, -2.82448122,  0.24638344,
        -2.02346633, -0.2016212 ,  0.94173428, -0.41105679,  1.44823963],
       [ 0.3214504 ,  1.31686526, -0.90179738,  0.0298733 ,  1.92337955,
        -0.68763577,  0.69448331,  0.07663522,  0.53918641,  0.9613467 ],
       [ 0.16316872,  1.01637867,  0.16113713, -0.26835683,  0.41678118,
         0.68353313, -0.2735437 ,  0.68474947,  0.15727851,  0.43335373],
       [ 0.96474783, -0.69684867,  1.39950298,  1.25394701,  0.3796324 ,
         1.20896005,  1.20799444, -0.16557876,  1.19737198,  0.76064244],
       [ 0.43911313, -0.42722325, -0.92896357,  1.13916632,  1.03124003,
         0.24026129, -0.55038671,  0.74494189, -1.80214737, -0.7818716 ]])

deserialize_components is also available as a method on SerializationContext objects.