-
Notifications
You must be signed in to change notification settings - Fork 850
/
Copy pathreader.rs
3495 lines (3221 loc) · 124 KB
/
reader.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! # JSON Reader
//!
//! This JSON reader allows JSON line-delimited files to be read into the Arrow memory
//! model. Records are loaded in batches and are then converted from row-based data to
//! columnar data.
//!
//! Example:
//!
//! ```
//! # use arrow_schema::*;
//! # use std::fs::File;
//! # use std::io::BufReader;
//! # use std::sync::Arc;
//!
//! let schema = Schema::new(vec![
//! Field::new("a", DataType::Float64, false),
//! Field::new("b", DataType::Float64, false),
//! Field::new("c", DataType::Float64, true),
//! ]);
//!
//! let file = File::open("test/data/basic.json").unwrap();
//!
//! let mut json = arrow_json::Reader::new(
//! BufReader::new(file),
//! Arc::new(schema),
//! arrow_json::reader::DecoderOptions::new(),
//! );
//!
//! let batch = json.next().unwrap().unwrap();
//! ```
use std::borrow::Borrow;
use std::io::{BufRead, BufReader, Read, Seek};
use std::sync::Arc;
use indexmap::map::IndexMap as HashMap;
use indexmap::set::IndexSet as HashSet;
use serde_json::json;
use serde_json::{map::Map as JsonMap, Value};
use arrow_array::builder::*;
use arrow_array::types::*;
use arrow_array::*;
use arrow_buffer::{bit_util, i256, Buffer, MutableBuffer};
use arrow_cast::parse::{parse_decimal, Parser};
use arrow_data::{ArrayData, ArrayDataBuilder};
use arrow_schema::*;
#[derive(Debug, Clone)]
enum InferredType {
Scalar(HashSet<DataType>),
Array(Box<InferredType>),
Object(HashMap<String, InferredType>),
Any,
}
impl InferredType {
fn merge(&mut self, other: InferredType) -> Result<(), ArrowError> {
match (self, other) {
(InferredType::Array(s), InferredType::Array(o)) => {
s.merge(*o)?;
}
(InferredType::Scalar(self_hs), InferredType::Scalar(other_hs)) => {
other_hs.into_iter().for_each(|v| {
self_hs.insert(v);
});
}
(InferredType::Object(self_map), InferredType::Object(other_map)) => {
for (k, v) in other_map {
self_map.entry(k).or_insert(InferredType::Any).merge(v)?;
}
}
(s @ InferredType::Any, v) => {
*s = v;
}
(_, InferredType::Any) => {}
// convert a scalar type to a single-item scalar array type.
(
InferredType::Array(self_inner_type),
other_scalar @ InferredType::Scalar(_),
) => {
self_inner_type.merge(other_scalar)?;
}
(s @ InferredType::Scalar(_), InferredType::Array(mut other_inner_type)) => {
other_inner_type.merge(s.clone())?;
*s = InferredType::Array(other_inner_type);
}
// incompatible types
(s, o) => {
return Err(ArrowError::JsonError(format!(
"Incompatible type found during schema inference: {s:?} v.s. {o:?}",
)));
}
}
Ok(())
}
}
/// Coerce data type during inference
///
/// * `Int64` and `Float64` should be `Float64`
/// * Lists and scalars are coerced to a list of a compatible scalar
/// * All other types are coerced to `Utf8`
fn coerce_data_type(dt: Vec<&DataType>) -> DataType {
let mut dt_iter = dt.into_iter().cloned();
let dt_init = dt_iter.next().unwrap_or(DataType::Utf8);
dt_iter.fold(dt_init, |l, r| match (l, r) {
(DataType::Boolean, DataType::Boolean) => DataType::Boolean,
(DataType::Int64, DataType::Int64) => DataType::Int64,
(DataType::Float64, DataType::Float64)
| (DataType::Float64, DataType::Int64)
| (DataType::Int64, DataType::Float64) => DataType::Float64,
(DataType::List(l), DataType::List(r)) => DataType::List(Box::new(Field::new(
"item",
coerce_data_type(vec![l.data_type(), r.data_type()]),
true,
))),
// coerce scalar and scalar array into scalar array
(DataType::List(e), not_list) | (not_list, DataType::List(e)) => {
DataType::List(Box::new(Field::new(
"item",
coerce_data_type(vec![e.data_type(), ¬_list]),
true,
)))
}
_ => DataType::Utf8,
})
}
fn generate_datatype(t: &InferredType) -> Result<DataType, ArrowError> {
Ok(match t {
InferredType::Scalar(hs) => coerce_data_type(hs.iter().collect()),
InferredType::Object(spec) => DataType::Struct(generate_fields(spec)?),
InferredType::Array(ele_type) => DataType::List(Box::new(Field::new(
"item",
generate_datatype(ele_type)?,
true,
))),
InferredType::Any => DataType::Null,
})
}
fn generate_fields(
spec: &HashMap<String, InferredType>,
) -> Result<Vec<Field>, ArrowError> {
spec.iter()
.map(|(k, types)| Ok(Field::new(k, generate_datatype(types)?, true)))
.collect()
}
/// Generate schema from JSON field names and inferred data types
fn generate_schema(spec: HashMap<String, InferredType>) -> Result<Schema, ArrowError> {
Ok(Schema::new(generate_fields(&spec)?))
}
/// JSON file reader that produces a serde_json::Value iterator from a Read trait
///
/// # Example
///
/// ```
/// use std::fs::File;
/// use std::io::BufReader;
/// use arrow_json::reader::ValueIter;
///
/// let mut reader =
/// BufReader::new(File::open("test/data/mixed_arrays.json").unwrap());
/// let mut value_reader = ValueIter::new(&mut reader, None);
/// for value in value_reader {
/// println!("JSON value: {}", value.unwrap());
/// }
/// ```
#[derive(Debug)]
pub struct ValueIter<'a, R: Read> {
reader: &'a mut BufReader<R>,
max_read_records: Option<usize>,
record_count: usize,
// reuse line buffer to avoid allocation on each record
line_buf: String,
}
impl<'a, R: Read> ValueIter<'a, R> {
/// Creates a new `ValueIter`
pub fn new(reader: &'a mut BufReader<R>, max_read_records: Option<usize>) -> Self {
Self {
reader,
max_read_records,
record_count: 0,
line_buf: String::new(),
}
}
}
impl<'a, R: Read> Iterator for ValueIter<'a, R> {
type Item = Result<Value, ArrowError>;
fn next(&mut self) -> Option<Self::Item> {
if let Some(max) = self.max_read_records {
if self.record_count >= max {
return None;
}
}
loop {
self.line_buf.truncate(0);
match self.reader.read_line(&mut self.line_buf) {
Ok(0) => {
// read_line returns 0 when stream reached EOF
return None;
}
Err(e) => {
return Some(Err(ArrowError::JsonError(format!(
"Failed to read JSON record: {e}"
))));
}
_ => {
let trimmed_s = self.line_buf.trim();
if trimmed_s.is_empty() {
// ignore empty lines
continue;
}
self.record_count += 1;
return Some(serde_json::from_str(trimmed_s).map_err(|e| {
ArrowError::JsonError(format!("Not valid JSON: {e}"))
}));
}
}
}
}
}
/// Infer the fields of a JSON file by reading the first n records of the file, with
/// `max_read_records` controlling the maximum number of records to read.
///
/// If `max_read_records` is not set, the whole file is read to infer its field types.
///
/// Contrary to [`infer_json_schema`], this function will seek back to the start of the `reader`.
/// That way, the `reader` can be used immediately afterwards to create a [`Reader`].
///
/// # Examples
/// ```
/// use std::fs::File;
/// use std::io::BufReader;
/// use arrow_json::reader::infer_json_schema_from_seekable;
///
/// let file = File::open("test/data/mixed_arrays.json").unwrap();
/// // file's cursor's offset at 0
/// let mut reader = BufReader::new(file);
/// let inferred_schema = infer_json_schema_from_seekable(&mut reader, None).unwrap();
/// // file's cursor's offset automatically set at 0
/// ```
pub fn infer_json_schema_from_seekable<R: Read + Seek>(
reader: &mut BufReader<R>,
max_read_records: Option<usize>,
) -> Result<Schema, ArrowError> {
let schema = infer_json_schema(reader, max_read_records);
// return the reader seek back to the start
reader.rewind()?;
schema
}
/// Infer the fields of a JSON file by reading the first n records of the buffer, with
/// `max_read_records` controlling the maximum number of records to read.
///
/// If `max_read_records` is not set, the whole file is read to infer its field types.
///
/// This function will not seek back to the start of the `reader`. The user has to manage the
/// original file's cursor. This function is useful when the `reader`'s cursor is not available
/// (does not implement [`Seek`]), such is the case for compressed streams decoders.
///
/// # Examples
/// ```
/// use std::fs::File;
/// use std::io::{BufReader, SeekFrom, Seek};
/// use flate2::read::GzDecoder;
/// use arrow_json::reader::infer_json_schema;
///
/// let mut file = File::open("test/data/mixed_arrays.json.gz").unwrap();
///
/// // file's cursor's offset at 0
/// let mut reader = BufReader::new(GzDecoder::new(&file));
/// let inferred_schema = infer_json_schema(&mut reader, None).unwrap();
/// // cursor's offset at end of file
///
/// // seek back to start so that the original file is usable again
/// file.seek(SeekFrom::Start(0)).unwrap();
/// ```
pub fn infer_json_schema<R: Read>(
reader: &mut BufReader<R>,
max_read_records: Option<usize>,
) -> Result<Schema, ArrowError> {
infer_json_schema_from_iterator(ValueIter::new(reader, max_read_records))
}
fn set_object_scalar_field_type(
field_types: &mut HashMap<String, InferredType>,
key: &str,
ftype: DataType,
) -> Result<(), ArrowError> {
if !field_types.contains_key(key) {
field_types.insert(key.to_string(), InferredType::Scalar(HashSet::new()));
}
match field_types.get_mut(key).unwrap() {
InferredType::Scalar(hs) => {
hs.insert(ftype);
Ok(())
}
// in case of column contains both scalar type and scalar array type, we convert type of
// this column to scalar array.
scalar_array @ InferredType::Array(_) => {
let mut hs = HashSet::new();
hs.insert(ftype);
scalar_array.merge(InferredType::Scalar(hs))?;
Ok(())
}
t => Err(ArrowError::JsonError(format!(
"Expected scalar or scalar array JSON type, found: {t:?}",
))),
}
}
fn infer_scalar_array_type(array: &[Value]) -> Result<InferredType, ArrowError> {
let mut hs = HashSet::new();
for v in array {
match v {
Value::Null => {}
Value::Number(n) => {
if n.is_i64() {
hs.insert(DataType::Int64);
} else {
hs.insert(DataType::Float64);
}
}
Value::Bool(_) => {
hs.insert(DataType::Boolean);
}
Value::String(_) => {
hs.insert(DataType::Utf8);
}
Value::Array(_) | Value::Object(_) => {
return Err(ArrowError::JsonError(format!(
"Expected scalar value for scalar array, got: {v:?}"
)));
}
}
}
Ok(InferredType::Scalar(hs))
}
fn infer_nested_array_type(array: &[Value]) -> Result<InferredType, ArrowError> {
let mut inner_ele_type = InferredType::Any;
for v in array {
match v {
Value::Array(inner_array) => {
inner_ele_type.merge(infer_array_element_type(inner_array)?)?;
}
x => {
return Err(ArrowError::JsonError(format!(
"Got non array element in nested array: {x:?}"
)));
}
}
}
Ok(InferredType::Array(Box::new(inner_ele_type)))
}
fn infer_struct_array_type(array: &[Value]) -> Result<InferredType, ArrowError> {
let mut field_types = HashMap::new();
for v in array {
match v {
Value::Object(map) => {
collect_field_types_from_object(&mut field_types, map)?;
}
_ => {
return Err(ArrowError::JsonError(format!(
"Expected struct value for struct array, got: {v:?}"
)));
}
}
}
Ok(InferredType::Object(field_types))
}
fn infer_array_element_type(array: &[Value]) -> Result<InferredType, ArrowError> {
match array.iter().take(1).next() {
None => Ok(InferredType::Any), // empty array, return any type that can be updated later
Some(a) => match a {
Value::Array(_) => infer_nested_array_type(array),
Value::Object(_) => infer_struct_array_type(array),
_ => infer_scalar_array_type(array),
},
}
}
fn collect_field_types_from_object(
field_types: &mut HashMap<String, InferredType>,
map: &JsonMap<String, Value>,
) -> Result<(), ArrowError> {
for (k, v) in map {
match v {
Value::Array(array) => {
let ele_type = infer_array_element_type(array)?;
if !field_types.contains_key(k) {
match ele_type {
InferredType::Scalar(_) => {
field_types.insert(
k.to_string(),
InferredType::Array(Box::new(InferredType::Scalar(
HashSet::new(),
))),
);
}
InferredType::Object(_) => {
field_types.insert(
k.to_string(),
InferredType::Array(Box::new(InferredType::Object(
HashMap::new(),
))),
);
}
InferredType::Any | InferredType::Array(_) => {
// set inner type to any for nested array as well
// so it can be updated properly from subsequent type merges
field_types.insert(
k.to_string(),
InferredType::Array(Box::new(InferredType::Any)),
);
}
}
}
match field_types.get_mut(k).unwrap() {
InferredType::Array(inner_type) => {
inner_type.merge(ele_type)?;
}
// in case of column contains both scalar type and scalar array type, we
// convert type of this column to scalar array.
field_type @ InferredType::Scalar(_) => {
field_type.merge(ele_type)?;
*field_type = InferredType::Array(Box::new(field_type.clone()));
}
t => {
return Err(ArrowError::JsonError(format!(
"Expected array json type, found: {t:?}",
)));
}
}
}
Value::Bool(_) => {
set_object_scalar_field_type(field_types, k, DataType::Boolean)?;
}
Value::Null => {
// do nothing, we treat json as nullable by default when
// inferring
}
Value::Number(n) => {
if n.is_f64() {
set_object_scalar_field_type(field_types, k, DataType::Float64)?;
} else {
// default to i64
set_object_scalar_field_type(field_types, k, DataType::Int64)?;
}
}
Value::String(_) => {
set_object_scalar_field_type(field_types, k, DataType::Utf8)?;
}
Value::Object(inner_map) => {
if !field_types.contains_key(k) {
field_types
.insert(k.to_string(), InferredType::Object(HashMap::new()));
}
match field_types.get_mut(k).unwrap() {
InferredType::Object(inner_field_types) => {
collect_field_types_from_object(inner_field_types, inner_map)?;
}
t => {
return Err(ArrowError::JsonError(format!(
"Expected object json type, found: {t:?}",
)));
}
}
}
}
}
Ok(())
}
/// Infer the fields of a JSON file by reading all items from the JSON Value Iterator.
///
/// The following type coercion logic is implemented:
/// * `Int64` and `Float64` are converted to `Float64`
/// * Lists and scalars are coerced to a list of a compatible scalar
/// * All other cases are coerced to `Utf8` (String)
///
/// Note that the above coercion logic is different from what Spark has, where it would default to
/// String type in case of List and Scalar values appeared in the same field.
///
/// The reason we diverge here is because we don't have utilities to deal with JSON data once it's
/// interpreted as Strings. We should match Spark's behavior once we added more JSON parsing
/// kernels in the future.
pub fn infer_json_schema_from_iterator<I, V>(value_iter: I) -> Result<Schema, ArrowError>
where
I: Iterator<Item = Result<V, ArrowError>>,
V: Borrow<Value>,
{
let mut field_types: HashMap<String, InferredType> = HashMap::new();
for record in value_iter {
match record?.borrow() {
Value::Object(map) => {
collect_field_types_from_object(&mut field_types, map)?;
}
value => {
return Err(ArrowError::JsonError(format!(
"Expected JSON record to be an object, found {value:?}"
)));
}
};
}
generate_schema(field_types)
}
/// JSON values to Arrow record batch decoder.
///
/// A [`Decoder`] decodes arbitrary streams of [`serde_json::Value`]s and
/// converts them to [`RecordBatch`]es. To decode JSON formatted files,
/// see [`Reader`].
///
/// Note: Consider instead using [`RawDecoder`] which is faster and will
/// eventually replace this implementation as part of [#3610]
///
/// # Examples
/// ```
/// use arrow_json::reader::{Decoder, DecoderOptions, ValueIter, infer_json_schema};
/// use std::fs::File;
/// use std::io::{BufReader, Seek, SeekFrom};
/// use std::sync::Arc;
///
/// let mut reader =
/// BufReader::new(File::open("test/data/mixed_arrays.json").unwrap());
/// let inferred_schema = infer_json_schema(&mut reader, None).unwrap();
/// let options = DecoderOptions::new()
/// .with_batch_size(1024);
/// let decoder = Decoder::new(Arc::new(inferred_schema), options);
///
/// // seek back to start so that the original file is usable again
/// reader.seek(SeekFrom::Start(0)).unwrap();
/// let mut value_reader = ValueIter::new(&mut reader, None);
/// let batch = decoder.next_batch(&mut value_reader).unwrap().unwrap();
/// assert_eq!(4, batch.num_rows());
/// assert_eq!(4, batch.num_columns());
/// ```
///
/// [`RawDecoder`]: crate::raw::RawDecoder
/// [#3610]: https://github.com/apache/arrow-rs/issues/3610
#[derive(Debug)]
#[deprecated(note = "Use RawDecoder instead")]
pub struct Decoder {
/// Explicit schema for the JSON file
schema: SchemaRef,
/// This is a collection of options for json decoder
options: DecoderOptions,
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// Options for JSON decoding
pub struct DecoderOptions {
/// Batch size (number of records to load each time), defaults to 1024 records
batch_size: usize,
/// Optional projection for which columns to load (case-sensitive names)
projection: Option<Vec<String>>,
/// optional HashMap of column name to its format string
format_strings: Option<HashMap<String, String>>,
}
impl Default for DecoderOptions {
fn default() -> Self {
Self {
batch_size: 1024,
projection: None,
format_strings: None,
}
}
}
impl DecoderOptions {
/// Creates a new `DecoderOptions`
pub fn new() -> Self {
Default::default()
}
/// Set the batch size (number of records to load at one time)
pub fn with_batch_size(mut self, batch_size: usize) -> Self {
self.batch_size = batch_size;
self
}
/// Set the reader's column projection
pub fn with_projection(mut self, projection: Vec<String>) -> Self {
self.projection = Some(projection);
self
}
/// Set the decoder's format Strings param
pub fn with_format_strings(
mut self,
format_strings: HashMap<String, String>,
) -> Self {
self.format_strings = Some(format_strings);
self
}
}
#[allow(deprecated)]
impl Decoder {
/// Create a new JSON decoder from some value that implements an
/// iterator over [`serde_json::Value`]s (aka implements the
/// `Iterator<Item=Result<Value>>` trait).
pub fn new(schema: SchemaRef, options: DecoderOptions) -> Self {
Self { schema, options }
}
/// Returns the schema of the reader, useful for getting the schema without reading
/// record batches
pub fn schema(&self) -> SchemaRef {
match &self.options.projection {
Some(projection) => {
let fields = self.schema.fields();
let projected_fields: Vec<Field> = fields
.iter()
.filter_map(|field| {
if projection.contains(field.name()) {
Some(field.clone())
} else {
None
}
})
.collect();
Arc::new(Schema::new(projected_fields))
}
None => self.schema.clone(),
}
}
/// Read the next batch of [`serde_json::Value`] records from the
/// interator into a [`RecordBatch`].
///
/// Returns `None` if the input iterator is exhausted.
pub fn next_batch<I>(
&self,
value_iter: &mut I,
) -> Result<Option<RecordBatch>, ArrowError>
where
I: Iterator<Item = Result<Value, ArrowError>>,
{
let batch_size = self.options.batch_size;
let mut rows: Vec<Value> = Vec::with_capacity(batch_size);
for value in value_iter.by_ref().take(batch_size) {
let v = value?;
match v {
Value::Object(_) => rows.push(v),
_ => {
return Err(ArrowError::JsonError(format!(
"Row needs to be of type object, got: {v:?}"
)));
}
}
}
if rows.is_empty() {
// reached end of file
return Ok(None);
}
let rows = &rows[..];
let arrays =
self.build_struct_array(rows, self.schema.fields(), &self.options.projection);
let projected_fields = if let Some(projection) = self.options.projection.as_ref()
{
projection
.iter()
.filter_map(|name| self.schema.column_with_name(name))
.map(|(_, field)| field.clone())
.collect()
} else {
self.schema.fields().to_vec()
};
let projected_schema = Arc::new(Schema::new(projected_fields));
arrays.and_then(|arr| {
RecordBatch::try_new_with_options(
projected_schema,
arr,
&RecordBatchOptions::new()
.with_match_field_names(true)
.with_row_count(Some(rows.len())),
)
.map(Some)
})
}
fn build_wrapped_list_array(
&self,
rows: &[Value],
col_name: &str,
key_type: &DataType,
) -> Result<ArrayRef, ArrowError> {
match *key_type {
DataType::Int8 => {
let dtype = DataType::Dictionary(
Box::new(DataType::Int8),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<Int8Type>(&dtype, col_name, rows)
}
DataType::Int16 => {
let dtype = DataType::Dictionary(
Box::new(DataType::Int16),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<Int16Type>(&dtype, col_name, rows)
}
DataType::Int32 => {
let dtype = DataType::Dictionary(
Box::new(DataType::Int32),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<Int32Type>(&dtype, col_name, rows)
}
DataType::Int64 => {
let dtype = DataType::Dictionary(
Box::new(DataType::Int64),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<Int64Type>(&dtype, col_name, rows)
}
DataType::UInt8 => {
let dtype = DataType::Dictionary(
Box::new(DataType::UInt8),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<UInt8Type>(&dtype, col_name, rows)
}
DataType::UInt16 => {
let dtype = DataType::Dictionary(
Box::new(DataType::UInt16),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<UInt16Type>(&dtype, col_name, rows)
}
DataType::UInt32 => {
let dtype = DataType::Dictionary(
Box::new(DataType::UInt32),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<UInt32Type>(&dtype, col_name, rows)
}
DataType::UInt64 => {
let dtype = DataType::Dictionary(
Box::new(DataType::UInt64),
Box::new(DataType::Utf8),
);
self.list_array_string_array_builder::<UInt64Type>(&dtype, col_name, rows)
}
ref e => Err(ArrowError::JsonError(format!(
"Data type is currently not supported for dictionaries in list : {e:?}"
))),
}
}
#[inline(always)]
fn list_array_string_array_builder<DT>(
&self,
data_type: &DataType,
col_name: &str,
rows: &[Value],
) -> Result<ArrayRef, ArrowError>
where
DT: ArrowPrimitiveType + ArrowDictionaryKeyType,
{
let mut builder: Box<dyn ArrayBuilder> = match data_type {
DataType::Utf8 => {
let values_builder =
StringBuilder::with_capacity(rows.len(), rows.len() * 5);
Box::new(ListBuilder::new(values_builder))
}
DataType::Dictionary(_, _) => {
let values_builder =
self.build_string_dictionary_builder::<DT>(rows.len() * 5);
Box::new(ListBuilder::new(values_builder))
}
e => {
return Err(ArrowError::JsonError(format!(
"Nested list data builder type is not supported: {e:?}"
)))
}
};
for row in rows {
if let Some(value) = row.get(col_name) {
// value can be an array or a scalar
let vals: Vec<Option<String>> = if let Value::String(v) = value {
vec![Some(v.to_string())]
} else if let Value::Array(n) = value {
n.iter()
.map(|v: &Value| {
if v.is_string() {
Some(v.as_str().unwrap().to_string())
} else if v.is_array() || v.is_object() || v.is_null() {
// implicitly drop nested values
// TODO support deep-nesting
None
} else {
Some(v.to_string())
}
})
.collect()
} else if let Value::Null = value {
vec![None]
} else if !value.is_object() {
vec![Some(value.to_string())]
} else {
return Err(ArrowError::JsonError(
"Only scalars are currently supported in JSON arrays".to_string(),
));
};
// TODO: ARROW-10335: APIs of dictionary arrays and others are different. Unify
// them.
match data_type {
DataType::Utf8 => {
let builder = builder
.as_any_mut()
.downcast_mut::<ListBuilder<StringBuilder>>()
.ok_or_else(||ArrowError::JsonError(
"Cast failed for ListBuilder<StringBuilder> during nested data parsing".to_string(),
))?;
for val in vals {
if let Some(v) = val {
builder.values().append_value(&v);
} else {
builder.values().append_null();
};
}
// Append to the list
builder.append(true);
}
DataType::Dictionary(_, _) => {
let builder = builder.as_any_mut().downcast_mut::<ListBuilder<StringDictionaryBuilder<DT>>>().ok_or_else(||ArrowError::JsonError(
"Cast failed for ListBuilder<StringDictionaryBuilder> during nested data parsing".to_string(),
))?;
for val in vals {
if let Some(v) = val {
let _ = builder.values().append(&v);
} else {
builder.values().append_null();
};
}
// Append to the list
builder.append(true);
}
e => {
return Err(ArrowError::JsonError(format!(
"Nested list data builder type is not supported: {e:?}"
)))
}
}
}
}
Ok(builder.finish() as ArrayRef)
}
#[inline(always)]
fn build_string_dictionary_builder<T>(
&self,
row_len: usize,
) -> StringDictionaryBuilder<T>
where
T: ArrowPrimitiveType + ArrowDictionaryKeyType,
{
StringDictionaryBuilder::with_capacity(row_len, row_len, row_len * 5)
}
#[inline(always)]
fn build_string_dictionary_array(
&self,
rows: &[Value],
col_name: &str,
key_type: &DataType,
value_type: &DataType,
) -> Result<ArrayRef, ArrowError> {
if let DataType::Utf8 = *value_type {
match *key_type {
DataType::Int8 => self.build_dictionary_array::<Int8Type>(rows, col_name),
DataType::Int16 => {
self.build_dictionary_array::<Int16Type>(rows, col_name)
}
DataType::Int32 => {
self.build_dictionary_array::<Int32Type>(rows, col_name)
}
DataType::Int64 => {
self.build_dictionary_array::<Int64Type>(rows, col_name)
}
DataType::UInt8 => {
self.build_dictionary_array::<UInt8Type>(rows, col_name)
}
DataType::UInt16 => {
self.build_dictionary_array::<UInt16Type>(rows, col_name)
}
DataType::UInt32 => {
self.build_dictionary_array::<UInt32Type>(rows, col_name)
}
DataType::UInt64 => {
self.build_dictionary_array::<UInt64Type>(rows, col_name)
}
_ => Err(ArrowError::JsonError(
"unsupported dictionary key type".to_string(),
)),
}
} else {
Err(ArrowError::JsonError(
"dictionary types other than UTF-8 not yet supported".to_string(),
))
}
}
fn build_boolean_array(
&self,
rows: &[Value],
col_name: &str,
) -> Result<ArrayRef, ArrowError> {
let mut builder = BooleanBuilder::with_capacity(rows.len());
for row in rows {
if let Some(value) = row.get(col_name) {
if let Some(boolean) = value.as_bool() {
builder.append_value(boolean);
} else {
builder.append_null();
}
} else {
builder.append_null();
}
}
Ok(Arc::new(builder.finish()))
}
fn build_primitive_array<T: ArrowPrimitiveType + Parser>(
&self,
rows: &[Value],
col_name: &str,
) -> Result<ArrayRef, ArrowError>
where
T: ArrowPrimitiveType,
T::Native: num::NumCast,
{
let format_string = self
.options
.format_strings
.as_ref()
.and_then(|fmts| fmts.get(col_name));
Ok(Arc::new(
rows.iter()
.map(|row| {