You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "kumarlokesh (via GitHub)" <gi...@apache.org> on 2025/05/29 20:15:23 UTC

[PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

kumarlokesh opened a new pull request, #7566:
URL: https://github.com/apache/arrow-rs/pull/7566

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #7302.
   
   # Rationale for this change
    
   <!--
   Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
   Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
   -->
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   1. Added native `UnionEncoder`
   2. Refactored test helper function `make_fallback_encoder_test_data` to use
   native `UnionEncoder`. Renamed it to `make_union_encoder_test_data`.
   
   # Are there any user-facing changes?
   
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!---
   If there are any breaking changes to public APIs, please call them out.
   -->
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #7566:
URL: https://github.com/apache/arrow-rs/pull/7566#issuecomment-4805868341

   Thank you for your contribution. Unfortunately, this pull request is stale because it has been open 60 days with no activity. Please remove the stale label or comment or this will be closed in 7 days.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #7566:
URL: https://github.com/apache/arrow-rs/pull/7566#discussion_r2115928606


##########
arrow-json/src/writer/encoder.rs:
##########
@@ -805,3 +812,131 @@ where
         out.push(b'"');
     }
 }
+
+/// Configuration for how to encode union values.
+///
+/// Controls whether to encode union values with or without type information.
+/// The format choice impacts the JSON output structure and readability.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum UnionFormat {
+    #[allow(dead_code)]
+    /// Encode as a simple value without type information (e.g., `1` or `"a"`).
+    Simple,
+
+    /// Encode as an object with type_id and value fields (e.g., `{"type_id": 0, "value": 1}`).
+    /// This is the default format and preserves complete type information.
+    WithTypeInfo,
+}
+
+/// Encoder for Union arrays that handles encoding union values according to the specified format.
+/// See [`UnionFormat`] for details on the available formats.
+pub(crate) struct UnionEncoder<'a> {
+    type_ids: &'a ScalarBuffer<i8>,
+    offsets: Option<&'a ScalarBuffer<i32>>,
+    field_encoders: Vec<NullableEncoder<'a>>,
+    format: UnionFormat,
+    type_id_to_index: std::collections::HashMap<i8, usize>,
+}
+
+impl<'a> UnionEncoder<'a> {
+    /// Create a new UnionEncoder for the given UnionArray.
+    ///
+    /// By default, this uses [`UnionFormat::WithTypeInfo`] to preserve complete type information.
+    /// For simpler output without type information, use [`UnionFormat::Simple`].
+    pub fn try_new(
+        field: &'a FieldRef,
+        array: &'a UnionArray,
+        options: &'a EncoderOptions,
+    ) -> Result<Self, ArrowError> {
+        Self::try_new_with_format(field, array, options, UnionFormat::WithTypeInfo)
+    }
+
+    /// Create a new UnionEncoder with a specific format.
+    ///
+    /// This allows explicitly choosing how to encode union values:
+    ///
+    /// - Use [`UnionFormat::Simple`] for cleaner JSON output without type information,
+    ///   producing values like: `1` or `"a"`
+    /// - Use [`UnionFormat::WithTypeInfo`] to preserve type information,
+    ///   producing values like: `{"type_id": 0, "value": 1}`
+    ///
+    /// See [`UnionFormat`] for more details about each format.
+    pub fn try_new_with_format(
+        _field: &'a FieldRef,
+        array: &'a UnionArray,
+        options: &'a EncoderOptions,
+        format: UnionFormat,
+    ) -> Result<Self, ArrowError> {
+        let type_ids = array.type_ids();
+
+        let union_fields = match array.data_type() {
+            DataType::Union(fields, _) => fields,
+            _ => unreachable!("Union array's data type is not a union!"),

Review Comment:
   Perhaps this could return a real error rather than panic'ing (given that this function already returns a `Result`)



##########
arrow-json/src/writer/encoder.rs:
##########
@@ -805,3 +812,131 @@ where
         out.push(b'"');
     }
 }
+
+/// Configuration for how to encode union values.
+///
+/// Controls whether to encode union values with or without type information.
+/// The format choice impacts the JSON output structure and readability.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum UnionFormat {
+    #[allow(dead_code)]

Review Comment:
   Why the `dead_code`?



##########
arrow-json/src/writer/mod.rs:
##########
@@ -2058,83 +2059,37 @@ mod tests {
         assert_json_eq(&buf, expected);
     }
 
-    fn make_fallback_encoder_test_data() -> (RecordBatch, Arc<dyn EncoderFactory>) {

Review Comment:
   are there any other usecases for a fallback encoder? I feel like that usecase is still quite valid
   
   What about `REEArray` or something 🤔 



##########
arrow-json/src/writer/encoder.rs:
##########
@@ -805,3 +812,131 @@ where
         out.push(b'"');
     }
 }
+
+/// Configuration for how to encode union values.
+///
+/// Controls whether to encode union values with or without type information.
+/// The format choice impacts the JSON output structure and readability.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum UnionFormat {
+    #[allow(dead_code)]
+    /// Encode as a simple value without type information (e.g., `1` or `"a"`).
+    Simple,
+
+    /// Encode as an object with type_id and value fields (e.g., `{"type_id": 0, "value": 1}`).
+    /// This is the default format and preserves complete type information.

Review Comment:
   👍 



##########
arrow-json/src/writer/encoder.rs:
##########
@@ -805,3 +812,131 @@ where
         out.push(b'"');
     }
 }
+
+/// Configuration for how to encode union values.
+///
+/// Controls whether to encode union values with or without type information.
+/// The format choice impacts the JSON output structure and readability.
+#[derive(Debug, Clone, Copy)]
+pub(crate) enum UnionFormat {
+    #[allow(dead_code)]
+    /// Encode as a simple value without type information (e.g., `1` or `"a"`).
+    Simple,
+
+    /// Encode as an object with type_id and value fields (e.g., `{"type_id": 0, "value": 1}`).
+    /// This is the default format and preserves complete type information.
+    WithTypeInfo,
+}
+
+/// Encoder for Union arrays that handles encoding union values according to the specified format.
+/// See [`UnionFormat`] for details on the available formats.
+pub(crate) struct UnionEncoder<'a> {
+    type_ids: &'a ScalarBuffer<i8>,
+    offsets: Option<&'a ScalarBuffer<i32>>,
+    field_encoders: Vec<NullableEncoder<'a>>,
+    format: UnionFormat,
+    type_id_to_index: std::collections::HashMap<i8, usize>,
+}
+
+impl<'a> UnionEncoder<'a> {
+    /// Create a new UnionEncoder for the given UnionArray.
+    ///
+    /// By default, this uses [`UnionFormat::WithTypeInfo`] to preserve complete type information.
+    /// For simpler output without type information, use [`UnionFormat::Simple`].
+    pub fn try_new(
+        field: &'a FieldRef,
+        array: &'a UnionArray,
+        options: &'a EncoderOptions,
+    ) -> Result<Self, ArrowError> {
+        Self::try_new_with_format(field, array, options, UnionFormat::WithTypeInfo)
+    }
+
+    /// Create a new UnionEncoder with a specific format.
+    ///
+    /// This allows explicitly choosing how to encode union values:
+    ///
+    /// - Use [`UnionFormat::Simple`] for cleaner JSON output without type information,
+    ///   producing values like: `1` or `"a"`
+    /// - Use [`UnionFormat::WithTypeInfo`] to preserve type information,
+    ///   producing values like: `{"type_id": 0, "value": 1}`
+    ///
+    /// See [`UnionFormat`] for more details about each format.
+    pub fn try_new_with_format(
+        _field: &'a FieldRef,
+        array: &'a UnionArray,
+        options: &'a EncoderOptions,
+        format: UnionFormat,
+    ) -> Result<Self, ArrowError> {
+        let type_ids = array.type_ids();
+
+        let union_fields = match array.data_type() {
+            DataType::Union(fields, _) => fields,
+            _ => unreachable!("Union array's data type is not a union!"),
+        };
+
+        let mut field_encoders = Vec::new();
+        let mut type_id_to_index = std::collections::HashMap::new();
+
+        for (idx, (type_id, field_ref)) in union_fields.iter().enumerate() {
+            let child = array.child(type_id);
+            let encoder = make_encoder(field_ref, child, options)?;
+            field_encoders.push(encoder);
+            type_id_to_index.insert(type_id, idx);
+        }
+
+        Ok(Self {
+            type_ids,
+            offsets: array.offsets(),
+            field_encoders,
+            format,
+            type_id_to_index,
+        })
+    }
+}
+
+impl Encoder for UnionEncoder<'_> {
+    fn encode(&mut self, idx: usize, out: &mut Vec<u8>) {
+        let type_id = self.type_ids[idx];
+        let value_idx = match self.offsets {
+            Some(offsets) => offsets[idx] as usize,
+            None => idx,
+        };
+
+        match self.format {
+            UnionFormat::Simple => {
+                if let Some(&encoder_idx) = self.type_id_to_index.get(&type_id) {

Review Comment:
   when would the type_id ever not be found? It seems like this means invalid input data -- and should be a panic in my opinion
   
   Likewise below



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #7566:
URL: https://github.com/apache/arrow-rs/pull/7566#discussion_r2116710100


##########
arrow-json/src/writer/mod.rs:
##########
@@ -2058,83 +2059,37 @@ mod tests {
         assert_json_eq(&buf, expected);
     }
 
-    fn make_fallback_encoder_test_data() -> (RecordBatch, Arc<dyn EncoderFactory>) {

Review Comment:
   It was pointed out in the original PR that geometry types were a use case



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #7566:
URL: https://github.com/apache/arrow-rs/pull/7566#issuecomment-2954345029

   Marking as draft as I think this PR is no longer waiting on feedback and I am trying to make it easier to find PRs in need of review. Please mark it as ready for review when it is ready for another look 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] closed pull request #7566: Add native support to write out UnionArray in JSON writer
URL: https://github.com/apache/arrow-rs/pull/7566


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] Add native support to write out UnionArray in JSON writer [arrow-rs]

Posted by "adriangb (via GitHub)" <gi...@apache.org>.
adriangb commented on code in PR #7566:
URL: https://github.com/apache/arrow-rs/pull/7566#discussion_r2116711200


##########
arrow-json/src/writer/mod.rs:
##########
@@ -2058,83 +2059,37 @@ mod tests {
         assert_json_eq(&buf, expected);
     }
 
-    fn make_fallback_encoder_test_data() -> (RecordBatch, Arc<dyn EncoderFactory>) {

Review Comment:
   Can we make the tests write out ints as bytes, floats as strings or something like that?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org