From bd23fde5c1292f125c3e2d18157c12aaff6740f5 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 16 Nov 2026 22:11:29 +1300 Subject: [PATCH 01/15] Add FilteredDataset in C++ and use for unions of filtered datasets Dataset.filter() stores a filter on the Python Dataset wrapper, but a UnionDataset is represented in C++, so filtered Datasets could not be unioned. This adds a new FilteredDataset class that holds a filter in the C++ layer, and converts any datasets with filters to a FilteredDataset when they are used to create a UnionDataset. --- cpp/src/arrow/dataset/dataset.cc | 122 ++++++++++++++++++ cpp/src/arrow/dataset/dataset.h | 61 +++++++++ cpp/src/arrow/dataset/dataset_test.cc | 126 +++++++++++++++++++ docs/source/python/api/dataset.rst | 1 + python/pyarrow/_dataset.pyx | 57 +++++++++ python/pyarrow/dataset.py | 14 +-- python/pyarrow/includes/libarrow_dataset.pxd | 9 ++ python/pyarrow/tests/test_dataset.py | 92 +++++++++++++- 8 files changed, 470 insertions(+), 12 deletions(-) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index 2925cbf0003d..0b81088a8bd1 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -19,6 +19,7 @@ #include #include "arrow/acero/util.h" +#include "arrow/compute/api_vector.h" #include "arrow/dataset/dataset.h" #include "arrow/dataset/dataset_internal.h" #include "arrow/dataset/projector.h" @@ -321,6 +322,127 @@ Result UnionDataset::GetFragmentsImpl(compute::Expression pred return GetFragmentsFromDatasets(children_, predicate); } +FilteredFragment::FilteredFragment(std::shared_ptr fragment, + compute::Expression filter) + : Fragment(fragment->partition_expression(), /*physical_schema=*/nullptr), + fragment_(std::move(fragment)), + filter_(std::move(filter)) {} + +Result> FilteredFragment::ReadPhysicalSchemaImpl() { + return fragment_->ReadPhysicalSchema(); +} + +Status FilteredFragment::ClearCachedMetadata() { + RETURN_NOT_OK(Fragment::ClearCachedMetadata()); + return fragment_->ClearCachedMetadata(); +} + +std::string FilteredFragment::ToString() const { + return "filtered(" + fragment_->ToString() + ", " + filter_.ToString() + ")"; +} + +Result FilteredFragment::ScanBatchesAsync( + const std::shared_ptr& options) { + const auto& dataset_schema = options->dataset_schema; + ARROW_ASSIGN_OR_RAISE(auto filter, filter_.Bind(*dataset_schema)); + ARROW_ASSIGN_OR_RAISE(filter, + SimplifyWithGuarantee(std::move(filter), partition_expression_)); + if (!filter.IsSatisfiable()) { + return MakeEmptyGenerator>(); + } + + // Combine any existing filter in the scan options with the fragment's filter, + // so the wrapped fragment can skip data that cannot match. + auto fragment_options = std::make_shared(*options); + ARROW_ASSIGN_OR_RAISE(fragment_options->filter, + compute::and_(options->filter, filter).Bind(*dataset_schema)); + ARROW_ASSIGN_OR_RAISE(auto batches, fragment_->ScanBatchesAsync(fragment_options)); + + // The filter might simplify to true if it only references partition fields, + // in which case we can skip filtering batches. + if (filter == compute::literal(true)) { + return batches; + } + + // Apply the fragment's filter to scanned rows. + // The filter in the scan options is only used for data pruning at this point + // and will be used to filter rows later, so don't duplicate that work. + auto guarantee = partition_expression_; + auto pool = options->pool; + return MakeMappedGenerator( + std::move(batches), + [filter, dataset_schema, guarantee, pool](const std::shared_ptr& batch) + -> Result> { + compute::ExecContext exec_context(pool); + ARROW_ASSIGN_OR_RAISE(auto exec_batch, + compute::MakeExecBatch(*dataset_schema, batch, guarantee)); + ARROW_ASSIGN_OR_RAISE(Datum mask, compute::ExecuteScalarExpression( + filter, exec_batch, &exec_context)); + if (mask.is_scalar()) { + const auto& selected = mask.scalar_as(); + return selected.is_valid && selected.value ? batch : batch->Slice(0, 0); + } + ARROW_ASSIGN_OR_RAISE( + Datum filtered, + compute::Filter(batch, mask, compute::FilterOptions::Defaults(), + &exec_context)); + return filtered.record_batch(); + }); +} + +Future> FilteredFragment::CountRows( + compute::Expression predicate, const std::shared_ptr& options) { + ARROW_ASSIGN_OR_RAISE( + auto combined, + compute::and_(std::move(predicate), filter_).Bind(*options->dataset_schema)); + return fragment_->CountRows(std::move(combined), options); +} + +FilteredDataset::FilteredDataset(std::shared_ptr child, + compute::Expression filter) + : Dataset(child->schema(), child->partition_expression()), + child_(std::move(child)), + filter_(std::move(filter)) {} + +Result> FilteredDataset::Make( + std::shared_ptr child, compute::Expression filter) { + // Verify the filter produces a bool + ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*child->schema())); + if (!bound.type()->Equals(*boolean())) { + return Status::TypeError("FilteredDataset filter must be boolean, got ", + *bound.type()); + } + // Store the unbound filter so it can be bound on-demand on the unified schema of a + // UnionDataset. + return std::shared_ptr( + new FilteredDataset(std::move(child), std::move(filter))); +} + +Result> FilteredDataset::ReplaceSchema( + std::shared_ptr schema) const { + ARROW_ASSIGN_OR_RAISE(auto child, child_->ReplaceSchema(std::move(schema))); + ARROW_ASSIGN_OR_RAISE(auto filtered, Make(std::move(child), filter_)); + return std::static_pointer_cast(std::move(filtered)); +} + +Result FilteredDataset::GetFragmentsImpl( + compute::Expression predicate) { + // Compute a combined predicate that can be used for predicate-pushdown to select + // fragments from the child Dataset. + ARROW_ASSIGN_OR_RAISE(auto combined_predicate, + compute::and_(std::move(predicate), filter_).Bind(*schema_)); + ARROW_ASSIGN_OR_RAISE(auto fragments, + child_->GetFragments(std::move(combined_predicate))); + + // Convert the child's fragments to FilteredFragments that apply the additional filter. + auto filter = filter_; + return MakeMapIterator( + [filter](std::shared_ptr fragment) -> std::shared_ptr { + return std::make_shared(std::move(fragment), filter); + }, + std::move(fragments)); +} + namespace { struct MissingColumn { diff --git a/cpp/src/arrow/dataset/dataset.h b/cpp/src/arrow/dataset/dataset.h index 5c788ef5581c..70ab582fc78a 100644 --- a/cpp/src/arrow/dataset/dataset.h +++ b/cpp/src/arrow/dataset/dataset.h @@ -485,6 +485,67 @@ class ARROW_DS_EXPORT UnionDataset : public Dataset { friend class UnionDatasetFactory; }; +/// \brief A Fragment which wraps another Fragment and applies a filter. +class ARROW_DS_EXPORT FilteredFragment : public Fragment { + public: + FilteredFragment(std::shared_ptr fragment, compute::Expression filter); + + Result ScanBatchesAsync( + const std::shared_ptr& options) override; + + Future> CountRows( + compute::Expression predicate, + const std::shared_ptr& options) override; + + Status ClearCachedMetadata() override; + + std::string type_name() const override { return "filtered"; } + + std::string ToString() const override; + + const std::shared_ptr& fragment() const { return fragment_; } + + const compute::Expression& filter() const { return filter_; } + + protected: + Result> ReadPhysicalSchemaImpl() override; + + std::shared_ptr fragment_; + compute::Expression filter_; +}; + +/// \brief A Dataset which wraps another Dataset and applies a filter. +/// +/// Unlike a filter in ScanOptions, the filter is part of the Dataset itself, so it +/// is preserved when the Dataset is combined with others, e.g. as a child of a +/// UnionDataset whose other children have different filters. +class ARROW_DS_EXPORT FilteredDataset : public Dataset { + public: + /// \brief Construct a FilteredDataset. + /// + /// \param[in] child the Dataset to filter. + /// \param[in] filter a boolean expression used to filter rows of the child Dataset. + static Result> Make(std::shared_ptr child, + compute::Expression filter); + + const std::shared_ptr& child() const { return child_; } + + const compute::Expression& filter() const { return filter_; } + + std::string type_name() const override { return "filtered"; } + + Result> ReplaceSchema( + std::shared_ptr schema) const override; + + protected: + Result GetFragmentsImpl(compute::Expression predicate) override; + + FilteredDataset(std::shared_ptr child, compute::Expression filter); + + std::shared_ptr child_; + compute::Expression filter_; +}; + /// @} } // namespace dataset diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index cd23429bf5ef..613785332bfe 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -277,6 +277,132 @@ TEST_F(TestUnionDataset, TrivialScan) { AssertDatasetEquals(reader.get(), dataset.get()); } +class TestFilteredDataset : public DatasetFixtureMixin {}; + +TEST_F(TestFilteredDataset, UnionOfDifferentFilters) { + SetSchema({field("i", int32())}); + // Include a null value to test handling when the filter evaluates to null. + auto batch = RecordBatchFromJSON(schema_, R"([[1], [2], [3], [null], [4]])"); + auto child = std::make_shared(schema_, RecordBatchVector{batch}); + + ASSERT_OK_AND_ASSIGN(auto small, + FilteredDataset::Make(child, compute::less(compute::field_ref("i"), + compute::literal(2)))); + ASSERT_OK_AND_ASSIGN( + auto large, FilteredDataset::Make(child, compute::greater(compute::field_ref("i"), + compute::literal(3)))); + ASSERT_OK_AND_ASSIGN(auto dataset, UnionDataset::Make(schema_, {small, large})); + + ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(schema_, {R"([[1], [4]])"}), *table, + /*same_chunk_layout=*/false); + ASSERT_OK_AND_EQ(2, scanner->CountRows()); + + // A filter on the union applies on top of each child's filter. + ASSERT_OK_AND_ASSIGN(builder, dataset->NewScan()); + ASSERT_OK( + builder->Filter(compute::not_equal(compute::field_ref("i"), compute::literal(1)))); + ASSERT_OK_AND_ASSIGN(scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(schema_, {R"([[4]])"}), *table, + /*same_chunk_layout=*/false); + ASSERT_OK_AND_EQ(1, scanner->CountRows()); +} + +TEST_F(TestFilteredDataset, ReplaceSchema) { + SetSchema({field("i", int32())}); + auto batch = RecordBatchFromJSON(schema_, R"([[1], [2]])"); + auto child = std::make_shared(schema_, RecordBatchVector{batch}); + ASSERT_OK_AND_ASSIGN( + auto filtered, FilteredDataset::Make(child, compute::equal(compute::field_ref("i"), + compute::literal(2)))); + + auto wider = schema({field("i", int32()), field("j", utf8())}); + ASSERT_OK_AND_ASSIGN(auto replaced, filtered->ReplaceSchema(wider)); + ASSERT_EQ("filtered", replaced->type_name()); + ASSERT_OK_AND_ASSIGN(auto builder, replaced->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(wider, {R"([[2, null]])"}), *table, + /*same_chunk_layout=*/false); + + // Check we get an error if attempting to replace the schema with one + // that the filter won't bind against. + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, testing::HasSubstr("No match for FieldRef"), + filtered->ReplaceSchema(schema({field("j", utf8())}))); +} + +TEST_F(TestFilteredDataset, FilterOnPartitionField) { + SetSchema({field("part", int32()), field("i", int32())}); + auto make_fragment = [this](int32_t part, const std::string& json) { + return std::make_shared( + schema_, RecordBatchVector{RecordBatchFromJSON(schema_, json)}, + compute::equal(compute::field_ref("part"), compute::literal(part))); + }; + auto child = std::make_shared( + schema_, FragmentVector{make_fragment(1, R"([[1, 10], [1, 11]])"), + make_fragment(2, R"([[2, 20], [2, 21]])"), + make_fragment(3, R"([[3, 30], [3, 31]])")}); + + // This filter is fully guaranteed by the matching fragment's partition expression, + // so it simplifies to true and no per-batch filtering is needed. + ASSERT_OK_AND_ASSIGN( + auto first, FilteredDataset::Make(child, compute::equal(compute::field_ref("part"), + compute::literal(1)))); + // This filter only partially simplifies, leaving i > 20 to apply to each batch. + ASSERT_OK_AND_ASSIGN( + auto second, + FilteredDataset::Make( + child, compute::and_( + compute::equal(compute::field_ref("part"), compute::literal(2)), + compute::greater(compute::field_ref("i"), compute::literal(20))))); + + // Fragments whose partition expression contradicts the filter are pruned. + ASSERT_OK_AND_ASSIGN(auto fragment_it, first->GetFragments()); + ASSERT_OK_AND_ASSIGN(auto fragments, fragment_it.ToVector()); + ASSERT_EQ(1, fragments.size()); + + ASSERT_OK_AND_ASSIGN(auto dataset, UnionDataset::Make(schema_, {first, second})); + ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(schema_, {R"([[1, 10], [1, 11], [2, 21]])"}), *table, + /*same_chunk_layout=*/false); + ASSERT_OK_AND_EQ(3, scanner->CountRows()); +} + +TEST_F(TestFilteredDataset, ScalarFilterResult) { + // The batches lack column j, so it is filled with a null scalar when filtering and + // filters that only reference j produce a scalar mask. + SetSchema({field("i", int32()), field("j", utf8())}); + auto batch = RecordBatchFromJSON(schema({field("i", int32())}), R"([[1], [2]])"); + auto child = std::make_shared(schema_, RecordBatchVector{batch}); + + // A true mask keeps every row. + ASSERT_OK_AND_ASSIGN( + auto keep_all, + FilteredDataset::Make(child, compute::is_null(compute::field_ref("j")))); + // A null mask drops every row. + ASSERT_OK_AND_ASSIGN(auto drop_null, FilteredDataset::Make( + child, compute::equal(compute::field_ref("j"), + compute::literal("x")))); + // A false mask drops every row. + ASSERT_OK_AND_ASSIGN( + auto drop_false, + FilteredDataset::Make(child, compute::is_valid(compute::field_ref("j")))); + + ASSERT_OK_AND_ASSIGN(auto dataset, + UnionDataset::Make(schema_, {keep_all, drop_null, drop_false})); + ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(schema_, {R"([[1, null], [2, null]])"}), *table, + /*same_chunk_layout=*/false); + ASSERT_OK_AND_EQ(2, scanner->CountRows()); +} + TEST(TestProjector, CheckProjectable) { struct Assert { explicit Assert(FieldVector from) : from_(from) {} diff --git a/docs/source/python/api/dataset.rst b/docs/source/python/api/dataset.rst index 4867c7bd7164..2b63c410f694 100644 --- a/docs/source/python/api/dataset.rst +++ b/docs/source/python/api/dataset.rst @@ -61,6 +61,7 @@ Classes FileSystemFactoryOptions FileSystemDatasetFactory UnionDataset + FilteredDataset Fragment FragmentScanOptions TaggedRecordBatch diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx index 4820027ee821..212023696d66 100644 --- a/python/pyarrow/_dataset.pyx +++ b/python/pyarrow/_dataset.pyx @@ -182,6 +182,7 @@ cdef class Dataset(_Weakrefable): classes = { 'union': UnionDataset, + 'filtered': FilteredDataset, 'filesystem': FileSystemDataset, 'in-memory': InMemoryDataset, } @@ -844,6 +845,17 @@ cdef class Dataset(_Weakrefable): filtered_dataset._scan_options = dict(filter=new_filter) return filtered_dataset + def _with_filter_attached(self): + """ + Return a Dataset which carries this Dataset's filter, if any, in its + C++ representation, so that it survives being combined with other + Datasets (e.g. in a UnionDataset). + """ + current_filter = self._scan_options.get("filter") + if current_filter is None: + return self + return FilteredDataset(Dataset.wrap(self.wrapped), current_filter) + def sort_by(self, sorting, **kwargs): """ Sort the Dataset by one or multiple columns. @@ -1097,6 +1109,51 @@ cdef class UnionDataset(Dataset): return [Dataset.wrap(children[i]) for i in range(children.size())] +cdef class FilteredDataset(Dataset): + """ + A Dataset viewing only the rows of a child dataset that match a filter. + + Unlike :meth:`Dataset.filter`, the filter is part of the dataset itself, so + it is preserved when this dataset is unioned with datasets that have + different filters. Rows for which the filter evaluates to null are dropped. + + Parameters + ---------- + child : Dataset + The dataset to filter. Any filter already applied to it with + :meth:`Dataset.filter` is combined with ``filter``. + filter : Expression + A boolean expression referencing fields of the child's schema. + """ + + cdef: + CFilteredDataset* filtered_dataset + + def __init__(self, Dataset child not None, Expression filter not None): + current_filter = child._scan_options.get("filter") + if current_filter is not None: + filter = current_filter & filter + self.init( GetResultValue( + CFilteredDataset.Make(child.wrapped, ( filter).unwrap()))) + + cdef void init(self, const shared_ptr[CDataset]& sp): + Dataset.init(self, sp) + self.filtered_dataset = sp.get() + + def __reduce__(self): + return FilteredDataset, (self.child, self.filter) + + @property + def child(self): + """The unfiltered child Dataset.""" + return Dataset.wrap(self.filtered_dataset.child()) + + @property + def filter(self): + """The filter applied to the child Dataset.""" + return Expression.wrap(self.filtered_dataset.filter()) + + cdef class FileSystemDataset(Dataset): """ A Dataset of file fragments. diff --git a/python/pyarrow/dataset.py b/python/pyarrow/dataset.py index f696d5f03ba5..49b1c33f1fab 100644 --- a/python/pyarrow/dataset.py +++ b/python/pyarrow/dataset.py @@ -48,6 +48,7 @@ Scanner, TaggedRecordBatch, UnionDataset, + FilteredDataset, UnionDatasetFactory, WrittenFile, get_partition_keys, @@ -500,16 +501,9 @@ def _union_dataset(children, schema=None, **kwargs): # unify the children datasets' schemas schema = pa.unify_schemas([child.schema for child in children]) - for child in children: - if getattr(child, "_scan_options", None): - raise ValueError( - "Creating an UnionDataset from filtered or projected Datasets " - "is currently not supported. Union the unfiltered datasets " - "and apply the filter to the resulting union." - ) - - # create datasets with the requested schema - children = [child.replace_schema(schema) for child in children] + # create datasets with the requested schema, keeping each child's own filter + children = [child._with_filter_attached().replace_schema(schema) + for child in children] return UnionDataset(schema, children) diff --git a/python/pyarrow/includes/libarrow_dataset.pxd b/python/pyarrow/includes/libarrow_dataset.pxd index 12cf82733935..42f164ef3ce0 100644 --- a/python/pyarrow/includes/libarrow_dataset.pxd +++ b/python/pyarrow/includes/libarrow_dataset.pxd @@ -154,6 +154,15 @@ cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil: const CDatasetVector& children() const + cdef cppclass CFilteredDataset "arrow::dataset::FilteredDataset"( + CDataset): + @staticmethod + CResult[shared_ptr[CFilteredDataset]] Make(shared_ptr[CDataset] child, + CExpression filter) + + const shared_ptr[CDataset]& child() const + const CExpression& filter() const + cdef cppclass CInspectOptions "arrow::dataset::InspectOptions": int fragments CField.CMergeOptions field_merge_options diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index fd5a418aaf2d..23208bf923af 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5627,8 +5627,96 @@ def test_union_dataset_filter(tempdir, dstype): filtered_ds1 = ds1.filter(pc.field("colA") < 3) filtered_ds2 = ds2.filter(pc.field("colA") < 10) - with pytest.raises(ValueError, match="currently not supported"): - ds.dataset((filtered_ds1, filtered_ds2)) + union_of_filtered = ds.dataset((filtered_ds1, filtered_ds2)) + assert union_of_filtered.to_table() == pa.table({ + "colA": [1, 2, 9], + "col2": ["a", "b", "h"] + }) + assert union_of_filtered.count_rows() == 3 + assert union_of_filtered.filter(pc.field("col2") != "a").to_table() == pa.table({ + "colA": [2, 9], + "col2": ["b", "h"] + }) + assert all(isinstance(child, ds.FilteredDataset) + for child in union_of_filtered.children) + + # Each child keeps its own filter, even where they overlap or select nulls. + t3 = pa.table({"colA": [1, None, 9], "col2": ["x", "y", "z"]}) + union_of_filtered = ds.dataset([ + ds.dataset(t3).filter(pc.field("colA") < 3), + ds.dataset(t3).filter(pc.field("colA") > 3), + ds.dataset(t3).filter(pc.field("colA").is_null()), + ]) + assert union_of_filtered.to_table() == pa.table({ + "colA": [1, 9, None], + "col2": ["x", "z", "y"] + }) + + +@pytest.mark.parquet +def test_filtered_dataset(tempdir, pickle_module): + table = pa.table({"part": [1, 1, 2, 2], "value": [1, 2, 3, 4]}) + ds.write_dataset(table, tempdir, format="parquet", partitioning=["part"]) + dataset = ds.dataset(tempdir, format="parquet", partitioning=["part"]) + + filtered = ds.FilteredDataset(dataset, pc.field("value") > 1) + assert filtered.filter.equals(pc.field("value") > 1) + assert filtered.child.to_table().num_rows == 4 + assert filtered.to_table().sort_by("value")["value"].to_pylist() == [2, 3, 4] + assert filtered.count_rows() == 3 + + # Fragments that cannot match the filter are pruned. + on_part = ds.FilteredDataset(dataset, pc.field("part") == 2) + assert len(list(on_part.get_fragments())) == 1 + assert on_part.to_table()["value"].to_pylist() == [3, 4] + + # A lazy filter on the child is folded into the FilteredDataset's filter. + combined = ds.FilteredDataset(dataset.filter(pc.field("value") < 4), + pc.field("value") > 1) + assert combined.to_table().sort_by("value")["value"].to_pylist() == [2, 3] + + assert pickle_module.loads( + pickle_module.dumps(filtered)).to_table().num_rows == 3 + + with pytest.raises(pa.ArrowInvalid): + ds.FilteredDataset(dataset, pc.field("missing") > 1) + with pytest.raises(TypeError): + ds.FilteredDataset(dataset, pc.field("value") + 1) + + +@pytest.mark.parquet +def test_union_of_filtered_datasets_pushes_down_outer_filter(tempdir): + """ + When scanning a union of filtered datasets with a predicate, + both the outer and inner predicates must be applied. + """ + # Write a Hive partitioned dataset with data covering 1000 days, + # with 10 rows per day. + day = pa.array([i // 10 for i in range(10_000)]) + for (i, part) in enumerate(["A", "B"]): + part_dir = tempdir / f"part={part}" + part_dir.mkdir() + table = pa.table({ + "day": day, + "v": pc.cast(pc.multiply(day, i + 2), "float64"), + }) + pq.write_table(table, part_dir / "part.parquet", row_group_size=500) + base = ds.dataset(tempdir, format="parquet", partitioning="hive") + + low_days = base.filter(pc.field("day") < 300) + high_days = base.filter(pc.field("day") >= 700) + union = ds.dataset([low_days, high_days]) + outer_filter = (pc.field("day") >= 250) & (pc.field("day") < 750) + + expected = pa.concat_tables( + [low_days.to_table(), high_days.to_table()]).filter(outer_filter) + assert expected.num_rows == 2_000 + result = union.filter(outer_filter) + sorting = [ + ("part", "ascending", "at_end"), + ("day", "ascending", "at_end"), + ] + assert result.to_table().sort_by(sorting).equals(expected.sort_by(sorting)) def test_parquet_dataset_filter(tempdir): From 9bcd294d8238c8e824abafc4b331aabb728de44f Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Wed, 18 Nov 2026 17:40:58 +1300 Subject: [PATCH 02/15] Add C++ type forwards --- cpp/src/arrow/dataset/type_fwd.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cpp/src/arrow/dataset/type_fwd.h b/cpp/src/arrow/dataset/type_fwd.h index d58781e038de..c2db45b53cdd 100644 --- a/cpp/src/arrow/dataset/type_fwd.h +++ b/cpp/src/arrow/dataset/type_fwd.h @@ -67,6 +67,9 @@ enum class ExistingDataBehavior : int8_t { class InMemoryDataset; +class FilteredDataset; +class FilteredFragment; + class CsvFileFormat; class CsvFileWriter; class CsvFileWriteOptions; From 8d2b1ecae7104d8970df5fb003ce9a4ce9c41a15 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Wed, 18 Nov 2026 17:41:56 +1300 Subject: [PATCH 03/15] Fix filter method shadowing --- python/pyarrow/_dataset.pyx | 4 ++-- python/pyarrow/tests/test_dataset.py | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx index 212023696d66..7579a951af81 100644 --- a/python/pyarrow/_dataset.pyx +++ b/python/pyarrow/_dataset.pyx @@ -1141,7 +1141,7 @@ cdef class FilteredDataset(Dataset): self.filtered_dataset = sp.get() def __reduce__(self): - return FilteredDataset, (self.child, self.filter) + return FilteredDataset, (self.child, self.filter_expression) @property def child(self): @@ -1149,7 +1149,7 @@ cdef class FilteredDataset(Dataset): return Dataset.wrap(self.filtered_dataset.child()) @property - def filter(self): + def filter_expression(self): """The filter applied to the child Dataset.""" return Expression.wrap(self.filtered_dataset.filter()) diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index 23208bf923af..62899bb3c6f5 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5660,11 +5660,15 @@ def test_filtered_dataset(tempdir, pickle_module): dataset = ds.dataset(tempdir, format="parquet", partitioning=["part"]) filtered = ds.FilteredDataset(dataset, pc.field("value") > 1) - assert filtered.filter.equals(pc.field("value") > 1) + assert filtered.filter_expression.equals(pc.field("value") > 1) assert filtered.child.to_table().num_rows == 4 assert filtered.to_table().sort_by("value")["value"].to_pylist() == [2, 3, 4] assert filtered.count_rows() == 3 + # The inherited Dataset.filter method applies a further filter. + refiltered = filtered.filter(pc.field("value") < 4) + assert refiltered.to_table().sort_by("value")["value"].to_pylist() == [2, 3] + # Fragments that cannot match the filter are pruned. on_part = ds.FilteredDataset(dataset, pc.field("part") == 2) assert len(list(on_part.get_fragments())) == 1 From 3ccc9df3de97b0b67eef33ac673f500a4f799353 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Wed, 18 Nov 2026 18:15:24 +1300 Subject: [PATCH 04/15] Fix handling of the __filename field --- cpp/src/arrow/dataset/dataset.cc | 4 +++- cpp/src/arrow/dataset/dataset_test.cc | 4 ++++ python/pyarrow/tests/test_dataset.py | 4 ++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index 0b81088a8bd1..f5ab25b1150a 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -338,7 +338,9 @@ Status FilteredFragment::ClearCachedMetadata() { } std::string FilteredFragment::ToString() const { - return "filtered(" + fragment_->ToString() + ", " + filter_.ToString() + ")"; + // The scanner uses ToString() for the __filename augmented field, so this must + // match the wrapped fragment. + return fragment_->ToString(); } Result FilteredFragment::ScanBatchesAsync( diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index 613785332bfe..84ba9df42314 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -363,6 +363,10 @@ TEST_F(TestFilteredDataset, FilterOnPartitionField) { ASSERT_OK_AND_ASSIGN(auto fragment_it, first->GetFragments()); ASSERT_OK_AND_ASSIGN(auto fragments, fragment_it.ToVector()); ASSERT_EQ(1, fragments.size()); + ASSERT_EQ("filtered", fragments[0]->type_name()); + // ToString() is used for the __filename field, so must match the wrapped fragment. + ASSERT_EQ(checked_cast(*fragments[0]).fragment()->ToString(), + fragments[0]->ToString()); ASSERT_OK_AND_ASSIGN(auto dataset, UnionDataset::Make(schema_, {first, second})); ASSERT_OK_AND_ASSIGN(auto builder, dataset->NewScan()); diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index 62899bb3c6f5..e3b831df2a0b 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5665,6 +5665,10 @@ def test_filtered_dataset(tempdir, pickle_module): assert filtered.to_table().sort_by("value")["value"].to_pylist() == [2, 3, 4] assert filtered.count_rows() == 3 + # The __filename field holds the paths of the underlying files. + filenames = filtered.to_table(columns=["__filename"])["__filename"] + assert set(filenames.to_pylist()) == {f.path for f in dataset.get_fragments()} + # The inherited Dataset.filter method applies a further filter. refiltered = filtered.filter(pc.field("value") < 4) assert refiltered.to_table().sort_by("value")["value"].to_pylist() == [2, 3] From 25f6f7ca51c12206629e005053319de92b199575 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Thu, 19 Nov 2026 10:22:06 +1300 Subject: [PATCH 05/15] Handle pickling a FilteredDataset with scan options --- python/pyarrow/_dataset.pyx | 6 +++++- python/pyarrow/tests/test_dataset.py | 5 +++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx index 7579a951af81..d8f8eb27b56c 100644 --- a/python/pyarrow/_dataset.pyx +++ b/python/pyarrow/_dataset.pyx @@ -1141,7 +1141,11 @@ cdef class FilteredDataset(Dataset): self.filtered_dataset = sp.get() def __reduce__(self): - return FilteredDataset, (self.child, self.filter_expression) + return (FilteredDataset, (self.child, self.filter_expression), + self._scan_options.copy()) + + def __setstate__(self, state): + self._scan_options = state @property def child(self): diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index e3b831df2a0b..d8d4bec14cc9 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5686,6 +5686,11 @@ def test_filtered_dataset(tempdir, pickle_module): assert pickle_module.loads( pickle_module.dumps(filtered)).to_table().num_rows == 3 + # A filter applied with Dataset.filter() is kept when pickling. + restored = pickle_module.loads(pickle_module.dumps(refiltered)) + assert restored.filter_expression.equals(pc.field("value") > 1) + assert restored.to_table().sort_by("value")["value"].to_pylist() == [2, 3] + with pytest.raises(pa.ArrowInvalid): ds.FilteredDataset(dataset, pc.field("missing") > 1) with pytest.raises(TypeError): From 578b406716b7e0980d3322adcdca3bf17cc97d93 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 11:46:20 +1300 Subject: [PATCH 06/15] Attach filters when using direct UnionDataset constructor --- python/pyarrow/_dataset.pyx | 2 ++ python/pyarrow/dataset.py | 5 ++--- python/pyarrow/tests/test_dataset.py | 9 +++++++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx index d8f8eb27b56c..58be0d80961c 100644 --- a/python/pyarrow/_dataset.pyx +++ b/python/pyarrow/_dataset.pyx @@ -1090,6 +1090,8 @@ cdef class UnionDataset(Dataset): shared_ptr[CUnionDataset] union_dataset for child in children: + # Any filter applied with Dataset.filter() needs to be moved to the C++ child Dataset + child = child._with_filter_attached() c_children.push_back(child.wrapped) union_dataset = GetResultValue(CUnionDataset.Make( diff --git a/python/pyarrow/dataset.py b/python/pyarrow/dataset.py index 49b1c33f1fab..eac23921a799 100644 --- a/python/pyarrow/dataset.py +++ b/python/pyarrow/dataset.py @@ -501,9 +501,8 @@ def _union_dataset(children, schema=None, **kwargs): # unify the children datasets' schemas schema = pa.unify_schemas([child.schema for child in children]) - # create datasets with the requested schema, keeping each child's own filter - children = [child._with_filter_attached().replace_schema(schema) - for child in children] + # create datasets with the requested schema + children = [child.replace_schema(schema) for child in children] return UnionDataset(schema, children) diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index d8d4bec14cc9..f8a1af9120b3 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5652,6 +5652,15 @@ def test_union_dataset_filter(tempdir, dstype): "col2": ["x", "z", "y"] }) + # A UnionDataset constructed directly from filtered children also works: + union_of_filtered_direct = ds.UnionDataset(ds1.schema, [filtered_ds1, filtered_ds2]) + assert union_of_filtered_direct.to_table() == pa.table({ + "colA": [1, 2, 9], + "col2": ["a", "b", "h"] + }) + assert all(isinstance(child, ds.FilteredDataset) + for child in union_of_filtered_direct.children) + @pytest.mark.parquet def test_filtered_dataset(tempdir, pickle_module): From 240a003b4cd2904e9fa300fd4821dc95084d77dd Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 11:58:16 +1300 Subject: [PATCH 07/15] Handle replacing the schema when using index based field references --- cpp/src/arrow/dataset/dataset.cc | 36 ++++++++++++++++++++++++++- cpp/src/arrow/dataset/dataset_test.cc | 20 +++++++++++++++ python/pyarrow/dataset.py | 6 +++-- python/pyarrow/tests/test_dataset.py | 9 +++++++ 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index f5ab25b1150a..b8a6cebfc00a 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -20,6 +20,7 @@ #include "arrow/acero/util.h" #include "arrow/compute/api_vector.h" +#include "arrow/compute/util.h" #include "arrow/dataset/dataset.h" #include "arrow/dataset/dataset_internal.h" #include "arrow/dataset/projector.h" @@ -406,6 +407,37 @@ FilteredDataset::FilteredDataset(std::shared_ptr child, child_(std::move(child)), filter_(std::move(filter)) {} +namespace { + +// Replace positional field references with references by name, so the expression +// refers to the same fields if the schema is replaced with one that reorders them. +Result FieldRefsToNames(compute::Expression expr, + const Schema& schema) { + return compute::ModifyExpression( + std::move(expr), + [&schema](compute::Expression e) -> Result { + const FieldRef* ref = e.field_ref(); + if (ref == nullptr || ref->IsNameSequence()) { + return e; + } + ARROW_ASSIGN_OR_RAISE(auto path, ref->FindOne(schema)); + std::vector names; + const FieldVector* fields = &schema.fields(); + for (int index : path.indices()) { + const auto& field = (*fields)[index]; + names.emplace_back(field->name()); + fields = &field->type()->fields(); + } + FieldRef by_name(std::move(names)); + // Fails if a name is ambiguous, e.g. due to duplicate field names + RETURN_NOT_OK(by_name.FindOne(schema)); + return compute::field_ref(std::move(by_name)); + }, + [](compute::Expression e, compute::Expression*) { return e; }); +} + +} // namespace + Result> FilteredDataset::Make( std::shared_ptr child, compute::Expression filter) { // Verify the filter produces a bool @@ -415,7 +447,9 @@ Result> FilteredDataset::Make( *bound.type()); } // Store the unbound filter so it can be bound on-demand on the unified schema of a - // UnionDataset. + // UnionDataset, with fields referenced by name so the filter refers to the same + // fields if they are reordered. + ARROW_ASSIGN_OR_RAISE(filter, FieldRefsToNames(std::move(filter), *child->schema())); return std::shared_ptr( new FilteredDataset(std::move(child), std::move(filter))); } diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index 84ba9df42314..2c7028503b5b 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -334,6 +334,26 @@ TEST_F(TestFilteredDataset, ReplaceSchema) { filtered->ReplaceSchema(schema({field("j", utf8())}))); } +TEST_F(TestFilteredDataset, ReplaceSchemaWithPositionalFieldRef) { + SetSchema({field("x", int32()), field("y", int32())}); + auto batch = RecordBatchFromJSON(schema_, R"([[0, 1], [1, 0]])"); + auto child = std::make_shared(schema_, RecordBatchVector{batch}); + // field 0 refers to x in the child's schema + ASSERT_OK_AND_ASSIGN( + auto filtered, + FilteredDataset::Make( + child, compute::equal(compute::field_ref(FieldRef(0)), compute::literal(1)))); + + // The filter must keep referring to x after the columns are reordered. + auto reordered = schema({field("y", int32()), field("x", int32())}); + ASSERT_OK_AND_ASSIGN(auto replaced, filtered->ReplaceSchema(reordered)); + ASSERT_OK_AND_ASSIGN(auto builder, replaced->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(reordered, {R"([[0, 1]])"}), *table, + /*same_chunk_layout=*/false); +} + TEST_F(TestFilteredDataset, FilterOnPartitionField) { SetSchema({field("part", int32()), field("i", int32())}); auto make_fragment = [this](int32_t part, const std::string& json) { diff --git a/python/pyarrow/dataset.py b/python/pyarrow/dataset.py index eac23921a799..790ff93ac039 100644 --- a/python/pyarrow/dataset.py +++ b/python/pyarrow/dataset.py @@ -501,8 +501,10 @@ def _union_dataset(children, schema=None, **kwargs): # unify the children datasets' schemas schema = pa.unify_schemas([child.schema for child in children]) - # create datasets with the requested schema - children = [child.replace_schema(schema) for child in children] + # create datasets with the requested schema, attaching any filter first so + # it's resolved against the child's own schema + children = [child._with_filter_attached().replace_schema(schema) + for child in children] return UnionDataset(schema, children) diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index f8a1af9120b3..ce9241de08b1 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5662,6 +5662,15 @@ def test_union_dataset_filter(tempdir, dstype): for child in union_of_filtered_direct.children) +def test_union_dataset_filter_positional_field_ref(): + # A positional field reference keeps referring to the same column + # when the union reorders the columns. + child = ds.dataset(pa.table({"x": [0, 1], "y": [1, 0]})) + reordered = pa.schema([("y", pa.int64()), ("x", pa.int64())]) + union = ds.dataset([child.filter(pc.field(0) == 1)], schema=reordered) + assert union.to_table().to_pylist() == [{"y": 0, "x": 1}] + + @pytest.mark.parquet def test_filtered_dataset(tempdir, pickle_module): table = pa.table({"part": [1, 1, 2, 2], "value": [1, 2, 3, 4]}) From 336d281b70ec2dabf15e5015b3ae2c9da714734a Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 12:15:26 +1300 Subject: [PATCH 08/15] Add extra checks when constructing a fFilteredFragment --- cpp/src/arrow/dataset/dataset.cc | 36 ++++++++++++++----- cpp/src/arrow/dataset/dataset_test.cc | 50 +++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 8 deletions(-) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index b8a6cebfc00a..fb2e0c41e2c1 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -344,16 +344,41 @@ std::string FilteredFragment::ToString() const { return fragment_->ToString(); } +namespace { + +// Bind a FilteredFragment's filter to the dataset schema of the scan options. +// FilteredFragment can be constructed and scanned directly, so validate the inputs. +Result BindFragmentFilter(const compute::Expression& filter, + const ScanOptions& options) { + if (options.dataset_schema == nullptr) { + return Status::Invalid("Scanning a FilteredFragment requires a dataset schema"); + } + ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*options.dataset_schema)); + if (!bound.type()->Equals(*boolean())) { + return Status::TypeError("FilteredFragment filter must be boolean, got ", + *bound.type()); + } + return bound; +} + +} // namespace + Result FilteredFragment::ScanBatchesAsync( const std::shared_ptr& options) { const auto& dataset_schema = options->dataset_schema; - ARROW_ASSIGN_OR_RAISE(auto filter, filter_.Bind(*dataset_schema)); + ARROW_ASSIGN_OR_RAISE(auto filter, BindFragmentFilter(filter_, *options)); ARROW_ASSIGN_OR_RAISE(filter, SimplifyWithGuarantee(std::move(filter), partition_expression_)); if (!filter.IsSatisfiable()) { return MakeEmptyGenerator>(); } + // The filter might simplify to true if it only references partition fields, + // in which case the wrapped fragment can be scanned unchanged. + if (filter == compute::literal(true)) { + return fragment_->ScanBatchesAsync(options); + } + // Combine any existing filter in the scan options with the fragment's filter, // so the wrapped fragment can skip data that cannot match. auto fragment_options = std::make_shared(*options); @@ -361,12 +386,6 @@ Result FilteredFragment::ScanBatchesAsync( compute::and_(options->filter, filter).Bind(*dataset_schema)); ARROW_ASSIGN_OR_RAISE(auto batches, fragment_->ScanBatchesAsync(fragment_options)); - // The filter might simplify to true if it only references partition fields, - // in which case we can skip filtering batches. - if (filter == compute::literal(true)) { - return batches; - } - // Apply the fragment's filter to scanned rows. // The filter in the scan options is only used for data pruning at this point // and will be used to filter rows later, so don't duplicate that work. @@ -395,9 +414,10 @@ Result FilteredFragment::ScanBatchesAsync( Future> FilteredFragment::CountRows( compute::Expression predicate, const std::shared_ptr& options) { + ARROW_ASSIGN_OR_RAISE(auto filter, BindFragmentFilter(filter_, *options)); ARROW_ASSIGN_OR_RAISE( auto combined, - compute::and_(std::move(predicate), filter_).Bind(*options->dataset_schema)); + compute::and_(std::move(predicate), filter).Bind(*options->dataset_schema)); return fragment_->CountRows(std::move(combined), options); } diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index 2c7028503b5b..a916e92e2ebf 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -427,6 +427,56 @@ TEST_F(TestFilteredDataset, ScalarFilterResult) { ASSERT_OK_AND_EQ(2, scanner->CountRows()); } +TEST_F(TestFilteredDataset, ScanFragmentDirectly) { + SetSchema({field("i", int32()), field("n", null())}); + auto batch = RecordBatchFromJSON(schema_, R"([[1, null], [2, null]])"); + auto fragment = std::make_shared(schema_, RecordBatchVector{batch}); + auto filtered = std::make_shared( + fragment, compute::greater(compute::field_ref("i"), compute::literal(1))); + + // The scan options must have a dataset schema. + auto options = std::make_shared(); + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, + testing::HasSubstr("requires a dataset schema"), + filtered->ScanBatchesAsync(options)); + auto count = filtered->CountRows(compute::literal(true), options); + EXPECT_RAISES_WITH_MESSAGE_THAT( + Invalid, testing::HasSubstr("requires a dataset schema"), count.result()); + + options->dataset_schema = schema_; + ASSERT_OK_AND_ASSIGN(auto batch_gen, filtered->ScanBatchesAsync(options)); + ASSERT_FINISHES_OK_AND_ASSIGN(auto batches, CollectAsyncGenerator(batch_gen)); + ASSERT_EQ(1, batches.size()); + AssertBatchesEqual(*RecordBatchFromJSON(schema_, R"([[2, null]])"), *batches[0]); + + // The filter must be boolean. A null-typed filter would otherwise be implicitly + // cast when combined with other filters. + auto non_boolean = + std::make_shared(fragment, compute::field_ref("n")); + EXPECT_RAISES_WITH_MESSAGE_THAT(TypeError, testing::HasSubstr("must be boolean"), + non_boolean->ScanBatchesAsync(options)); + count = non_boolean->CountRows(compute::literal(true), options); + EXPECT_RAISES_WITH_MESSAGE_THAT(TypeError, testing::HasSubstr("must be boolean"), + count.result()); +} + +TEST_F(TestFilteredDataset, FilterOnAugmentedField) { + SetSchema({field("i", int32())}); + auto batch = RecordBatchFromJSON(schema_, R"([[1], [2]])"); + auto child = std::make_shared(schema_, RecordBatchVector{batch}); + auto filter = + compute::equal(compute::field_ref("__filename"), compute::literal("in-memory")); + + // Augmented fields can't be used in a scan filter, only in the projection. + ASSERT_OK_AND_ASSIGN(auto builder, child->NewScan()); + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, testing::HasSubstr("No match for FieldRef"), + builder->Filter(filter)); + + // So a FilteredDataset rejects them too. + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, testing::HasSubstr("No match for FieldRef"), + FilteredDataset::Make(child, filter)); +} + TEST(TestProjector, CheckProjectable) { struct Assert { explicit Assert(FieldVector from) : from_(from) {} From f97fd8b33b80caf088697e900943c199f9bec8df Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 12:19:31 +1300 Subject: [PATCH 09/15] Simplify against partition expression when counting rows --- cpp/src/arrow/dataset/dataset.cc | 7 +++++++ cpp/src/arrow/dataset/dataset_test.cc | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index fb2e0c41e2c1..ed185d85da0c 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -418,6 +418,13 @@ Future> FilteredFragment::CountRows( ARROW_ASSIGN_OR_RAISE( auto combined, compute::and_(std::move(predicate), filter).Bind(*options->dataset_schema)); + // Simplify so the wrapped fragment can count from metadata where possible, + // matching FileFragment::CountRows. + ARROW_ASSIGN_OR_RAISE(combined, compute::SimplifyWithGuarantee(std::move(combined), + partition_expression_)); + if (!combined.IsSatisfiable()) { + return Future>::MakeFinished(0); + } return fragment_->CountRows(std::move(combined), options); } diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index a916e92e2ebf..20e8534e890c 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -460,6 +460,32 @@ TEST_F(TestFilteredDataset, ScanFragmentDirectly) { count.result()); } +TEST_F(TestFilteredDataset, CountRowsWithPartitionExpression) { + SetSchema({field("part", int32()), field("i", int32())}); + auto batch = RecordBatchFromJSON(schema_, R"([[1, 1], [1, 2]])"); + auto fragment = std::make_shared( + schema_, RecordBatchVector{batch}, + compute::equal(compute::field_ref("part"), compute::literal(1))); + auto options = std::make_shared(); + options->dataset_schema = schema_; + + auto count_rows = [&](compute::Expression filter) { + return std::make_shared(fragment, std::move(filter)) + ->CountRows(compute::literal(true), options); + }; + + // An unsatisfiable filter counts no rows. + ASSERT_FINISHES_OK_AND_EQ(std::make_optional(0), + count_rows(compute::literal(false))); + ASSERT_FINISHES_OK_AND_EQ( + std::make_optional(0), + count_rows(compute::equal(compute::field_ref("part"), compute::literal(2)))); + // A filter guaranteed by the partition expression counts all rows from metadata. + ASSERT_FINISHES_OK_AND_EQ( + std::make_optional(2), + count_rows(compute::equal(compute::field_ref("part"), compute::literal(1)))); +} + TEST_F(TestFilteredDataset, FilterOnAugmentedField) { SetSchema({field("i", int32())}); auto batch = RecordBatchFromJSON(schema_, R"([[1], [2]])"); From 07ff0c04b8ab0b831b153584d6b856aab335e688 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 12:21:28 +1300 Subject: [PATCH 10/15] Check for invalid inputs in FilteredDataset::Make --- cpp/src/arrow/dataset/dataset.cc | 6 ++++++ cpp/src/arrow/dataset/dataset_test.cc | 12 ++++++++++++ 2 files changed, 18 insertions(+) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index ed185d85da0c..0c8840ab01ae 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -467,6 +467,12 @@ Result FieldRefsToNames(compute::Expression expr, Result> FilteredDataset::Make( std::shared_ptr child, compute::Expression filter) { + if (child == nullptr) { + return Status::Invalid("FilteredDataset child must not be null"); + } + if (!filter.is_valid()) { + return Status::Invalid("FilteredDataset filter must be a valid expression"); + } // Verify the filter produces a bool ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*child->schema())); if (!bound.type()->Equals(*boolean())) { diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index 20e8534e890c..261e29e1f2be 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -460,6 +460,18 @@ TEST_F(TestFilteredDataset, ScanFragmentDirectly) { count.result()); } +TEST_F(TestFilteredDataset, MakeWithInvalidArguments) { + SetSchema({field("i", int32())}); + auto child = std::make_shared(schema_, RecordBatchVector{}); + auto filter = compute::greater(compute::field_ref("i"), compute::literal(1)); + + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, testing::HasSubstr("child must not be null"), + FilteredDataset::Make(nullptr, filter)); + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, + testing::HasSubstr("must be a valid expression"), + FilteredDataset::Make(child, compute::Expression())); +} + TEST_F(TestFilteredDataset, CountRowsWithPartitionExpression) { SetSchema({field("part", int32()), field("i", int32())}); auto batch = RecordBatchFromJSON(schema_, R"([[1, 1], [1, 2]])"); From e8f5f26b793d8b2700bcd0711756ad3a76792d9a Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 12:40:46 +1300 Subject: [PATCH 11/15] Simplify filters against the partition guarantee before making a FilteredFragment This allows standalone reads of the fragment to work when the filter references partition fields. --- cpp/src/arrow/dataset/dataset.cc | 15 +++++++++++---- python/pyarrow/tests/test_dataset.py | 11 +++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index 0c8840ab01ae..6ea001568db4 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -504,10 +504,17 @@ Result FilteredDataset::GetFragmentsImpl( child_->GetFragments(std::move(combined_predicate))); // Convert the child's fragments to FilteredFragments that apply the additional filter. - auto filter = filter_; - return MakeMapIterator( - [filter](std::shared_ptr fragment) -> std::shared_ptr { - return std::make_shared(std::move(fragment), filter); + // The filter is simplified using each fragment's partition expression, which removes + // references to partition fields, so a fragment can also be scanned with only its + // physical schema. + ARROW_ASSIGN_OR_RAISE(auto filter, filter_.Bind(*schema_)); + return MakeMaybeMapIterator( + [filter](std::shared_ptr fragment) -> Result> { + ARROW_ASSIGN_OR_RAISE( + auto fragment_filter, + compute::SimplifyWithGuarantee(filter, fragment->partition_expression())); + return std::make_shared(std::move(fragment), + std::move(fragment_filter)); }, std::move(fragments)); } diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index ce9241de08b1..d20802bd561a 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5696,6 +5696,17 @@ def test_filtered_dataset(tempdir, pickle_module): assert len(list(on_part.get_fragments())) == 1 assert on_part.to_table()["value"].to_pylist() == [3, 4] + # Fragments can be scanned without a schema, + # in which case partition fields are excluded from the returned batches. + (fragment,) = on_part.get_fragments() + assert fragment.to_table().to_pylist() == [{"value": 3}, {"value": 4}] + assert fragment.count_rows() == 2 + on_part_and_value = ds.FilteredDataset( + dataset, (pc.field("part") == 2) & (pc.field("value") > 3)) + (fragment,) = on_part_and_value.get_fragments() + assert fragment.to_table().to_pylist() == [{"value": 4}] + assert fragment.count_rows() == 1 + # A lazy filter on the child is folded into the FilteredDataset's filter. combined = ds.FilteredDataset(dataset.filter(pc.field("value") < 4), pc.field("value") > 1) From f18b83c0872997d1dce5aa1285d3ca0793863b4a Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 14:08:50 +1300 Subject: [PATCH 12/15] Add check for valid expression in FilteredFragment scan --- cpp/src/arrow/dataset/dataset.cc | 3 +++ cpp/src/arrow/dataset/dataset_test.cc | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc index 6ea001568db4..4157c776a647 100644 --- a/cpp/src/arrow/dataset/dataset.cc +++ b/cpp/src/arrow/dataset/dataset.cc @@ -353,6 +353,9 @@ Result BindFragmentFilter(const compute::Expression& filter if (options.dataset_schema == nullptr) { return Status::Invalid("Scanning a FilteredFragment requires a dataset schema"); } + if (!filter.is_valid()) { + return Status::Invalid("FilteredFragment filter must be a valid expression"); + } ARROW_ASSIGN_OR_RAISE(auto bound, filter.Bind(*options.dataset_schema)); if (!bound.type()->Equals(*boolean())) { return Status::TypeError("FilteredFragment filter must be boolean, got ", diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index 261e29e1f2be..9e5075581714 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -458,6 +458,15 @@ TEST_F(TestFilteredDataset, ScanFragmentDirectly) { count = non_boolean->CountRows(compute::literal(true), options); EXPECT_RAISES_WITH_MESSAGE_THAT(TypeError, testing::HasSubstr("must be boolean"), count.result()); + + // The filter must be a valid expression. + auto invalid = std::make_shared(fragment, compute::Expression()); + EXPECT_RAISES_WITH_MESSAGE_THAT(Invalid, + testing::HasSubstr("must be a valid expression"), + invalid->ScanBatchesAsync(options)); + count = invalid->CountRows(compute::literal(true), options); + EXPECT_RAISES_WITH_MESSAGE_THAT( + Invalid, testing::HasSubstr("must be a valid expression"), count.result()); } TEST_F(TestFilteredDataset, MakeWithInvalidArguments) { From 7b6f207b1720648ba82210538d0fb961a9d952f8 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 14:15:56 +1300 Subject: [PATCH 13/15] Add test to verify handling of an already bound filter --- cpp/src/arrow/dataset/dataset.h | 2 ++ cpp/src/arrow/dataset/dataset_test.cc | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/cpp/src/arrow/dataset/dataset.h b/cpp/src/arrow/dataset/dataset.h index 70ab582fc78a..b1b29d9506e4 100644 --- a/cpp/src/arrow/dataset/dataset.h +++ b/cpp/src/arrow/dataset/dataset.h @@ -525,6 +525,8 @@ class ARROW_DS_EXPORT FilteredDataset : public Dataset { /// /// \param[in] child the Dataset to filter. /// \param[in] filter a boolean expression used to filter rows of the child Dataset. + /// It may be bound or unbound, and is always bound again against the current schema + /// when used. static Result> Make(std::shared_ptr child, compute::Expression filter); diff --git a/cpp/src/arrow/dataset/dataset_test.cc b/cpp/src/arrow/dataset/dataset_test.cc index 9e5075581714..0ba17d0163ce 100644 --- a/cpp/src/arrow/dataset/dataset_test.cc +++ b/cpp/src/arrow/dataset/dataset_test.cc @@ -354,6 +354,24 @@ TEST_F(TestFilteredDataset, ReplaceSchemaWithPositionalFieldRef) { /*same_chunk_layout=*/false); } +TEST_F(TestFilteredDataset, ReplaceSchemaWithBoundPositionalFieldRef) { + SetSchema({field("x", int32()), field("y", int32())}); + auto batch = RecordBatchFromJSON(schema_, R"([[0, 1], [1, 0]])"); + auto child = std::make_shared(schema_, RecordBatchVector{batch}); + // An already bound filter is bound again against the current schema when used + auto filter = compute::equal(compute::field_ref(FieldRef(0)), compute::literal(1)); + ASSERT_OK_AND_ASSIGN(auto bound_filter, filter.Bind(*schema_)); + ASSERT_OK_AND_ASSIGN(auto filtered, FilteredDataset::Make(child, bound_filter)); + + auto reordered = schema({field("y", int32()), field("x", int32())}); + ASSERT_OK_AND_ASSIGN(auto replaced, filtered->ReplaceSchema(reordered)); + ASSERT_OK_AND_ASSIGN(auto builder, replaced->NewScan()); + ASSERT_OK_AND_ASSIGN(auto scanner, builder->Finish()); + ASSERT_OK_AND_ASSIGN(auto table, scanner->ToTable()); + AssertTablesEqual(*TableFromJSON(reordered, {R"([[0, 1]])"}), *table, + /*same_chunk_layout=*/false); +} + TEST_F(TestFilteredDataset, FilterOnPartitionField) { SetSchema({field("part", int32()), field("i", int32())}); auto make_fragment = [this](int32_t part, const std::string& json) { From 488ba8a0883e4a8642b031f95ddd3aa219a6b8e0 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 14:23:10 +1300 Subject: [PATCH 14/15] Add a Python wrapper for the FilteredFragment class --- docs/source/python/api/dataset.rst | 1 + python/pyarrow/_dataset.pyx | 29 ++++++++++++++++++++ python/pyarrow/dataset.py | 1 + python/pyarrow/includes/libarrow_dataset.pxd | 5 ++++ python/pyarrow/tests/test_dataset.py | 10 +++++++ 5 files changed, 46 insertions(+) diff --git a/docs/source/python/api/dataset.rst b/docs/source/python/api/dataset.rst index 2b63c410f694..ebcbf489b57b 100644 --- a/docs/source/python/api/dataset.rst +++ b/docs/source/python/api/dataset.rst @@ -63,6 +63,7 @@ Classes UnionDataset FilteredDataset Fragment + FilteredFragment FragmentScanOptions TaggedRecordBatch Scanner diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx index 58be0d80961c..5851335cb063 100644 --- a/python/pyarrow/_dataset.pyx +++ b/python/pyarrow/_dataset.pyx @@ -1521,6 +1521,7 @@ cdef class Fragment(_Weakrefable): 'json': FileFragment, 'orc': FileFragment, 'parquet': _get_parquet_symbol('ParquetFileFragment'), + 'filtered': FilteredFragment, } class_ = classes.get(type_name, None) @@ -2040,6 +2041,34 @@ cdef class Fragment(_Weakrefable): ).count_rows() +cdef class FilteredFragment(Fragment): + """ + A Fragment of a FilteredDataset, which yields only the rows of a wrapped + Fragment that match a filter. + """ + + cdef: + CFilteredFragment* filtered_fragment + + cdef void init(self, const shared_ptr[CFragment]& sp): + Fragment.init(self, sp) + self.filtered_fragment = sp.get() + + @property + def fragment(self): + """The unfiltered wrapped Fragment.""" + return Fragment.wrap(self.filtered_fragment.fragment()) + + @property + def filter_expression(self): + """ + The filter applied to the wrapped Fragment. This may be simplified + from the FilteredDataset's filter using the Fragment's partition + expression. + """ + return Expression.wrap(self.filtered_fragment.filter()) + + cdef class FileFragment(Fragment): """A Fragment representing a data file.""" diff --git a/python/pyarrow/dataset.py b/python/pyarrow/dataset.py index 790ff93ac039..607085f92b62 100644 --- a/python/pyarrow/dataset.py +++ b/python/pyarrow/dataset.py @@ -49,6 +49,7 @@ TaggedRecordBatch, UnionDataset, FilteredDataset, + FilteredFragment, UnionDatasetFactory, WrittenFile, get_partition_keys, diff --git a/python/pyarrow/includes/libarrow_dataset.pxd b/python/pyarrow/includes/libarrow_dataset.pxd index 42f164ef3ce0..bd4cfa9af83c 100644 --- a/python/pyarrow/includes/libarrow_dataset.pxd +++ b/python/pyarrow/includes/libarrow_dataset.pxd @@ -163,6 +163,11 @@ cdef extern from "arrow/dataset/api.h" namespace "arrow::dataset" nogil: const shared_ptr[CDataset]& child() const const CExpression& filter() const + cdef cppclass CFilteredFragment "arrow::dataset::FilteredFragment"( + CFragment): + const shared_ptr[CFragment]& fragment() const + const CExpression& filter() const + cdef cppclass CInspectOptions "arrow::dataset::InspectOptions": int fragments CField.CMergeOptions field_merge_options diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index d20802bd561a..850562d355d4 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5707,6 +5707,16 @@ def test_filtered_dataset(tempdir, pickle_module): assert fragment.to_table().to_pylist() == [{"value": 4}] assert fragment.count_rows() == 1 + # The wrapped fragment and the simplified filter are accessible. + assert isinstance(fragment, ds.FilteredFragment) + assert isinstance(fragment.fragment, ds.ParquetFileFragment) + assert fragment.fragment.path.startswith(str(tempdir / "2")) + assert fragment.fragment.to_table()["value"].to_pylist() == [3, 4] + # The filter is bound, so compare string representations + assert str(fragment.filter_expression) == str(pc.field("value") > 3) + assert fragment.partition_expression.equals( + fragment.fragment.partition_expression) + # A lazy filter on the child is folded into the FilteredDataset's filter. combined = ds.FilteredDataset(dataset.filter(pc.field("value") < 4), pc.field("value") > 1) From 85ec0c6bb737dac977900c890dca4efe1c3123b1 Mon Sep 17 00:00:00 2001 From: Adam Reeve Date: Mon, 23 Nov 2026 22:36:38 +1300 Subject: [PATCH 15/15] Fix test assertion so path comparison works on Windows --- python/pyarrow/tests/test_dataset.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/pyarrow/tests/test_dataset.py b/python/pyarrow/tests/test_dataset.py index 850562d355d4..2ef4c0f2284c 100644 --- a/python/pyarrow/tests/test_dataset.py +++ b/python/pyarrow/tests/test_dataset.py @@ -5710,7 +5710,7 @@ def test_filtered_dataset(tempdir, pickle_module): # The wrapped fragment and the simplified filter are accessible. assert isinstance(fragment, ds.FilteredFragment) assert isinstance(fragment.fragment, ds.ParquetFileFragment) - assert fragment.fragment.path.startswith(str(tempdir / "2")) + assert pathlib.Path(fragment.fragment.path).parent == tempdir / "2" assert fragment.fragment.to_table()["value"].to_pylist() == [3, 4] # The filter is bound, so compare string representations assert str(fragment.filter_expression) == str(pc.field("value") > 3)