Skip to content

Commit 57afc5a

Browse files
Add accepts empty values
When building the Solr document, empty values will not be skipped if they are also present in the fieldUpdates. Tests are included.
1 parent 98c78c2 commit 57afc5a

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

pysolr.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -940,18 +940,26 @@ def _build_xml_doc(self, doc, boost=None, fieldUpdates=None):
940940
else:
941941
values = (value,)
942942

943+
use_field_updates = fieldUpdates and key in fieldUpdates
944+
if use_field_updates and not values:
945+
values = ("",)
943946
for bit in values:
947+
948+
attrs = {"name": key}
949+
944950
if self._is_null_value(bit):
945-
continue
951+
if use_field_updates:
952+
bit = ""
953+
attrs["null"] = "true"
954+
else:
955+
continue
946956

947957
if key == "_doc":
948958
child = self._build_xml_doc(bit, boost)
949959
doc_elem.append(child)
950960
continue
951961

952-
attrs = {"name": key}
953-
954-
if fieldUpdates and key in fieldUpdates:
962+
if use_field_updates:
955963
attrs["update"] = fieldUpdates[key]
956964

957965
if boost and key in boost:

tests/test_client.py

+39
Original file line numberDiff line numberDiff line change
@@ -720,6 +720,45 @@ def test__build_xml_doc_with_sub_docs(self):
720720
self.assertEqual(children_docs[0].find("*[@name='id']").text, sub_docs[0]["id"])
721721
self.assertEqual(children_docs[1].find("*[@name='id']").text, sub_docs[1]["id"])
722722

723+
def test__build_xml_doc_with_empty_values(self):
724+
doc = {
725+
"id": "doc_1",
726+
"title": "",
727+
"price": None,
728+
"tags": [],
729+
}
730+
doc_xml = force_unicode(
731+
ElementTree.tostring(self.solr._build_xml_doc(doc), encoding="utf-8")
732+
)
733+
self.assertNotIn('<field name="title" />', doc_xml)
734+
self.assertNotIn('<field name="price" />', doc_xml)
735+
self.assertNotIn('<field name="tags" />', doc_xml)
736+
self.assertIn('<field name="id">doc_1</field>', doc_xml)
737+
self.assertEqual(len(doc_xml), 41)
738+
739+
def test__build_xml_doc_with_empty_values_and_field_updates(self):
740+
doc = {
741+
"id": "doc_1",
742+
"title": "",
743+
"price": None,
744+
"tags": [],
745+
}
746+
fieldUpdates = {
747+
"title": "set",
748+
"tags": "set",
749+
}
750+
doc_xml = force_unicode(
751+
ElementTree.tostring(
752+
self.solr._build_xml_doc(doc, fieldUpdates=fieldUpdates),
753+
encoding="utf-8",
754+
)
755+
)
756+
self.assertIn('<field name="title" null="true" update="set" />', doc_xml)
757+
self.assertNotIn('<field name="price" />', doc_xml)
758+
self.assertIn('<field name="tags" null="true" update="set" />', doc_xml)
759+
self.assertIn('<field name="id">doc_1</field>', doc_xml)
760+
self.assertEqual(len(doc_xml), 134)
761+
723762
def test_build_json_doc_matches_xml(self):
724763
doc = {
725764
"id": "doc_1",

0 commit comments

Comments
 (0)