You need to enable JavaScript to run this app. 如何使用Apache Arrow C++ API读取多个Parquet文件或目录
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache Arrow C++ API读取多个Parquet文件或目录

Apache Arrow C++ 读取多Parquet文件为单Table实现方案

你可以通过「逐个读取文件为Arrow Table→合并所有Table」的流程实现和Python API完全一致的效果,完整可运行代码如下:

#include <vector>
#include <string>
#include <iostream>
#include <arrow/table.h>
#include <arrow/concat.h>
#include <arrow/memory_pool.h>
#include <arrow/filesystem/localfs.h>
#include <parquet/arrow/reader.h>

using namespace arrow;

int main() {
    // 基础配置
    MemoryPool* pool = default_memory_pool();
    fs::LocalFileSystem file_system;
    // 待读取的所有Parquet文件路径列表
    std::vector<std::string> parquet_paths = {
        "/tmp/data1.parquet",
        "/tmp/data2.parquet",
        "/tmp/data3.parquet"
    };
    std::vector<std::shared_ptr<Table>> all_tables;

    for (const auto& path : parquet_paths) {
        // 打开单个Parquet文件
        std::shared_ptr<io::RandomAccessFile> input = file_system.OpenInputFile(path).ValueOrDie();
        std::unique_ptr<parquet::arrow::FileReader> arrow_reader;
        Status st = parquet::arrow::OpenFile(input, pool, &arrow_reader);
        if (!st.ok()) {
            // 可替换为自定义错误处理逻辑
            std::cerr << "打开文件失败: " << path << " 错误信息: " << st.ToString() << std::endl;
            return -1;
        }

        // 读取单个文件为Arrow Table
        std::shared_ptr<Table> single_table;
        st = arrow_reader->ReadTable(&single_table);
        if (!st.ok()) {
            std::cerr << "读取文件转Table失败: " << path << " 错误信息: " << st.ToString() << std::endl;
            return -1;
        }
        all_tables.push_back(single_table);
    }

    // 合并所有Table为单个Table,效果和Python API批量读多文件完全一致
    std::shared_ptr<Table> final_table = ConcatenateTables(all_tables).ValueOrDie();

    // 后续可直接对final_table执行数据处理逻辑
    return 0;
}

注意事项

  • 所有输入Parquet文件默认需要Schema完全一致,如果存在字段差异的场景,可以先调用arrow::UnifySchemas()方法对齐所有文件Schema后再做合并
  • 如果需要读取整个目录下所有Parquet文件,可调用file_system.GetFileInfoGenerator()方法批量扫描后缀为.parquet的文件,无需手动维护路径列表
  • 大文件场景下可替换ReadTable为ReadTableAsync异步读取多个文件,充分利用多核资源提升读取效率

内容的提问来源于stack exchange,提问作者S Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 13:06:04