Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the Iterator trait for the json Reader. #451

Merged
merged 2 commits into from
Jun 13, 2021
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions arrow/src/json/reader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1569,6 +1569,18 @@ impl ReaderBuilder {
}
}

impl<R: Read> Iterator for Reader<R> {
type Item = Result<RecordBatch>;

fn next(&mut self) -> Option<Self::Item> {
match self.next() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you might be able to do self.next().transpose() here

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah indeed that sounds more idiomatic, I just pushed this change.

Ok(None) => None,
Ok(Some(some)) => Some(Ok(some)),
Err(e) => Some(Err(e)),
}
}
}

#[cfg(test)]
mod tests {
use crate::{
Expand Down Expand Up @@ -2946,4 +2958,35 @@ mod tests {
assert_eq!(batch.num_columns(), 1);
assert_eq!(batch.num_rows(), 3);
}

#[test]
fn test_json_iterator() {
let builder = ReaderBuilder::new().infer_schema(None).with_batch_size(5);
let reader: Reader<File> = builder
.build::<File>(File::open("test/data/basic.json").unwrap())
.unwrap();
let schema = reader.schema();
let (col_a_index, _) = schema.column_with_name("a").unwrap();

let mut sum_num_rows = 0;
let mut num_batches = 0;
let mut sum_a = 0;
for batch in reader {
let batch = batch.unwrap();
assert_eq!(4, batch.num_columns());
sum_num_rows += batch.num_rows();
num_batches += 1;
let batch_schema = batch.schema();
assert_eq!(schema, batch_schema);
let a_array = batch
.column(col_a_index)
.as_any()
.downcast_ref::<Int64Array>()
.unwrap();
sum_a += (0..a_array.len()).map(|i| a_array.value(i)).sum::<i64>();
}
assert_eq!(12, sum_num_rows);
assert_eq!(3, num_batches);
assert_eq!(100000000000011, sum_a);
}
}