Skip to content

feat: add JSONB read/write support - #4566

Merged
Xuanwo merged 19 commits into
mainfrom
add-json-in-lance
Aug 27, 2025
Merged

Xuanwo merged 19 commits into
mainfrom
add-json-in-lance

Conversation

@Xuanwo

@Xuanwo Xuanwo commented Aug 26, 2025 •

Copy link
Copy Markdown
Member

Part of #4516

This PR will add basic JSONB read/write support so users can use them like an extension arrow type like blob and bfloat16.

"""Test filtering and selecting with JSON columns."""

json_data = [
    {"user_id": 1, "preferences": {"theme": "dark"}},
    {"user_id": 2, "preferences": {"theme": "light"}},
    {"user_id": 3, "preferences": {"theme": "dark"}},
]

json_strings = [json.dumps(d) for d in json_data]
json_ext_array = JsonArray.from_json_strings(json_strings)

table = pa.table(
    {
        "id": pa.array([1, 2, 3]),
        "user_data": json_ext_array,
        "active": pa.array([True, False, True]),
    },
    schema=pa.schema(
        [
            pa.field("id", pa.int32()),
            json_field("user_data"),
            pa.field("active", pa.bool_()),
        ]
    ),
)

with tempfile.TemporaryDirectory() as tmpdir:
    dataset_path = Path(tmpdir) / "filter_test.lance"
    lance.write_dataset(table, dataset_path, data_storage_version="2.2")
    dataset = lance.dataset(dataset_path)

    # Test column selection
    selected = dataset.to_table(columns=["id", "user_data"])
    assert selected.num_columns == 2
    assert "active" not in selected.column_names

This PR was primarily authored with Claude Code using Opus 4.1 and then hand-reviewed by me. I AM responsible for every change made in this PR. I aimed to keep it aligned with our goals, though I may have missed minor issues. Please flag anything that feels off, I'll fix it quickly.

Xuanwo added 2 commits August 26, 2025 12:31
Signed-off-by: Xuanwo <[email protected]>
@github-actions github-actions Bot added enhancement New feature or request A-python Python bindings labels Aug 26, 2025
@github-actions

This comment was marked as resolved.

@Xuanwo Xuanwo changed the title feat: Add JSONB read/write support feat: add JSONB read/write support Aug 26, 2025
@github-actions github-actions Bot added the A-java Java bindings + JNI label Aug 26, 2025
@codecov-commenter

codecov-commenter commented Aug 26, 2025 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 52.38095% with 180 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.89%. Comparing base (a13d41b) to head (244d2eb).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
rust/lance-arrow/src/json.rs 53.75% 105 Missing and 6 partials ⚠️
rust/lance-datafusion/src/udf/json.rs 60.00% 32 Missing and 4 partials ⚠️
rust/lance/src/dataset.rs 33.33% 12 Missing ⚠️
rust/lance/src/dataset/write/insert.rs 33.33% 9 Missing and 1 partial ⚠️
rust/lance-core/src/datatypes/field.rs 27.27% 5 Missing and 3 partials ⚠️
rust/lance-core/src/datatypes.rs 0.00% 0 Missing and 1 partial ⚠️
rust/lance-file/src/v2/reader.rs 0.00% 1 Missing ⚠️
rust/lance-file/src/v2/writer.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4566      +/-   ##
==========================================
- Coverage   80.98%   80.89%   -0.10%     
==========================================
  Files         312      314       +2     
  Lines      114696   115072     +376     
  Branches   114696   115072     +376     
==========================================
+ Hits        92886    93083     +197     
- Misses      18539    18703     +164     
- Partials     3271     3286      +15     
Flag Coverage Δ
unittests 80.89% <52.38%> (-0.10%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Signed-off-by: Xuanwo <[email protected]>

@westonpace westonpace left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I have some suggestions but overall I think this is a good starting point for moving forward on JSON.

Some of the test cases in test_json.py seem a little extraneous.

Also, someday, I'd love to get rid of logical type from the lance table format and just use Arrow there too but definitely we should save that for a future PR 😆

Comment thread python/python/lance/_arrow/json.py Resolved
Comment on lines +48 to +49
# Write the dataset with version 2.2 (required for JSON support)
lance.write_dataset(table, dataset_path, data_storage_version="2.2")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I don't think we actually need 2.2 if we're doing everything at the table level (originally I thought you were adding JSONB to file level)

Comment thread python/python/tests/test_json.py Resolved
Comment thread python/python/tests/test_json.py Resolved
Comment thread python/python/tests/test_json.py Resolved
}
}

impl TryFrom<&LargeStringArray> for JsonArray {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hmm, supporting both string and large string is ok, but not sure it is vital at the moment if it becomes an inconvenience.

"binary" => Some(Binary),
"large_string" => Some(LargeUtf8),
"large_binary" => Some(LargeBinary),
"json" => Some(LargeBinary),

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Does this mean JSON is always large binary?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Yes for now. I'm open to provide Binary support for small json. Maybe it's worth a seperate issue?

Comment thread rust/lance-datafusion/src/udf/json.rs Resolved
Comment thread rust/lance/src/dataset.rs
Comment on lines +556 to +574
let schema_has_json = manifest.schema.fields_pre_order().any(|field| {
let arrow_field = ArrowField::from(field);
lance_arrow::json::has_json_fields(&arrow_field)
});

if schema_has_json {
let storage_version = manifest.data_storage_format.lance_file_version()?;
if storage_version < lance_file::version::LanceFileVersion::V2_2 {
return Err(Error::NotSupported {
source: format!(
"Cannot read dataset with JSON fields from file format version {}. \
JSON fields require Lance file format version 2.2 or later.",
storage_version
)
.into(),
location: location!(),
});
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Can we remove this check for now since we aren't modifying file format? Maybe once this feature stabilzes we can put it back (if we add variant type to file format) or handle it with a table feature flag.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I'm hesitant about this because the binary format for jsonb is not quite stable and is still evolving. My current plan is to change into pg compatible jsonb format in the future.

@Xuanwo Xuanwo Aug 27, 2025 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Tracked at #4575, I'm open to create a new PR to get it removed. And for now, I will merge this PR first.

Comment on lines +367 to +383
let schema_has_json = data_schema.fields_pre_order().any(|field| {
let arrow_field = ArrowField::from(field);
lance_arrow::json::has_json_fields(&arrow_field)
});

if schema_has_json && context.storage_version < LanceFileVersion::V2_2 {
return Err(Error::NotSupported {
source: format!(
"JSON fields require Lance file format version 2.2 or later. \
Current version: {}. Please specify data_storage_version='2.2' in WriteParams",
context.storage_version
)
.into(),
location: location!(),
});
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Same as above, let's remove this check for now

@Xuanwo
Xuanwo merged commit 40c9e54 into main Aug 27, 2025
@Xuanwo
Xuanwo deleted the add-json-in-lance branch August 27, 2025 08:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-java Java bindings + JNI A-python Python bindings enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants