首页 > 解决方案 > 如何序列化apache箭头c ++表,通过套接字传输,并在python端反序列化

问题描述

我是 apache arrow 的新手,我的 C++ 项目使用 apache::table 来很好地存储数据。现在,我需要将带有套接字的 c++ 表传输到其他 python 客户端。为什么要尝试这个,因为 python 客户端需要将数据转换为数据框,我注意到 python 中的箭头表可以使用 'to_pandas()' 来做到这一点。我试图查找箭头 cython 代码,但我一无所获。

标签: pythonc++apache-arrow

解决方案


可以通过基本套接字(下面的示例)发送箭头表,但最好使用 Flight。Flight 使用 grpc 来回发送箭头数据,它将消除使用套接字的一些乏味。 是一个很好的例子。

完整的套接字示例可以在这个gist中找到。

我将把相关位放在这里:

发送

void SendTable(int socket_fd) {
  auto output_res = SocketOutputStream::Open(socket_fd);
  if (!CheckErr(output_res.status(), "arrow::io::FileOutputStream")) {
    return;
  }
  auto output = *output_res;

  arrow::MemoryPool *pool = arrow::default_memory_pool();

  auto table = MakeTable();
  if (table == nullptr) {
    return;
  }

  auto writer_res = arrow::ipc::MakeStreamWriter(output, table->schema());
  if (!CheckErr(writer_res.status(), "arrow::ipc::MakeStreamWriter")) {
    return;
  }
  auto writer = *writer_res;
  if (!CheckErr(writer->WriteTable(*table), "RecordBatchWriter::WriteTable")) {
    return;
  }
  CheckErr(writer->Close(), "RecordBatchWriter::Close");
}

接收

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind((listen, port))
    sock.listen()
    print(f"Listening on {listen} on port {port}")
    conn, _ = sock.accept()
    with conn:
        conn_file = conn.makefile(mode="b")
        reader = pyarrow.ipc.RecordBatchStreamReader(conn_file)
        table = reader.read_all()
        print(table)
        print(table.to_pandas())

推荐阅读