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

zanmato1984 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow.git


The following commit(s) were added to refs/heads/main by this push:
     new 541fcb54b7f GH-55447: [C++][Python] Allow creating a UnionDataset from 
filtered datasets (#55665)
541fcb54b7f is described below

commit 541fcb54b7f4bd0e31d38395b24ca3bb77622a3f
Author: Adam Reeve <[email protected]>
AuthorDate: Wed Nov 25 08:15:56 2026 +1300

    GH-55447: [C++][Python] Allow creating a UnionDataset from filtered 
datasets (#55665)
    
    ### Rationale for this change
    
    `Dataset.filter()` stores a filter on the Python Dataset wrapper, which is 
later used to build scan options. But a `UnionDataset` is represented in C++, 
so filtered Datasets could not be unioned.
    
    See https://github.com/apache/arrow/issues/55447 for more context.
    
    ### What changes are included in this PR?
    
    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`.
    
    The Dataset's filter is combined with any filter in the scan options for 
predicate pushdown. Scanning a `FilteredDataset` generates `FilteredFragment` 
instances, which apply the filter when generating batches. The row-level filter 
doesn't account for any additional filter in the scan options, because that's 
always applied after the scan, so this would just duplicate work.
    
    A possible future optimization could be to implement what was proposed in 
#28944 so a combined filter could be applied once within the fragment, and then 
a guarantee declared that uses the combined filter expression, so the later 
filter could be simplified.
    
    ### Are these changes tested?
    
    Yes, this includes new C++and Python unit tests.
    
    ### Are there any user-facing changes?
    
    This adds new types to the public API and new functionality. You can now 
create a `UnionDataset` using Datasets that have filters, which would 
previously raise an error.
    
    ### Was AI used for this PR?
    
    In accordance to the [AI generation 
guidelines](https://arrow.apache.org/docs/dev/developers/overview.html#ai-generated-code),
 please disclose below whether and how AI was used in this PR.
    
    **PR code and description written by:**
    
    - [x] Human
    - [x] AI
    
    (I used Claude Opus 5.5 for the initial implementation, then reviewed and 
edited everything myself)
    
    **Reviewed before submission by:**
    
    - [x] Human
    - [x] AI
    - [ ] Not reviewed
    
    * GitHub Issue: #55447
    
    Authored-by: Adam Reeve <[email protected]>
    Signed-off-by: Rossi Sun <[email protected]>
---
 cpp/src/arrow/dataset/dataset.cc             | 201 ++++++++++++++++++++
 cpp/src/arrow/dataset/dataset.h              |  63 +++++++
 cpp/src/arrow/dataset/dataset_test.cc        | 265 +++++++++++++++++++++++++++
 cpp/src/arrow/dataset/type_fwd.h             |   3 +
 docs/source/python/api/dataset.rst           |   2 +
 python/pyarrow/_dataset.pyx                  |  92 ++++++++++
 python/pyarrow/dataset.py                    |  16 +-
 python/pyarrow/includes/libarrow_dataset.pxd |  14 ++
 python/pyarrow/tests/test_dataset.py         | 144 ++++++++++++++-
 9 files changed, 788 insertions(+), 12 deletions(-)

diff --git a/cpp/src/arrow/dataset/dataset.cc b/cpp/src/arrow/dataset/dataset.cc
index 2925cbf0003..4157c776a64 100644
--- a/cpp/src/arrow/dataset/dataset.cc
+++ b/cpp/src/arrow/dataset/dataset.cc
@@ -19,6 +19,8 @@
 #include <utility>
 
 #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"
@@ -321,6 +323,205 @@ Result<FragmentIterator> 
UnionDataset::GetFragmentsImpl(compute::Expression pred
   return GetFragmentsFromDatasets(children_, predicate);
 }
 
+FilteredFragment::FilteredFragment(std::shared_ptr<Fragment> fragment,
+                                   compute::Expression filter)
+    : Fragment(fragment->partition_expression(), /*physical_schema=*/nullptr),
+      fragment_(std::move(fragment)),
+      filter_(std::move(filter)) {}
+
+Result<std::shared_ptr<Schema>> FilteredFragment::ReadPhysicalSchemaImpl() {
+  return fragment_->ReadPhysicalSchema();
+}
+
+Status FilteredFragment::ClearCachedMetadata() {
+  RETURN_NOT_OK(Fragment::ClearCachedMetadata());
+  return fragment_->ClearCachedMetadata();
+}
+
+std::string FilteredFragment::ToString() const {
+  // The scanner uses ToString() for the __filename augmented field, so this 
must
+  // match the wrapped fragment.
+  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<compute::Expression> BindFragmentFilter(const compute::Expression& 
filter,
+                                               const ScanOptions& options) {
+  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 ",
+                             *bound.type());
+  }
+  return bound;
+}
+
+}  // namespace
+
+Result<RecordBatchGenerator> FilteredFragment::ScanBatchesAsync(
+    const std::shared_ptr<ScanOptions>& options) {
+  const auto& dataset_schema = options->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<std::shared_ptr<RecordBatch>>();
+  }
+
+  // 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<ScanOptions>(*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));
+
+  // 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<RecordBatch>& batch)
+          -> Result<std::shared_ptr<RecordBatch>> {
+        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<BooleanScalar>();
+          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<std::optional<int64_t>> FilteredFragment::CountRows(
+    compute::Expression predicate, const std::shared_ptr<ScanOptions>& 
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));
+  // 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<std::optional<int64_t>>::MakeFinished(0);
+  }
+  return fragment_->CountRows(std::move(combined), options);
+}
+
+FilteredDataset::FilteredDataset(std::shared_ptr<Dataset> child,
+                                 compute::Expression filter)
+    : Dataset(child->schema(), child->partition_expression()),
+      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<compute::Expression> FieldRefsToNames(compute::Expression expr,
+                                             const Schema& schema) {
+  return compute::ModifyExpression(
+      std::move(expr),
+      [&schema](compute::Expression e) -> Result<compute::Expression> {
+        const FieldRef* ref = e.field_ref();
+        if (ref == nullptr || ref->IsNameSequence()) {
+          return e;
+        }
+        ARROW_ASSIGN_OR_RAISE(auto path, ref->FindOne(schema));
+        std::vector<FieldRef> 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<std::shared_ptr<FilteredDataset>> FilteredDataset::Make(
+    std::shared_ptr<Dataset> 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())) {
+    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, 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<FilteredDataset>(
+      new FilteredDataset(std::move(child), std::move(filter)));
+}
+
+Result<std::shared_ptr<Dataset>> FilteredDataset::ReplaceSchema(
+    std::shared_ptr<Schema> 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<Dataset>(std::move(filtered));
+}
+
+Result<FragmentIterator> 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.
+  // 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> fragment) -> 
Result<std::shared_ptr<Fragment>> {
+        ARROW_ASSIGN_OR_RAISE(
+            auto fragment_filter,
+            compute::SimplifyWithGuarantee(filter, 
fragment->partition_expression()));
+        return std::make_shared<FilteredFragment>(std::move(fragment),
+                                                  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 5c788ef5581..b1b29d9506e 100644
--- a/cpp/src/arrow/dataset/dataset.h
+++ b/cpp/src/arrow/dataset/dataset.h
@@ -485,6 +485,69 @@ 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> fragment, compute::Expression 
filter);
+
+  Result<RecordBatchGenerator> ScanBatchesAsync(
+      const std::shared_ptr<ScanOptions>& options) override;
+
+  Future<std::optional<int64_t>> CountRows(
+      compute::Expression predicate,
+      const std::shared_ptr<ScanOptions>& options) override;
+
+  Status ClearCachedMetadata() override;
+
+  std::string type_name() const override { return "filtered"; }
+
+  std::string ToString() const override;
+
+  const std::shared_ptr<Fragment>& fragment() const { return fragment_; }
+
+  const compute::Expression& filter() const { return filter_; }
+
+ protected:
+  Result<std::shared_ptr<Schema>> ReadPhysicalSchemaImpl() override;
+
+  std::shared_ptr<Fragment> 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.
+  /// It may be bound or unbound, and is always bound again against the 
current schema
+  /// when used.
+  static Result<std::shared_ptr<FilteredDataset>> 
Make(std::shared_ptr<Dataset> child,
+                                                       compute::Expression 
filter);
+
+  const std::shared_ptr<Dataset>& child() const { return child_; }
+
+  const compute::Expression& filter() const { return filter_; }
+
+  std::string type_name() const override { return "filtered"; }
+
+  Result<std::shared_ptr<Dataset>> ReplaceSchema(
+      std::shared_ptr<Schema> schema) const override;
+
+ protected:
+  Result<FragmentIterator> GetFragmentsImpl(compute::Expression predicate) 
override;
+
+  FilteredDataset(std::shared_ptr<Dataset> child, compute::Expression filter);
+
+  std::shared_ptr<Dataset> 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 cd23429bf5e..0ba17d0163c 100644
--- a/cpp/src/arrow/dataset/dataset_test.cc
+++ b/cpp/src/arrow/dataset/dataset_test.cc
@@ -277,6 +277,271 @@ 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<InMemoryDataset>(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<InMemoryDataset>(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, ReplaceSchemaWithPositionalFieldRef) {
+  SetSchema({field("x", int32()), field("y", int32())});
+  auto batch = RecordBatchFromJSON(schema_, R"([[0, 1], [1, 0]])");
+  auto child = std::make_shared<InMemoryDataset>(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, ReplaceSchemaWithBoundPositionalFieldRef) {
+  SetSchema({field("x", int32()), field("y", int32())});
+  auto batch = RecordBatchFromJSON(schema_, R"([[0, 1], [1, 0]])");
+  auto child = std::make_shared<InMemoryDataset>(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) {
+    return std::make_shared<InMemoryFragment>(
+        schema_, RecordBatchVector{RecordBatchFromJSON(schema_, json)},
+        compute::equal(compute::field_ref("part"), compute::literal(part)));
+  };
+  auto child = std::make_shared<FragmentDataset>(
+      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_EQ("filtered", fragments[0]->type_name());
+  // ToString() is used for the __filename field, so must match the wrapped 
fragment.
+  ASSERT_EQ(checked_cast<const 
FilteredFragment&>(*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());
+  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<InMemoryDataset>(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_F(TestFilteredDataset, ScanFragmentDirectly) {
+  SetSchema({field("i", int32()), field("n", null())});
+  auto batch = RecordBatchFromJSON(schema_, R"([[1, null], [2, null]])");
+  auto fragment = std::make_shared<InMemoryFragment>(schema_, 
RecordBatchVector{batch});
+  auto filtered = std::make_shared<FilteredFragment>(
+      fragment, compute::greater(compute::field_ref("i"), 
compute::literal(1)));
+
+  // The scan options must have a dataset schema.
+  auto options = std::make_shared<ScanOptions>();
+  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<FilteredFragment>(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());
+
+  // The filter must be a valid expression.
+  auto invalid = std::make_shared<FilteredFragment>(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) {
+  SetSchema({field("i", int32())});
+  auto child = std::make_shared<InMemoryDataset>(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]])");
+  auto fragment = std::make_shared<InMemoryFragment>(
+      schema_, RecordBatchVector{batch},
+      compute::equal(compute::field_ref("part"), compute::literal(1)));
+  auto options = std::make_shared<ScanOptions>();
+  options->dataset_schema = schema_;
+
+  auto count_rows = [&](compute::Expression filter) {
+    return std::make_shared<FilteredFragment>(fragment, std::move(filter))
+        ->CountRows(compute::literal(true), options);
+  };
+
+  // An unsatisfiable filter counts no rows.
+  ASSERT_FINISHES_OK_AND_EQ(std::make_optional<int64_t>(0),
+                            count_rows(compute::literal(false)));
+  ASSERT_FINISHES_OK_AND_EQ(
+      std::make_optional<int64_t>(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<int64_t>(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]])");
+  auto child = std::make_shared<InMemoryDataset>(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) {}
diff --git a/cpp/src/arrow/dataset/type_fwd.h b/cpp/src/arrow/dataset/type_fwd.h
index d58781e038d..c2db45b53cd 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;
diff --git a/docs/source/python/api/dataset.rst 
b/docs/source/python/api/dataset.rst
index 4867c7bd716..ebcbf489b57 100644
--- a/docs/source/python/api/dataset.rst
+++ b/docs/source/python/api/dataset.rst
@@ -61,7 +61,9 @@ Classes
    FileSystemFactoryOptions
    FileSystemDatasetFactory
    UnionDataset
+   FilteredDataset
    Fragment
+   FilteredFragment
    FragmentScanOptions
    TaggedRecordBatch
    Scanner
diff --git a/python/pyarrow/_dataset.pyx b/python/pyarrow/_dataset.pyx
index 4820027ee82..5851335cb06 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.
@@ -1078,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(
@@ -1097,6 +1111,55 @@ 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(<shared_ptr[CDataset]> GetResultValue(
+            CFilteredDataset.Make(child.wrapped, (<Expression> 
filter).unwrap())))
+
+    cdef void init(self, const shared_ptr[CDataset]& sp):
+        Dataset.init(self, sp)
+        self.filtered_dataset = <CFilteredDataset*> sp.get()
+
+    def __reduce__(self):
+        return (FilteredDataset, (self.child, self.filter_expression),
+                self._scan_options.copy())
+
+    def __setstate__(self, state):
+        self._scan_options = state
+
+    @property
+    def child(self):
+        """The unfiltered child Dataset."""
+        return Dataset.wrap(self.filtered_dataset.child())
+
+    @property
+    def filter_expression(self):
+        """The filter applied to the child Dataset."""
+        return Expression.wrap(self.filtered_dataset.filter())
+
+
 cdef class FileSystemDataset(Dataset):
     """
     A Dataset of file fragments.
@@ -1458,6 +1521,7 @@ cdef class Fragment(_Weakrefable):
             'json': FileFragment,
             'orc': FileFragment,
             'parquet': _get_parquet_symbol('ParquetFileFragment'),
+            'filtered': FilteredFragment,
         }
 
         class_ = classes.get(type_name, None)
@@ -1977,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 = <CFilteredFragment*> 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 f696d5f03ba..607085f92b6 100644
--- a/python/pyarrow/dataset.py
+++ b/python/pyarrow/dataset.py
@@ -48,6 +48,8 @@ try:
         Scanner,
         TaggedRecordBatch,
         UnionDataset,
+        FilteredDataset,
+        FilteredFragment,
         UnionDatasetFactory,
         WrittenFile,
         get_partition_keys,
@@ -500,16 +502,10 @@ 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, 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/includes/libarrow_dataset.pxd 
b/python/pyarrow/includes/libarrow_dataset.pxd
index 12cf8273393..bd4cfa9af83 100644
--- a/python/pyarrow/includes/libarrow_dataset.pxd
+++ b/python/pyarrow/includes/libarrow_dataset.pxd
@@ -154,6 +154,20 @@ 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 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 fd5a418aaf2..2ef4c0f2284 100644
--- a/python/pyarrow/tests/test_dataset.py
+++ b/python/pyarrow/tests/test_dataset.py
@@ -5627,8 +5627,148 @@ 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"]
+    })
+
+    # 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)
+
+
+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}]
+
+
[email protected]
+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_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 __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]
+
+    # 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]
+
+    # 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
+
+    # The wrapped fragment and the simplified filter are accessible.
+    assert isinstance(fragment, ds.FilteredFragment)
+    assert isinstance(fragment.fragment, ds.ParquetFileFragment)
+    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)
+    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)
+    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
+
+    # 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):
+        ds.FilteredDataset(dataset, pc.field("value") + 1)
+
+
[email protected]
+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):

Reply via email to