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

Support passing dict to add JSON field #158

Merged
merged 1 commit into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
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
27 changes: 18 additions & 9 deletions src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,19 +672,28 @@ impl Document {
self.add_value(field_name, bytes);
}

/// Add a bytes value to the document.
/// Add a JSON value to the document.
///
/// Args:
/// field_name (str): The field for which we are adding the bytes.
/// value (str): The json object that will be added to the document.
/// value (str | Dict[str, Any]): The JSON object that will be added
/// to the document.
///
/// Raises a ValueError if the json is invalid.
fn add_json(&mut self, field_name: String, json: &str) -> PyResult<()> {
let json_object: serde_json::Value =
serde_json::from_str(json).map_err(to_pyerr)?;
self.add_value(field_name, json_object);

Ok(())
/// Raises a ValueError if the JSON is invalid.
fn add_json(&mut self, field_name: String, value: &PyAny) -> PyResult<()> {
type JsonMap = serde_json::Map<String, serde_json::Value>;

if let Ok(json_str) = value.extract::<&str>() {
let json_map: JsonMap =
serde_json::from_str(json_str).map_err(to_pyerr)?;
self.add_value(field_name, json_map);
Ok(())
} else if let Ok(json_map) = pythonize::depythonize::<JsonMap>(value) {
self.add_value(field_name, json_map);
Ok(())
} else {
Err(to_pyerr("Invalid JSON object. Expected valid JSON string or Dict[str, Any]."))
}
cjrh marked this conversation as resolved.
Show resolved Hide resolved
}

/// Returns the number of added fields that have been added to the document
Expand Down
8 changes: 4 additions & 4 deletions tests/tantivy_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -786,12 +786,12 @@ def test_query_from_json_field(self):
doc = Document()
doc.add_json(
"attributes",
"""{
"order":1.2,
{
"order": 1.2,
"target": "submit-button",
"cart": {"product_id": 133},
"description": "das keyboard"
}""",
"description": "das keyboard",
},
)

writer.add_document(doc)
Expand Down
Loading