首页 > 解决方案 > 如何从 pyarrow 缓冲区反序列化 RecordBatch

问题描述

我的目标是序列化 a RecordBatch,在 websocket 通道上发送它并在接收端反序列化它。

在接收方,在接收到数据包并用 重建pyarrow.lib.Buffer对象后pa.py_buffer,我无法将其反序列化回RecordBatch.

保留 websocket 的样板,这是一个总结我正在尝试做的事情的片段:

import pyarrow as pa

indicators = [(1, 'A'), (2, 'B')]

id = pa.int16()
name = pa.string()

data = pa.array(indicators, type=pa.struct([('id', id), ('name', name)]))

batch = pa.RecordBatch.from_arrays([data], ['indicators'])

buffer = batch.serialize()

# How to get back a RecordBatch from buffer?
#
# ???

标签: pythonpyarrow

解决方案


使用这样的serialize方法时,您可以使用给定已知模式的read_record_batch函数:

>>> pa.ipc.read_record_batch(buffer, batch.schema)
<pyarrow.lib.RecordBatch at 0x7ff412257278>

但这意味着您需要了解接收方的架构。要将其封装在序列化数据中,请RecordBatchStreamWriter改用:

>>> sink = pa.BufferOutputStream()
>>> writer = pa.RecordBatchStreamWriter(sink, batch.schema)
>>> writer.write_batch(batch)
>>> writer.close()
>>> buf = sink.getvalue()
>>> reader = pa.ipc.open_stream(buf)
>>> reader.read_all()
pyarrow.Table
indicators: struct<id: int16, name: string>
  child 0, id: int16
  child 1, name: string

请参阅https://arrow.apache.org/docs/python/ipc.html上的文档


推荐阅读