Rust编程2026-03-03 01:01

如何使用 Rust 语言中的新 Polars 流式引擎,实现高效的懒加载和数据倾斜处理?

rustfan
rustfan
作者

我正在使用 Rust 中的 Polars 0.53.0。根据我所了解的情况,使用新的流式引擎进行惰性扫描和写入(不使用 collect() 或显式数据),应该按照以下方式进行,但结果为空。我找不到任何 0.53.0 的实际代码示例。请问有人知道如何做到吗?

Cargo.toml

[dependencies]
polars = {version = "0.53.0", features = ["lazy", "new_streaming", "polars-io", "csv"]}

main.rs

use polars::prelude::*;

fn process_data(intsv: &str, outtsv: &str) -> std::io::Result<()> {
    let schema = Schema::from_iter(vec![
        Field::new("idx".into(), DataType::Int64),
        Field::new("f1".into(), DataType::Int64),
        Field::new("f2".into(), DataType::Int64),
    ]);
    let lf1: LazyFrame =
        LazyCsvReader::new(PlRefPath::new(&*intsv))
        .with_has_header(true)
        .with_separator(b'\t')
        .with_schema(Some(Arc::new(schema.clone())))
        .finish().unwrap();
    let outpath = PlRefPath::new(&*outtsv);
    let mut seropts = SerializeOptions::default();
    seropts.separator = b'\t';
    let aseropts = Arc::new(seropts);
    let mut csvwo = CsvWriterOptions::default();
    csvwo.include_header = true;
    csvwo.serialize_options = aseropts;
    let frame = lf1
        .with_new_streaming(true)
        .filter(col("idx").eq(lit(1)))
        //.collect()
        .sink(
            SinkDestination::File {
                target: SinkTarget::Path(outpath)
            },
            FileWriteFormat::Csv(csvwo),
            UnifiedSinkArgs::default())
        .expect("problem writing CSV output");
    //println!("{}", frame);
    Ok(())
}

fn main() {
    let input_tsv = "mydata.tsv";
    let output_tsv = "mydata-filt.tsv";
    std::process::exit(match process_data(input_tsv, output_tsv) {
        Ok(_) => 0,
        Err(err) => {
            eprintln!("error: {err:?}");
            1
        }
    });
}

mydata.tsv

idx     f1      f2
1       4       5
2       6       7
3       7       8
1
45

评论 (0)

登录后评论

立即登录

加载评论中...