MCPcopy Create free account
hub / github.com/apache/datafusion / read_csv

Function read_csv

datafusion-examples/examples/dataframe/dataframe.rs:110–156  ·  view source on GitHub ↗

Use the DataFrame API to 1. Read CSV files 2. Optionally specify schema

(ctx: &SessionContext)

Source from the content-addressed store, hash-verified

108/// 1. Read CSV files
109/// 2. Optionally specify schema
110async fn read_csv(ctx: &SessionContext) -> Result<()> {
111 // create example.csv file in a temporary directory
112 let dir = tempdir()?;
113 let file_path = dir.path().join("example.csv");
114 {
115 let mut file = File::create(&file_path)?;
116 // write CSV data
117 file.write_all(
118 r#"id,time,vote,unixtime,rating
119 a1,"10 6, 2013",3,1381017600,5.0
120 a2,"08 9, 2013",2,1376006400,4.5"#
121 .as_bytes(),
122 )?;
123 } // scope closes the file
124 let file_path = file_path.to_str().unwrap();
125
126 // You can read a CSV file and DataFusion will infer the schema automatically
127 let csv_df = ctx.read_csv(file_path, CsvReadOptions::default()).await?;
128 csv_df.show().await?;
129
130 // If you know the types of your data you can specify them explicitly
131 let schema = Schema::new(vec![
132 Field::new("id", DataType::Utf8, false),
133 Field::new("time", DataType::Utf8, false),
134 Field::new("vote", DataType::Int32, true),
135 Field::new("unixtime", DataType::Int64, false),
136 Field::new("rating", DataType::Float32, true),
137 ]);
138 // Create a csv option provider with the desired schema
139 let csv_read_option = CsvReadOptions {
140 // Update the option provider with the defined schema
141 schema: Some(&schema),
142 ..Default::default()
143 };
144 let csv_df = ctx.read_csv(file_path, csv_read_option).await?;
145 csv_df.show().await?;
146
147 // You can also create DataFrames from the result of sql queries
148 // and using the `enable_url_table` refer to local files directly
149 let dyn_ctx = ctx.clone().enable_url_table();
150 let csv_df = dyn_ctx
151 .sql(&format!("SELECT rating, unixtime FROM '{file_path}'"))
152 .await?;
153 csv_df.show().await?;
154
155 Ok(())
156}
157
158/// Use the DataFrame API to:
159/// 1. Read in-memory data.

Callers 1

dataframe_exampleFunction · 0.85

Calls 10

createFunction · 0.85
newFunction · 0.85
read_csvMethod · 0.80
showMethod · 0.80
enable_url_tableMethod · 0.80
sqlMethod · 0.80
joinMethod · 0.45
pathMethod · 0.45
write_allMethod · 0.45
cloneMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…