@@ -316,15 +316,29 @@ public boolean hasField(String path, boolean failOutOfRange) {
316316
317317 /**
318318 * Removes the field identified by the provided path.
319+ *
319320 * @param path the path of the field to be removed
320321 * @throws IllegalArgumentException if the path is null, empty, invalid or if the field doesn't exist.
321322 */
322323 public void removeField (String path ) {
324+ removeField (path , false );
325+ }
326+
327+ /**
328+ * Removes the field identified by the provided path.
329+ *
330+ * @param path the path of the field to be removed
331+ * @param ignoreMissing The flag to determine whether to throw an exception when `path` is not found in the document.
332+ * @throws IllegalArgumentException if the path is null, empty, or invalid; or if the field doesn't exist (and ignoreMissing is false).
333+ */
334+ public void removeField (String path , boolean ignoreMissing ) {
323335 final FieldPath fieldPath = FieldPath .of (path );
324336 Object context = fieldPath .initialContext (this );
325337 ResolveResult result = resolve (fieldPath .pathElements , fieldPath .pathElements .length - 1 , path , context );
326338 if (result .wasSuccessful ) {
327339 context = result .resolvedObject ;
340+ } else if (ignoreMissing ) {
341+ return ; // nothing was found, so there's nothing to remove :shrug:
328342 } else {
329343 throw new IllegalArgumentException (result .errorMessage );
330344 }
@@ -335,13 +349,13 @@ public void removeField(String path) {
335349 } else if (context instanceof IngestCtxMap map ) { // optimization: handle IngestCtxMap separately from Map
336350 if (map .containsKey (leafKey )) {
337351 map .remove (leafKey );
338- } else {
352+ } else if ( ignoreMissing == false ) {
339353 throw new IllegalArgumentException (Errors .notPresent (path , leafKey ));
340354 }
341355 } else if (context instanceof Map <?, ?> map ) {
342356 if (map .containsKey (leafKey )) {
343357 map .remove (leafKey );
344- } else {
358+ } else if ( ignoreMissing == false ) {
345359 throw new IllegalArgumentException (Errors .notPresent (path , leafKey ));
346360 }
347361 } else if (context instanceof List <?> list ) {
@@ -352,11 +366,13 @@ public void removeField(String path) {
352366 throw new IllegalArgumentException (Errors .notInteger (path , leafKey ), e );
353367 }
354368 if (index < 0 || index >= list .size ()) {
355- throw new IllegalArgumentException (Errors .outOfBounds (path , index , list .size ()));
369+ if (ignoreMissing == false ) {
370+ throw new IllegalArgumentException (Errors .outOfBounds (path , index , list .size ()));
371+ }
356372 } else {
357373 list .remove (index );
358374 }
359- } else {
375+ } else if ( ignoreMissing == false ) {
360376 throw new IllegalArgumentException (Errors .cannotRemove (path , leafKey , context ));
361377 }
362378 }
0 commit comments