-
Notifications
You must be signed in to change notification settings - Fork 472
chore: add an initial internal sql-json-path query implementation #7620
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
Draft
sunng87
wants to merge
4
commits into
GreptimeTeam:main
Choose a base branch
from
sunng87:feature/sql-json-path
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
127 changes: 127 additions & 0 deletions
127
src/common/function/src/scalars/json/json_path_query.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| // Copyright 2023 Greptime Team | ||
| // | ||
| // Licensed 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. | ||
|
|
||
| use std::fmt::{self, Display}; | ||
| use std::sync::Arc; | ||
|
|
||
| use arrow::array::{Array, AsArray, BinaryBuilder}; | ||
| use arrow::compute; | ||
| use datafusion_common::DataFusionError; | ||
| use datafusion_common::arrow::datatypes::DataType; | ||
| use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, Signature}; | ||
| use sql_json_path::JsonPath; | ||
|
|
||
| use crate::function::{Function, extract_args}; | ||
| use crate::helper; | ||
|
|
||
| /// Query JSON data using the given JSON path. | ||
| #[derive(Clone, Debug)] | ||
| pub(crate) struct JsonPathQueryFunction { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for JsonPathQueryFunction { | ||
| fn default() -> Self { | ||
| Self { | ||
| signature: helper::one_of_sigs2( | ||
| vec![DataType::Binary, DataType::BinaryView], | ||
| vec![DataType::Utf8, DataType::Utf8View], | ||
| ), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| const NAME: &str = "json_path_query"; | ||
|
|
||
| impl Function for JsonPathQueryFunction { | ||
| fn name(&self) -> &str { | ||
| NAME | ||
| } | ||
|
|
||
| fn return_type(&self, _: &[DataType]) -> datafusion_common::Result<DataType> { | ||
| Ok(DataType::Binary) | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn invoke_with_args( | ||
| &self, | ||
| args: ScalarFunctionArgs, | ||
| ) -> datafusion_common::Result<ColumnarValue> { | ||
| let [arg0, arg1] = extract_args(self.name(), &args)?; | ||
| let arg0 = compute::cast(&arg0, &DataType::BinaryView)?; | ||
| let jsons = arg0.as_binary_view(); | ||
| let arg1 = compute::cast(&arg1, &DataType::Utf8View)?; | ||
| let paths = arg1.as_string_view(); | ||
|
|
||
| let size = jsons.len(); | ||
| let mut builder = BinaryBuilder::with_capacity(size, size * 32); | ||
|
|
||
| for i in 0..size { | ||
| let json = jsons.is_valid(i).then(|| jsons.value(i)); | ||
| let path = paths.is_valid(i).then(|| paths.value(i)); | ||
|
|
||
| let result = match (json, path) { | ||
| (Some(json), Some(path)) => { | ||
| if !jsonb::is_null(json) { | ||
| let jsonb_value = jsonb::from_slice(json).map_err(|e| { | ||
| DataFusionError::Execution(format!("invalid jsonb binary: {e}")) | ||
| })?; | ||
| let mut json_str = jsonb_value.to_string(); | ||
| let json_value: simd_json::OwnedValue = unsafe { | ||
| simd_json::from_str(&mut json_str).map_err(|e| { | ||
| DataFusionError::Execution(format!("failed to parse json: {e}")) | ||
| })? | ||
| }; | ||
| let json_path = JsonPath::new(path).map_err(|e| { | ||
| DataFusionError::Execution(format!("invalid json path '{path}': {e}")) | ||
| })?; | ||
| let nodes = json_path.query(&json_value).map_err(|e| { | ||
| DataFusionError::Execution(format!( | ||
| "failed to evaluate json path '{path}': {e}" | ||
| )) | ||
| })?; | ||
| let node_values: Vec<simd_json::OwnedValue> = | ||
| nodes.into_iter().map(|n| n.into_owned()).collect(); | ||
| let result_json = simd_json::OwnedValue::Array(Box::new(node_values)); | ||
| let json_bytes = simd_json::to_vec(&result_json).map_err(|e| { | ||
| DataFusionError::Execution(format!("failed to serialize json: {e}")) | ||
| })?; | ||
| let result_jsonb: jsonb::Value = | ||
| jsonb::from_slice(&json_bytes).map_err(|e| { | ||
| DataFusionError::Execution(format!( | ||
| "failed to deserialize json: {e}" | ||
| )) | ||
| })?; | ||
| Some(result_jsonb.to_vec()) | ||
| } else { | ||
| None | ||
| } | ||
| } | ||
| _ => None, | ||
| }; | ||
| builder.append_option(result.as_deref()); | ||
| } | ||
|
|
||
| Ok(ColumnarValue::Array(Arc::new(builder.finish()))) | ||
| } | ||
| } | ||
|
|
||
| impl Display for JsonPathQueryFunction { | ||
| fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
| write!(f, "JSON_PATH_QUERY") | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: best if we can unify the json string deserialization. Currently we have both serde_json and simd_json.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@sunng87 PTAL