You are viewing a plain text version of this content. The canonical link for it is here.
Posted to oak-commits@jackrabbit.apache.org by nf...@apache.org on 2024/09/16 14:52:28 UTC

(jackrabbit-oak) branch trunk updated: OAK-11114 - Filter downloaded Mongo documents by path suffix (#1716)

This is an automated email from the ASF dual-hosted git repository.

nfsantos pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/jackrabbit-oak.git


The following commit(s) were added to refs/heads/trunk by this push:
     new 917c1e45dd OAK-11114 - Filter downloaded Mongo documents by path suffix (#1716)
917c1e45dd is described below

commit 917c1e45dd12fa687f53f75aae9522bff93fa276
Author: Nuno Santos <ns...@adobe.com>
AuthorDate: Mon Sep 16 16:52:22 2024 +0200

    OAK-11114 - Filter downloaded Mongo documents by path suffix (#1716)
---
 .../document/flatfile/pipelined/ConfigHelper.java  |  19 ++++
 .../flatfile/pipelined/NodeDocumentCodec.java      |  98 ++++++++++++++---
 .../flatfile/pipelined/NodeDocumentFilter.java     | 120 +++++++++++++++++++++
 .../pipelined/PipelinedMongoDownloadTask.java      |   6 +-
 .../flatfile/pipelined/ConfigHelperTest.java       |  57 ++++++++++
 .../flatfile/pipelined/NodeDocumentFilterTest.java |  90 ++++++++++++++++
 .../document/flatfile/pipelined/PipelinedIT.java   |  48 +++++++++
 7 files changed, 425 insertions(+), 13 deletions(-)

diff --git a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelper.java b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelper.java
index bc9121709b..b16171b0e2 100644
--- a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelper.java
+++ b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelper.java
@@ -18,9 +18,14 @@
  */
 package org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
 
+import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.Arrays;
+import java.util.List;
+import java.util.stream.Collectors;
+
 public class ConfigHelper {
     private static final Logger LOG = LoggerFactory.getLogger(ConfigHelper.class);
 
@@ -48,4 +53,18 @@ public class ConfigHelper {
         LOG.info("Config {}={}", name, value);
         return value;
     }
+
+    /**
+     * white space at the start/end of the string or at the start/end of the parts delimited by separator are trimmed
+     */
+    public static List<String> getSystemPropertyAsStringList(String name, String defaultValue, char separator) {
+        String result = System.getProperty(name, defaultValue);
+        List<String> parts = splitString(result, separator);
+        LOG.info("Config {}={}", name, parts);
+        return parts;
+    }
+
+    private static List<String> splitString(String str, char separator) {
+        return str.isBlank() ? List.of() : Arrays.stream(StringUtils.split(str, separator)).map(String::trim).collect(Collectors.toList());
+    }
 }
diff --git a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentCodec.java b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentCodec.java
index 81c0796bd7..6e79863b37 100644
--- a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentCodec.java
+++ b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentCodec.java
@@ -18,7 +18,8 @@
  */
 package org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
 
-import org.apache.commons.lang3.mutable.MutableInt;
+import org.apache.commons.lang3.mutable.MutableLong;
+import org.apache.jackrabbit.oak.commons.IOUtils;
 import org.apache.jackrabbit.oak.plugins.document.Collection;
 import org.apache.jackrabbit.oak.plugins.document.Document;
 import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
@@ -35,9 +36,15 @@ import org.bson.codecs.Codec;
 import org.bson.codecs.DecoderContext;
 import org.bson.codecs.EncoderContext;
 import org.bson.codecs.configuration.CodecRegistry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+import java.util.List;
 import java.util.SortedMap;
 import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Collectors;
 
 /**
  * Custom codec for MongoDB to transform a stream of BSON tokens into a NodeDocument. This custom codec provides two
@@ -49,44 +56,111 @@ import java.util.TreeMap;
  *   <li>Allows estimating the size of the document while reading it, which will have a negligible overhead (as compared
  *   with doing an additional traverse of the object structure to compute the size).</li>
  * </ul>
- *
+ * <p>
  * This class must be thread-safe, Mongo uses a single coded implementation across multiple threads.
- *
  */
 public class NodeDocumentCodec implements Codec<NodeDocument> {
+    private final static Logger LOG = LoggerFactory.getLogger(NodeDocumentCodec.class);
+
+    public static final String OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_FILTERED_PATH = "oak.indexer.pipelined.nodeDocument.filter.filteredPath";
+    public static final String OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_SUFFIXES_TO_SKIP = "oak.indexer.pipelined.nodeDocument.filter.suffixesToSkip";
+    private final String filteredPath = ConfigHelper.getSystemPropertyAsString(OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_FILTERED_PATH, "");
+    private final List<String> suffixesToSkip = ConfigHelper.getSystemPropertyAsStringList(OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_SUFFIXES_TO_SKIP, "", ';');
+
     // The estimated size is stored in the NodeDocument itself
     public final static String SIZE_FIELD = "_ESTIMATED_SIZE_";
+
+    private static class NodeDocumentDecoderContext {
+        long docsDecoded = 0;
+        long dataDownloaded = 0;
+        int estimatedSizeOfCurrentObject = 0;
+    }
+
+    private final NodeDocument emptyNodeDocument;
+
     private final MongoDocumentStore store;
     private final Collection<NodeDocument> collection;
     private final BsonTypeCodecMap bsonTypeCodecMap;
     private final DecoderContext decoderContext = DecoderContext.builder().build();
-
     private final Codec<String> stringCoded;
     private final Codec<Long> longCoded;
     private final Codec<Boolean> booleanCoded;
 
+    private final NodeDocumentFilter nodeDocumentFilter = new NodeDocumentFilter(filteredPath, suffixesToSkip);
+
+    // Statistics
+    private final AtomicLong totalDocsDecoded = new AtomicLong(0);
+    private final AtomicLong totalDataDownloaded = new AtomicLong(0);
+    private final ThreadLocal<NodeDocumentDecoderContext> perThreadContext = ThreadLocal.withInitial(NodeDocumentDecoderContext::new);
+
     public NodeDocumentCodec(MongoDocumentStore store, Collection<NodeDocument> collection, CodecRegistry defaultRegistry) {
         this.store = store;
         this.collection = collection;
         this.bsonTypeCodecMap = new BsonTypeCodecMap(new BsonTypeClassMap(), defaultRegistry);
+        this.emptyNodeDocument = collection.newDocument(store);
         // Retrieve references to the most commonly used codecs, to avoid the map lookup in the common case
         this.stringCoded = (Codec<String>) bsonTypeCodecMap.get(BsonType.STRING);
         this.longCoded = (Codec<Long>) bsonTypeCodecMap.get(BsonType.INT64);
         this.booleanCoded = (Codec<Boolean>) bsonTypeCodecMap.get(BsonType.BOOLEAN);
     }
 
+    /**
+     * Skipping over values in the BSON file is faster than reading them. Skipping is done by advancing a pointer in
+     * an internal buffer, while reading requires converting them to a Java data type (typically String).
+     */
+    private void skipUntilEndOfDocument(BsonReader reader) {
+        while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
+            reader.skipName();
+            reader.skipValue();
+        }
+        reader.readEndDocument();
+    }
+
     @Override
     public NodeDocument decode(BsonReader reader, DecoderContext decoderContext) {
         NodeDocument nodeDocument = collection.newDocument(store);
-        MutableInt estimatedSizeOfCurrentObject = new MutableInt(0);
+        NodeDocumentDecoderContext threadLocalContext = perThreadContext.get();
+        threadLocalContext.estimatedSizeOfCurrentObject = 0;
         reader.readStartDocument();
         while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
             String fieldName = reader.readName();
-            Object value = readValue(reader, fieldName, estimatedSizeOfCurrentObject);
+            Object value = readValue(reader, fieldName, threadLocalContext);
+            // Once we read the _id or the _path, apply the filter
+            if (!nodeDocumentFilter.isFilteringDisabled()
+                    && (fieldName.equals(NodeDocument.ID) || fieldName.equals(NodeDocument.PATH))
+                    && (value instanceof String)) {
+                // value should always be non-null and of type String, but we do not want the filter to ever break the
+                // downlaoder as filtering is best-effort and just a performance optimization. So we check anyway that
+                // value is what we expect it to be, and if not, just skip trying to filter.
+                if (nodeDocumentFilter.shouldSkip(fieldName, (String) value)) {
+                    skipUntilEndOfDocument(reader);
+                    // The Mongo driver requires us to return a document. To indicate that the document should be skipped,
+                    // we return an empty document. The logic reading from the Mongo cursor can then check if the _id of
+                    // the document is null, which indicates that the document should be skipped.
+                    return emptyNodeDocument;
+                }
+            }
             nodeDocument.put(fieldName, value);
         }
         reader.readEndDocument();
-        nodeDocument.put(SIZE_FIELD, estimatedSizeOfCurrentObject.toInteger());
+        threadLocalContext.docsDecoded++;
+        threadLocalContext.dataDownloaded += threadLocalContext.estimatedSizeOfCurrentObject;
+        long docsDecodedLocal = totalDocsDecoded.incrementAndGet();
+        long dataDownloadedLocal = totalDataDownloaded.addAndGet(threadLocalContext.estimatedSizeOfCurrentObject);
+        if (docsDecodedLocal % 500_000 == 0) {
+            ConcurrentHashMap<String, MutableLong> filteredSuffixes = nodeDocumentFilter.getFilteredSuffixesCounts();
+            long totalDocumentsFiltered = filteredSuffixes.values().stream().mapToLong(MutableLong::longValue).sum();
+            String filteredRenditionsString = filteredSuffixes.entrySet().stream()
+                    .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
+                    .limit(10)
+                    .map(e -> e.getKey() + "=" + e.getValue())
+                    .collect(Collectors.joining(", ", "{", "}"));
+            LOG.info("docsDecodedByThread: {}, dataDownloadedByThread: {}, docsDecodedTotal: {}, dataDownloadedTotal: {}, docsSkippedTotal {}, filteredRenditionsTotal (top 10): {}",
+                    threadLocalContext.docsDecoded, IOUtils.humanReadableByteCountBin(threadLocalContext.dataDownloaded),
+                    totalDocsDecoded, IOUtils.humanReadableByteCountBin(dataDownloadedLocal),
+                    totalDocumentsFiltered, filteredRenditionsString);
+        }
+        nodeDocument.put(SIZE_FIELD, threadLocalContext.estimatedSizeOfCurrentObject);
         return nodeDocument;
     }
 
@@ -100,7 +174,7 @@ public class NodeDocumentCodec implements Codec<NodeDocument> {
         return NodeDocument.class;
     }
 
-    private Object readValue(BsonReader reader, String fieldName, MutableInt estimatedSizeOfCurrentObject) {
+    private Object readValue(BsonReader reader, String fieldName, NodeDocumentDecoderContext threadContext) {
         BsonType bsonType = reader.getCurrentBsonType();
         Object value;
         int valSize;
@@ -115,7 +189,7 @@ public class NodeDocumentCodec implements Codec<NodeDocument> {
                 valSize = 16;
                 break;
             case DOCUMENT:
-                value = readDocument(reader, estimatedSizeOfCurrentObject);
+                value = readDocument(reader, threadContext);
                 valSize = 0; // the size is updated by the recursive calls inside readDocument
                 break;
             case BOOLEAN:
@@ -141,16 +215,16 @@ public class NodeDocumentCodec implements Codec<NodeDocument> {
                 }
                 break;
         }
-        estimatedSizeOfCurrentObject.add(16 + fieldName.length() + valSize);
+        threadContext.estimatedSizeOfCurrentObject += 16 + fieldName.length() + valSize;
         return value;
     }
 
-    private SortedMap<Revision, Object> readDocument(BsonReader reader, MutableInt estimatedSizeOfCurrentObject) {
+    private SortedMap<Revision, Object> readDocument(BsonReader reader, NodeDocumentDecoderContext threadContext) {
         TreeMap<Revision, Object> map = new TreeMap<>(StableRevisionComparator.REVERSE);
         reader.readStartDocument();
         while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
             String fieldName = reader.readName();
-            Object value = readValue(reader, fieldName, estimatedSizeOfCurrentObject);
+            Object value = readValue(reader, fieldName, threadContext);
             map.put(Revision.fromString(fieldName), value);
         }
         reader.readEndDocument();
diff --git a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentFilter.java b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentFilter.java
new file mode 100644
index 0000000000..b599d0e022
--- /dev/null
+++ b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentFilter.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.commons.lang3.mutable.MutableLong;
+import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * Implements a filter to decide if a given Mongo document should be processed or ignored based on its path. The filter has
+ * two configuration parameters:
+ *
+ * <ul>
+ * <li> filteredPath - The path where the filter is applied. Only the documents inside this path will be considered for filtering.
+ *   Documents in other paths will all be accepted.
+ * <li> suffixesToSkip - A list of suffixes to filter. That is, any document whose path ends in one of these suffixes will
+ *   be filtered.
+ * </ul>
+ * <p>
+ * The intent of this filter is to be applied as close as possible to the download/decoding of the documents from Mongo,
+ * in order to filter unnecessary documents early and avoid spending resources processing them.
+ */
+public class NodeDocumentFilter {
+    private static final Logger LOG = LoggerFactory.getLogger(NodeDocumentFilter.class);
+
+    private final String filteredPath;
+    private final List<String> suffixesToSkip;
+
+    private final boolean filteringDisabled;
+
+    // Statistics
+    private final AtomicLong skippedFields = new AtomicLong(0);
+    private final AtomicLong longPathSkipped = new AtomicLong(0);
+    private final ConcurrentHashMap<String, MutableLong> filteredSuffixesCounts = new ConcurrentHashMap<>();
+
+    public NodeDocumentFilter(String filteredPath, List<String> suffixesToSkip) {
+        this.filteredPath = filteredPath;
+        this.suffixesToSkip = suffixesToSkip;
+        this.filteringDisabled = filteredPath.isBlank() || suffixesToSkip.isEmpty();
+        if (filteringDisabled) {
+            LOG.info("Node document filtering disabled.");
+        }
+    }
+
+    /**
+     * @param fieldName     Name of the Mongo document field. Expected to be either  _id or _path
+     * @param idOrPathValue The value of the field
+     * @return true if the document should be skipped, false otherwise
+     */
+    public boolean shouldSkip(String fieldName, String idOrPathValue) {
+        if (filteringDisabled) {
+            return false;
+        }
+        // Check if the NodeDocument should be considered for filtering, that is, if it starts with includePath.
+        // If the value is for an _id, then we must find the start of the path section, that is, the position of the first
+        // slash (3:/foo/bar/baz). If the value given is for a path, then it already contains only the path. In any case,
+        // we look up for the first occurrence of /
+        int idxOfFirstForwardSlash = idOrPathValue.indexOf('/');
+        if (idxOfFirstForwardSlash < 0) {
+            LOG.warn("Invalid field. {} = {}", fieldName, idOrPathValue);
+            return false;
+        }
+        if (idOrPathValue.startsWith(filteredPath, idxOfFirstForwardSlash)) {
+            // Match the include path. Check if it ends with any of the suffixes to skip.
+            for (String suffix : suffixesToSkip) {
+                if (idOrPathValue.endsWith(suffix)) {
+                    // This node document should be skipped.
+                    filteredSuffixesCounts.computeIfAbsent(suffix, k -> new MutableLong(0)).increment();
+                    long skippedSoFar = skippedFields.incrementAndGet();
+                    if (fieldName.equals(NodeDocument.PATH)) {
+                        longPathSkipped.incrementAndGet();
+                    }
+                    if (skippedSoFar % 50_000 == 0) {
+                        LOG.info("skippedSoFar: {}. Long path: {}, Doc: {}={}", skippedSoFar, longPathSkipped.get(), fieldName, idOrPathValue);
+                    }
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+
+    public boolean isFilteringDisabled() {
+        return filteringDisabled;
+    }
+
+    public long getSkippedFields() {
+        return skippedFields.get();
+    }
+
+    public long getLongPathSkipped() {
+        return longPathSkipped.get();
+    }
+
+    public ConcurrentHashMap<String, MutableLong> getFilteredSuffixesCounts() {
+        return filteredSuffixesCounts;
+    }
+}
diff --git a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java
index 07940e15f0..1fc40a62bd 100644
--- a/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java
+++ b/oak-run-commons/src/main/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedMongoDownloadTask.java
@@ -786,7 +786,11 @@ public class PipelinedMongoDownloadTask implements Callable<PipelinedMongoDownlo
                 try {
                     while (cursor.hasNext()) {
                         NodeDocument next = cursor.next();
+                        // If the id is not set, then the document was filtered by NodeDocumentFilter and should be ignored
                         String id = next.getId();
+                        if (id == null) {
+                            continue;
+                        }
                         // All the Mongo queries in this class have a requirement on the _modified field, so the
                         // documents downloaded will all have the field defined.
                         this.nextLastModified = next.getModified();
@@ -796,7 +800,7 @@ public class PipelinedMongoDownloadTask implements Callable<PipelinedMongoDownlo
                         this.lastIdDownloaded = id;
                         this.documentsDownloadedTotal++;
                         downloadStatics.incrementDocumentsDownloadedTotal();
-                        if (this.documentsDownloadedTotal % 20_000 == 0) {
+                        if (this.documentsDownloadedTotal % 50_000 == 0) {
                             reportProgress(id);
                         }
                         TRAVERSAL_LOG.trace(id);
diff --git a/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelperTest.java b/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelperTest.java
new file mode 100644
index 0000000000..5e8ba1effe
--- /dev/null
+++ b/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/ConfigHelperTest.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.RestoreSystemProperties;
+
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+
+public class ConfigHelperTest {
+
+    @Rule
+    public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
+
+    @Test
+    public void getSystemPropertyAsStringList() {
+        assertEquals(List.of(), ConfigHelper.getSystemPropertyAsStringList("not.defined", "", ';'));
+        assertEquals(List.of("default"), ConfigHelper.getSystemPropertyAsStringList("not.defined", "default", ';'));
+        assertEquals(List.of("default1", "default2"), ConfigHelper.getSystemPropertyAsStringList("not.defined", "default1;default2", ';'));
+
+        test(List.of("value1"), "value1", "default", ';');
+        test(List.of(), " ", "default", ';');
+        test(List.of("v1", "v2"), "v1;v2", "default", ';');
+        test(List.of("v1", "v2"), "v1; v2", "default", ';');
+        test(List.of("v1", "v2"), "v1,v2", "default", ',');
+        test(List.of("v1,v2"), "v1,v2", "default", ';');
+    }
+
+    private void test(List<String> expected, String sysPropertyValue, String defaultValue, char separator) {
+        String key = "$$ConfigHelperTest_KEY$$";
+        System.setProperty(key, sysPropertyValue);
+        try {
+            assertEquals(expected, ConfigHelper.getSystemPropertyAsStringList(key, defaultValue, separator));
+        } finally {
+            System.clearProperty(key);
+        }
+    }
+}
\ No newline at end of file
diff --git a/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentFilterTest.java b/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentFilterTest.java
new file mode 100644
index 0000000000..bf9ac71104
--- /dev/null
+++ b/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/NodeDocumentFilterTest.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+package org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined;
+
+import org.apache.jackrabbit.oak.plugins.document.NodeDocument;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.contrib.java.lang.system.RestoreSystemProperties;
+
+import java.util.List;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+public class NodeDocumentFilterTest {
+
+    @Rule
+    public final RestoreSystemProperties restoreSystemProperties = new RestoreSystemProperties();
+
+    @Test
+    public void filterInDirectory() {
+        NodeDocumentFilter nodeDocumentFilter = new NodeDocumentFilter("/foo/bar", List.of("/skip/me", "/dont/include/me", "/not_this_one"));
+
+        // nodes are in the include paths for filtering
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "5:/foo/bar/a/b/not_this_one"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/bar/a/b/not_this_one"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "6:/foo/bar/a/b/skip/me"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/bar/a/b/skip/me"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "7:/foo/bar/a/b/dont/include/me"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/bar/a/b/dont/include/me"));
+
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "4:/foo/bar/a/b"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/bar/a/b"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "6:/foo/bar/a/b/not_this_one/child"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/bar/a/b/not_this_one/child"));
+
+
+        // nodes are not in the include paths for filtering
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "4:/foo/a/b/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/a/b/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "5:/foo/a/b/skip/me"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/a/b/skip/me"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "6:/foo/a/b/dont/include/me"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/foo/a/b/dont/include/me"));
+    }
+
+
+    @Test
+    public void filterIncludePathRoot() {
+        NodeDocumentFilter nodeDocumentFilter = new NodeDocumentFilter("/", List.of("/skip/me"));
+
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "1:/skip"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "1:/me"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "2:/skip/me"));
+        assertTrue(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "3:/foo/skip/me"));
+    }
+
+    @Test
+    public void filterDisabled() {
+        NodeDocumentFilter nodeDocumentFilter = new NodeDocumentFilter("", List.of("/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "3:/a/b/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/a/b/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "1:/a"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/a"));
+    }
+
+    @Test
+    public void emptySuffixList() {
+        NodeDocumentFilter nodeDocumentFilter = new NodeDocumentFilter("/", List.of());
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "3:/a/b/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.PATH, "/a/b/not_this_one"));
+        assertFalse(nodeDocumentFilter.shouldSkip(NodeDocument.ID, "/a"));
+    }
+}
\ No newline at end of file
diff --git a/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedIT.java b/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedIT.java
index c0720b8d7e..6c1d6a3d37 100644
--- a/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedIT.java
+++ b/oak-run-commons/src/test/java/org/apache/jackrabbit/oak/index/indexer/document/flatfile/pipelined/PipelinedIT.java
@@ -65,6 +65,8 @@ import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
 import static java.lang.management.ManagementFactory.getPlatformMBeanServer;
+import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined.NodeDocumentCodec.OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_FILTERED_PATH;
+import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined.NodeDocumentCodec.OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_SUFFIXES_TO_SKIP;
 import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined.PipelineITUtil.assertMetrics;
 import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined.PipelineITUtil.contentDamPathFilter;
 import static org.apache.jackrabbit.oak.index.indexer.document.flatfile.pipelined.PipelinedMongoDownloadTask.OAK_INDEXER_PIPELINED_MONGO_CUSTOM_EXCLUDED_PATHS;
@@ -351,6 +353,52 @@ public class PipelinedIT {
                 excludedPathsRegexTestExpected);
     }
 
+
+    @Test
+    public void createFFSFilterMongoDocuments() throws Exception {
+        System.setProperty(OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_FILTERED_PATH, "/content/dam/2022");
+        System.setProperty(OAK_INDEXER_PIPELINED_NODE_DOCUMENT_FILTER_SUFFIXES_TO_SKIP, "/01;/03;/02/28");
+        System.setProperty(OAK_INDEXER_PIPELINED_MONGO_REGEX_PATH_FILTERING, "true");
+
+        Predicate<String> pathPredicate = s -> true;
+        PathFilter pathFilter = new PathFilter(List.of("/content/dam/2022", "/content/dam/2023"), List.of());
+        List<PathFilter> pathFilters = List.of(pathFilter);
+
+        // The full list of nodes under /content/dam/2022 and /content/dam/2023 is:
+        //  /content
+        //  /content/dam
+        //  /content/dam/2022
+        //  /content/dam/2022/01
+        //  /content/dam/2022/01/01
+        //  /content/dam/2022/02
+        //  /content/dam/2022/02/01
+        //  /content/dam/2022/02/02
+        //  /content/dam/2022/02/03
+        //  /content/dam/2022/02/04
+        //  /content/dam/2022/03
+        //  /content/dam/2022/04
+        //  /content/dam/2023
+        //  /content/dam/2023/01
+        //  /content/dam/2023/02
+        //  /content/dam/2023/02/28
+        // We are filtering nodes ending in /01 and /03 inside /content/dam/2022.
+        // Nodes in /content/dam/2023 should not be filtered, even if they match the suffixes
+        testSuccessfulDownload(pathPredicate, pathFilters, List.of(
+                "/|{}",
+                "/content|{}",
+                "/content/dam|{}",
+                "/content/dam/2022|{}",
+                "/content/dam/2022/02|{\"p1\":\"v202202\"}",
+                "/content/dam/2022/02/02|{\"p1\":\"v20220202\"}",
+                "/content/dam/2022/02/04|{\"p1\":\"v20220204\"}",
+                "/content/dam/2022/04|{\"p1\":\"v202204\"}",
+                "/content/dam/2023|{\"p2\":\"v2023\"}",
+                "/content/dam/2023/01|{\"p1\":\"v202301\"}",
+                "/content/dam/2023/02|{}",
+                "/content/dam/2023/02/28|{\"p1\":\"v20230228\"}"
+        ), true);
+    }
+
     private void buildNodeStoreForExcludedRegexTest(DocumentNodeStore rwNodeStore) {
         @NotNull NodeBuilder rootBuilder = rwNodeStore.getRoot().builder();
         @NotNull NodeBuilder contentDamBuilder = rootBuilder.child("content").child("dam");