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

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git


The following commit(s) were added to refs/heads/main by this push:
     new e4866cd39 feat(table): add `WithDictionaryColumns` scan option (#2677)
e4866cd39 is described below

commit e4866cd3936d4e08cccbd43918776abeeda43129
Author: Harrison Crosse <[email protected]>
AuthorDate: Mon Nov 23 13:53:59 2026 -0500

    feat(table): add `WithDictionaryColumns` scan option (#2677)
    
    * feat(table): add WithDictionaryColumns scan option
    
    WithDictionaryColumns returns the named string and binary columns as
    Arrow dictionary<int32, utf8|binary> arrays. The Parquet reader reads them
    as dictionaries, and the projection re-encodes any column a file returns
    plain or as a large type, so the declared schema and every batch agree.
    Columns read only for a row filter, delete-file reads and internal scans
    are unaffected.
    
    Signed-off-by: Harrison Crosse <[email protected]>
    
    * docs(table): document filtered scan decoding and defaultToArray context
    
    Signed-off-by: Harrison Crosse <[email protected]>
    
    ---------
    
    Signed-off-by: Harrison Crosse <[email protected]>
---
 table/arrow_scanner.go                |  32 +-
 table/arrow_utils.go                  |  89 ++++-
 table/changelog_normalization.go      |   9 +-
 table/changelog_reader.go             |  10 +-
 table/internal/interfaces.go          |   9 +
 table/internal/parquet_files.go       |  65 ++++
 table/scan_dictionary_columns_test.go | 665 ++++++++++++++++++++++++++++++++++
 table/scanner.go                      |  50 +++
 table/table.go                        |  26 ++
 website/src/api.md                    |   8 +
 10 files changed, 939 insertions(+), 24 deletions(-)

diff --git a/table/arrow_scanner.go b/table/arrow_scanner.go
index 1f242665c..c5e1ed79d 100644
--- a/table/arrow_scanner.go
+++ b/table/arrow_scanner.go
@@ -1638,6 +1638,8 @@ type arrowScan struct {
        // read.parquet.batch-size property for this scan's reads.
        arrowBatchSize int
 
+       dictionaryFieldIDs set[int]
+
        // added is nil for a normal scan. A changelog deleted-row read sets it 
so
        // rows matched by that snapshot's new deletes are kept.
        added *addedDeleteState
@@ -1902,6 +1904,13 @@ func (s *recordSink) handOff() taskCredits {
        return s.credits
 }
 
+func (as *arrowScan) emptyBatchSchema() (*arrow.Schema, error) {
+       return SchemaToArrowSchemaWithOptions(as.projectedSchema, 
ArrowSchemaOptions{
+               UseLargeTypes:      as.useLargeTypes,
+               dictionaryFieldIDs: as.dictionaryFieldIDs,
+       })
+}
+
 func (as *arrowScan) prepareToRead(
        ctx context.Context,
        file iceberg.DataFile,
@@ -1924,6 +1933,14 @@ func (as *arrowScan) prepareToRead(
                }
        }(rdr)
 
+       // Each reader needs this, including those that reuse a cached plan.
+       // Readers without dictionary support fall back to the projection's 
encode.
+       if dr, ok := rdr.(tblutils.DictionaryReader); ok && 
len(as.dictionaryFieldIDs) > 0 {
+               if err = dr.ReadDictionaries(as.dictionaryFieldIDs, 
invariants.nameMapping); err != nil {
+                       return nil, nil, nil, err
+               }
+       }
+
        readPrunedSchemaForIDs := func(projectedIDs map[int]struct{}) 
(*iceberg.Schema, []int, error) {
                fileSchema, colIndices, err := rdr.PrunedSchema(projectedIDs, 
invariants.nameMapping)
                if err != nil {
@@ -1972,7 +1989,6 @@ func (as *arrowScan) prepareToRead(
 
                return readPrunedSchemaForIDs(expandedIDs)
        }
-
        if !as.cacheFileReadPlan {
                iceSchema, colIndices, err = readPrunedSchema()
                if err != nil {
@@ -2735,7 +2751,7 @@ func (as *arrowScan) processRecordsWithPlans(
                // an empty batch just like the dropFile path does; without it 
every
                // record queued behind this task is silently discarded on 
close.
                var emptySchema *arrow.Schema
-               emptySchema, err = SchemaToArrowSchema(as.projectedSchema, nil, 
false, as.useLargeTypes)
+               emptySchema, err = as.emptyBatchSchema()
                if err != nil {
                        return err
                }
@@ -2980,7 +2996,7 @@ func (as *arrowScan) recordsFromTask(ctx context.Context, 
task tblutils.Enumerat
 
        if dropFile {
                var emptySchema *arrow.Schema
-               emptySchema, err = SchemaToArrowSchema(as.projectedSchema, nil, 
false, as.useLargeTypes)
+               emptySchema, err = as.emptyBatchSchema()
                if err != nil {
                        return err
                }
@@ -3012,8 +3028,9 @@ func (as *arrowScan) recordsFromTask(ctx context.Context, 
task tblutils.Enumerat
                }
 
                return ToRequestedSchema(ctx, as.projectedSchema, readSchema, 
r, SchemaOptions{
-                       UseLargeTypes:   as.useLargeTypes,
-                       TableProperties: invariants.tableProperties,
+                       UseLargeTypes:      as.useLargeTypes,
+                       TableProperties:    invariants.tableProperties,
+                       dictionaryFieldIDs: as.dictionaryFieldIDs,
                })
        })
 
@@ -3439,8 +3456,9 @@ func (as *arrowScan) prepareTaskReads(ctx 
context.Context, tasks []FileScanTask)
        ctx = tblutils.WithTableProperties(ctx, tableProperties)
 
        resultSchema, err := SchemaToArrowSchemaWithOptions(as.projectedSchema, 
ArrowSchemaOptions{
-               UseLargeTypes:   as.useLargeTypes,
-               TableProperties: tableProperties,
+               UseLargeTypes:      as.useLargeTypes,
+               TableProperties:    tableProperties,
+               dictionaryFieldIDs: as.dictionaryFieldIDs,
        })
        if err != nil {
                return nil, nil, err
diff --git a/table/arrow_utils.go b/table/arrow_utils.go
index a34515fe3..ad75e771f 100644
--- a/table/arrow_utils.go
+++ b/table/arrow_utils.go
@@ -601,10 +601,11 @@ func ensureSmallArrowTypes(dt arrow.DataType) 
(arrow.DataType, error) {
 }
 
 type convertToArrow struct {
-       metadata        map[string]string
-       includeFieldIDs bool
-       useLargeTypes   bool
-       tableProperties iceberg.Properties
+       metadata           map[string]string
+       includeFieldIDs    bool
+       useLargeTypes      bool
+       tableProperties    iceberg.Properties
+       dictionaryFieldIDs set[int]
 }
 
 func (c convertToArrow) Schema(_ *iceberg.Schema, result arrow.Field) 
arrow.Field {
@@ -632,10 +633,23 @@ func (c convertToArrow) Field(field iceberg.NestedField, 
result arrow.Field) arr
        }
 
        result.Name, result.Nullable = field.Name, !field.Required
+       if _, ok := c.dictionaryFieldIDs[field.ID]; ok {
+               result.Type = dictionaryArrowType(field.Type)
+       }
 
        return result
 }
 
+// dictionaryArrowType requires t to be an Iceberg string or binary type.
+func dictionaryArrowType(t iceberg.Type) *arrow.DictionaryType {
+       valueType := arrow.BinaryTypes.String
+       if _, ok := t.(iceberg.BinaryType); ok {
+               valueType = arrow.BinaryTypes.Binary
+       }
+
+       return &arrow.DictionaryType{IndexType: arrow.PrimitiveTypes.Int32, 
ValueType: valueType}
+}
+
 func (c convertToArrow) List(list iceberg.ListType, elemResult arrow.Field) 
arrow.Field {
        elemField := c.Field(list.ElementField(), elemResult)
        if c.useLargeTypes {
@@ -790,6 +804,8 @@ type ArrowSchemaOptions struct {
        IncludeFieldIDs bool
        UseLargeTypes   bool
        TableProperties iceberg.Properties
+
+       dictionaryFieldIDs set[int]
 }
 
 // SchemaToArrowSchema converts an Iceberg schema to an Arrow schema. If the 
metadata parameter
@@ -809,10 +825,11 @@ func SchemaToArrowSchema(sc *iceberg.Schema, metadata 
map[string]string, include
 // metadata in the table properties.
 func SchemaToArrowSchemaWithOptions(sc *iceberg.Schema, opts 
ArrowSchemaOptions) (*arrow.Schema, error) {
        top, err := iceberg.Visit(sc, convertToArrow{
-               metadata:        opts.Metadata,
-               includeFieldIDs: opts.IncludeFieldIDs,
-               useLargeTypes:   opts.UseLargeTypes,
-               tableProperties: opts.TableProperties,
+               metadata:           opts.Metadata,
+               includeFieldIDs:    opts.IncludeFieldIDs,
+               useLargeTypes:      opts.UseLargeTypes,
+               tableProperties:    opts.TableProperties,
+               dictionaryFieldIDs: opts.dictionaryFieldIDs,
        })
        if err != nil {
                return nil, err
@@ -837,9 +854,10 @@ func TypeToArrowType(t iceberg.Type, includeFieldIDs bool, 
useLargeTypes bool) (
 func TypeToArrowTypeWithOptions(t iceberg.Type, opts ArrowSchemaOptions) 
(arrow.DataType, error) {
        top, err := iceberg.Visit(iceberg.NewSchema(0, 
iceberg.NestedField{Type: t}),
                convertToArrow{
-                       includeFieldIDs: opts.IncludeFieldIDs,
-                       useLargeTypes:   opts.UseLargeTypes,
-                       tableProperties: opts.TableProperties,
+                       includeFieldIDs:    opts.IncludeFieldIDs,
+                       useLargeTypes:      opts.UseLargeTypes,
+                       tableProperties:    opts.TableProperties,
+                       dictionaryFieldIDs: opts.dictionaryFieldIDs,
                })
        if err != nil {
                return nil, err
@@ -1021,6 +1039,15 @@ func defaultToScalar(v any, t iceberg.Type, dt 
arrow.DataType) scalar.Scalar {
 
 // defaultToArray creates an Arrow array of length n filled with the given 
default value v.
 func defaultToArray(v any, t iceberg.Type, dt arrow.DataType, n int, alloc 
memory.Allocator) arrow.Array {
+       if dictType, ok := dt.(*arrow.DictionaryType); ok {
+               plain := defaultToArray(v, t, dictType.ValueType, n, alloc)
+               defer plain.Release()
+
+               // defaultToArray has no context parameter, so the context only 
carries alloc.
+               return 
retOrPanic(compute.DictionaryEncodeArray(compute.WithAllocator(context.Background(),
 alloc),
+                       compute.DictionaryEncodeOptions{}, plain))
+       }
+
        sc := defaultToScalar(v, t, dt)
        out, err := scalar.MakeArrayFromScalar(sc, n, alloc)
        if err != nil {
@@ -1048,13 +1075,15 @@ type arrowProjectionVisitor struct {
        useLargeTypes        bool
        useWriteDefault      bool
        allowMissingRequired bool
+       dictionaryFieldIDs   set[int]
 }
 
 func (a *arrowProjectionVisitor) typeToArrowType(t iceberg.Type) 
arrow.DataType {
        return retOrPanic(TypeToArrowTypeWithOptions(t, ArrowSchemaOptions{
-               IncludeFieldIDs: a.includeFieldIDs,
-               UseLargeTypes:   a.useLargeTypes,
-               TableProperties: a.tableProperties,
+               IncludeFieldIDs:    a.includeFieldIDs,
+               UseLargeTypes:      a.useLargeTypes,
+               TableProperties:    a.tableProperties,
+               dictionaryFieldIDs: a.dictionaryFieldIDs,
        }))
 }
 
@@ -1071,6 +1100,14 @@ func (a *arrowProjectionVisitor) castIfNeeded(field 
iceberg.NestedField, vals ar
                return vals
        }
 
+       if _, ok := a.dictionaryFieldIDs[field.ID]; ok {
+               if !field.Type.Equals(typ) {
+                       retOrPanic(iceberg.PromoteType(fileField.Type, 
field.Type))
+               }
+
+               return a.toDictionary(vals, dictionaryArrowType(field.Type))
+       }
+
        if !field.Type.Equals(typ) {
                if !canDowncastTimestampPrecision(fileField.Type, field.Type, 
a.downcastNsTimestamp) {
                        var targetType arrow.DataType
@@ -1169,6 +1206,24 @@ func (a *arrowProjectionVisitor) 
rewrapExtension(targetType arrow.DataType, vals
        return array.NewExtensionArrayWithStorage(tgtExt, storage), true
 }
 
+// Parquet dictionary reads can return plain arrays when the stored Arrow
+// schema gives the column a large type.
+func (a *arrowProjectionVisitor) toDictionary(vals arrow.Array, target 
*arrow.DictionaryType) arrow.Array {
+       if arrow.TypeEqual(vals.DataType(), target) {
+               vals.Retain()
+
+               return vals
+       }
+
+       if !arrow.TypeEqual(vals.DataType(), target.ValueType) {
+               plain := retOrPanic(compute.CastArray(a.ctx, vals, 
compute.SafeCastOptions(target.ValueType)))
+               defer plain.Release()
+               vals = plain
+       }
+
+       return retOrPanic(compute.DictionaryEncodeArray(a.ctx, 
compute.DictionaryEncodeOptions{}, vals))
+}
+
 func canDowncastTimestampPrecision(fileType, readType iceberg.Type, enabled 
bool) bool {
        if !enabled {
                return false
@@ -1274,6 +1329,9 @@ func (a *arrowProjectionVisitor) Struct(st 
iceberg.StructType, structArr arrow.A
                        fields[i] = a.constructField(field, arr.DataType())
                } else {
                        dt := a.typeToArrowType(field.Type)
+                       if _, ok := a.dictionaryFieldIDs[field.ID]; ok {
+                               dt = dictionaryArrowType(field.Type)
+                       }
                        alloc := compute.GetAllocator(a.ctx)
 
                        switch {
@@ -1444,6 +1502,8 @@ type SchemaOptions struct {
        UseWriteDefault      bool
        AllowMissingRequired bool
        TableProperties      iceberg.Properties
+
+       dictionaryFieldIDs set[int]
 }
 
 // ToRequestedSchema will construct a new record batch matching the requested 
iceberg schema
@@ -1476,6 +1536,7 @@ func toRequestedSchema(ctx context.Context, requested, 
fileSchema *iceberg.Schem
                        useLargeTypes:        opts.UseLargeTypes,
                        useWriteDefault:      opts.UseWriteDefault,
                        allowMissingRequired: opts.AllowMissingRequired,
+                       dictionaryFieldIDs:   opts.dictionaryFieldIDs,
                }, arrowAccessor{fileSchema: fileSchema})
        if err != nil {
                return nil, err
diff --git a/table/changelog_normalization.go b/table/changelog_normalization.go
index 344cd114a..ec8851655 100644
--- a/table/changelog_normalization.go
+++ b/table/changelog_normalization.go
@@ -101,6 +101,10 @@ func (s *IncrementalChangelogScan) 
ToNormalizedArrowRecords(ctx context.Context,
        if err != nil {
                return nil, nil, err
        }
+       dictionaryFieldIDs, err := s.scan.dictionaryFieldIDs(requested)
+       if err != nil {
+               return nil, nil, err
+       }
 
        // Reading the complete snapshot prevents a hidden changed column or a 
raw
        // limit/filter from turning an update into a carryover or an unmatched 
row.
@@ -211,7 +215,10 @@ func (s *IncrementalChangelogScan) 
ToNormalizedArrowRecords(ctx context.Context,
                                                return true, nil
                                        }
                                        out, err := 
projectNormalizedChangelog(ctx, rec, outSchema, requested, fullProjection, 
SchemaOptions{
-                                               UseLargeTypes: useLargeTypes, 
FormatVersion: version, TableProperties: props,
+                                               UseLargeTypes:      
useLargeTypes,
+                                               FormatVersion:      version,
+                                               TableProperties:    props,
+                                               dictionaryFieldIDs: 
dictionaryFieldIDs,
                                        })
                                        if err != nil {
                                                return false, err
diff --git a/table/changelog_reader.go b/table/changelog_reader.go
index d8f4838bb..12fdd1093 100644
--- a/table/changelog_reader.go
+++ b/table/changelog_reader.go
@@ -174,6 +174,11 @@ func changelogArrowSchema(scan *Scan) (*arrow.Schema, 
bool, error) {
                return nil, false, err
        }
 
+       dictionaryFieldIDs, err := scan.dictionaryFieldIDs(projected)
+       if err != nil {
+               return nil, false, err
+       }
+
        useLargeTypes, err := 
strconv.ParseBool(scan.options.Get(ScanOptionArrowUseLargeTypes, "false"))
        if err != nil {
                useLargeTypes = false
@@ -189,8 +194,9 @@ func changelogArrowSchema(scan *Scan) (*arrow.Schema, bool, 
error) {
        }
 
        dataSchema, err := SchemaToArrowSchemaWithOptions(projected, 
ArrowSchemaOptions{
-               UseLargeTypes:   useLargeTypes,
-               TableProperties: props,
+               UseLargeTypes:      useLargeTypes,
+               TableProperties:    props,
+               dictionaryFieldIDs: dictionaryFieldIDs,
        })
        if err != nil {
                return nil, false, err
diff --git a/table/internal/interfaces.go b/table/internal/interfaces.go
index 0a804ccfd..7bdf67472 100644
--- a/table/internal/interfaces.go
+++ b/table/internal/interfaces.go
@@ -75,6 +75,15 @@ type FileReader interface {
        ReadTable(context.Context) (arrow.Table, error)
 }
 
+// DictionaryReader is a FileReader that can return selected string and binary
+// leaf columns as Arrow dictionaries.
+type DictionaryReader interface {
+       // ReadDictionaries requests dictionary reads for the leaves with the 
given
+       // field IDs. Call it before PrunedSchema or GetRecords. Readers may 
still
+       // return plain arrays when a file's stored Arrow schema requires them.
+       ReadDictionaries(fieldIDs map[int]struct{}, mapping 
iceberg.NameMapping) error
+}
+
 // FileWriter is an incremental single-file writer with open/write/close
 // lifecycle. It writes Arrow record batches and tracks bytes written for
 // rolling file decisions.
diff --git a/table/internal/parquet_files.go b/table/internal/parquet_files.go
index a88730b49..95ccc7c73 100644
--- a/table/internal/parquet_files.go
+++ b/table/internal/parquet_files.go
@@ -2314,6 +2314,71 @@ func (w wrapPqArrowReader) PrunedSchema(projectedIDs 
map[int]struct{}, mapping i
        return pruneParquetColumns(w.Manifest, projectedIDs, false, mapping)
 }
 
+// ReadDictionaries rebuilds the schema manifest because pqarrow decides
+// dictionary reads when it builds the manifest, not when it reads. The value
+// receiver is safe: the writes go through the embedded *pqarrow.FileReader.
+func (w wrapPqArrowReader) ReadDictionaries(fieldIDs map[int]struct{}, mapping 
iceberg.NameMapping) error {
+       leaves := &dictionaryLeafVisitor{fieldIDs: fieldIDs}
+       if _, err := visitParquetManifest(w.Manifest, leaves, 
&iceberg.MappedField{Fields: mapping}); err != nil {
+               return err
+       }
+       if len(leaves.colIndices) == 0 {
+               return nil
+       }
+
+       props := w.Props
+       for _, idx := range leaves.colIndices {
+               props.SetReadDict(idx, true)
+       }
+       meta := w.ParquetReader().MetaData()
+       manifest, err := pqarrow.NewSchemaManifest(meta.Schema, 
meta.KeyValueMetadata(), &props)
+       if err != nil {
+               return err
+       }
+       w.Props, w.Manifest = props, manifest
+
+       return nil
+}
+
+type dictionaryLeafVisitor struct {
+       fieldIDs   map[int]struct{}
+       colIndices []int
+}
+
+func (*dictionaryLeafVisitor) Manifest(*pqarrow.SchemaManifest, []struct{}, 
*iceberg.MappedField) struct{} {
+       return struct{}{}
+}
+
+func (*dictionaryLeafVisitor) Field(pqarrow.SchemaField, struct{}, 
*iceberg.MappedField) struct{} {
+       return struct{}{}
+}
+
+func (*dictionaryLeafVisitor) Struct(pqarrow.SchemaField, []struct{}, 
*iceberg.MappedField) struct{} {
+       return struct{}{}
+}
+
+func (*dictionaryLeafVisitor) List(pqarrow.SchemaField, struct{}, 
*iceberg.MappedField) struct{} {
+       return struct{}{}
+}
+
+func (*dictionaryLeafVisitor) Map(pqarrow.SchemaField, struct{}, struct{}, 
*iceberg.MappedField) struct{} {
+       return struct{}{}
+}
+
+func (v *dictionaryLeafVisitor) Primitive(field pqarrow.SchemaField, mapping 
*iceberg.MappedField) struct{} {
+       id := getFieldID(*field.Field)
+       if id == nil && mapping != nil {
+               id = mapping.FieldID
+       }
+       if id != nil {
+               if _, ok := v.fieldIDs[*id]; ok {
+                       v.colIndices = append(v.colIndices, field.ColIndex)
+               }
+       }
+
+       return struct{}{}
+}
+
 // parquetRowGroupSplitOffset returns the same first-page offset used when
 // DataFileStatistics.SplitOffsets is built. RowGroup.file_offset is optional
 // in Parquet and Arrow returns zero when it is absent, so relying on it can
diff --git a/table/scan_dictionary_columns_test.go 
b/table/scan_dictionary_columns_test.go
new file mode 100644
index 000000000..f38dad145
--- /dev/null
+++ b/table/scan_dictionary_columns_test.go
@@ -0,0 +1,665 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package table_test
+
+import (
+       "context"
+       "os"
+       "path/filepath"
+       "slices"
+       "strconv"
+       "strings"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/compute"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/arrow-go/v18/parquet"
+       "github.com/apache/arrow-go/v18/parquet/compress"
+       "github.com/apache/arrow-go/v18/parquet/pqarrow"
+       "github.com/apache/iceberg-go"
+       iceio "github.com/apache/iceberg-go/io"
+       "github.com/apache/iceberg-go/table"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+var (
+       dictUTF8   = &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.String}
+       dictBinary = &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int32, ValueType: arrow.BinaryTypes.Binary}
+)
+
+func newDictionaryColumnsTable(t *testing.T, schema *iceberg.Schema, props 
iceberg.Properties) *table.Table {
+       t.Helper()
+
+       location := filepath.ToSlash(t.TempDir())
+       meta, err := table.NewMetadata(schema, iceberg.UnpartitionedSpec, 
table.UnsortedSortOrder, location, props)
+       require.NoError(t, err)
+
+       metaLoc := location + "/metadata/v1.metadata.json"
+       fsF := func(context.Context) (iceio.IO, error) { return 
iceio.LocalFS{}, nil }
+
+       return table.New(table.Identifier{"db", "dictionary_columns"}, meta, 
metaLoc, fsF,
+               &concurrentTestCatalog{metadata: meta, location: metaLoc, fsF: 
fsF})
+}
+
+// addDictionaryColumnsFile writes rows to a Parquet file with the given Arrow
+// schema and writer settings and adds it to tbl without rewriting it.
+func addDictionaryColumnsFile(t *testing.T, tbl *table.Table, name string, sc 
*arrow.Schema, rows string,
+       props []parquet.WriterProperty, arrowProps ...pqarrow.WriterOption,
+) *table.Table {
+       t.Helper()
+
+       rec, _, err := array.RecordFromJSON(memory.DefaultAllocator, sc, 
strings.NewReader(rows))
+       require.NoError(t, err)
+       defer rec.Release()
+
+       path := tbl.Location() + "/data/" + name + ".parquet"
+       require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755))
+       f, err := os.Create(path)
+       require.NoError(t, err)
+       w, err := pqarrow.NewFileWriter(sc, f, 
parquet.NewWriterProperties(props...),
+               pqarrow.NewArrowWriterProperties(arrowProps...))
+       require.NoError(t, err)
+       require.NoError(t, w.Write(rec))
+       require.NoError(t, w.Close())
+
+       tx := tbl.NewTransaction()
+       require.NoError(t, tx.AddDataFilesByPath(t.Context(), []string{path}, 
nil, false))
+       tbl, err = tx.Commit(t.Context())
+       require.NoError(t, err)
+
+       return tbl
+}
+
+func fieldWithID(name string, id int, typ arrow.DataType) arrow.Field {
+       return arrow.Field{
+               Name: name, Type: typ, Nullable: true,
+               Metadata: 
arrow.NewMetadata([]string{table.ArrowParquetFieldIDKey}, 
[]string{strconv.Itoa(id)}),
+       }
+}
+
+// rowValue returns the value at row i, decoding dictionaries and
+// rendering binary as string so expectations can be literals.
+func rowValue(t *testing.T, col arrow.Array, i int) any {
+       t.Helper()
+
+       if col.IsNull(i) {
+               return nil
+       }
+       switch c := col.(type) {
+       case *array.Int64:
+               return c.Value(i)
+       case *array.Dictionary:
+               return rowValue(t, c.Dictionary(), c.GetValueIndex(i))
+       case *array.String:
+               return c.Value(i)
+       case *array.Binary:
+               return string(c.Value(i))
+       case *array.Struct:
+               return rowValue(t, c.Field(0), i)
+       }
+       t.Fatalf("unexpected column type %s", col.DataType())
+
+       return nil
+}
+
+func tableRows(t *testing.T, tbl arrow.Table) [][]any {
+       t.Helper()
+
+       var rows [][]any
+       rdr := array.NewTableReader(tbl, -1)
+       defer rdr.Release()
+       for rdr.Next() {
+               rec := rdr.RecordBatch()
+               for i := range int(rec.NumRows()) {
+                       row := make([]any, rec.NumCols())
+                       for j, col := range rec.Columns() {
+                               row[j] = rowValue(t, col, i)
+                       }
+                       rows = append(rows, row)
+               }
+       }
+
+       return rows
+}
+
+func TestWithDictionaryColumnsReturnsDictionaries(t *testing.T) {
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+               iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String, InitialDefault: "z"},
+               iceberg.NestedField{ID: 3, Name: "b", Type: 
iceberg.PrimitiveTypes.Binary},
+       )
+       tbl := newDictionaryColumnsTable(t, schema, 
iceberg.Properties{table.PropertyFormatVersion: "3"})
+
+       id := arrow.Field{
+               Name: "id", Type: arrow.PrimitiveTypes.Int64,
+               Metadata: 
arrow.NewMetadata([]string{table.ArrowParquetFieldIDKey}, []string{"1"}),
+       }
+       fileSchema := func(str, bin arrow.DataType) *arrow.Schema {
+               return arrow.NewSchema([]arrow.Field{id, fieldWithID("s", 2, 
str), fieldWithID("b", 3, bin)}, nil)
+       }
+       plain := fileSchema(arrow.BinaryTypes.String, arrow.BinaryTypes.Binary)
+
+       // b holds base64 in JSON: eA== x, eQ== y, dw== w, dg== v, dQ== u, dA== 
t.
+       // Compression turns off the writer's cost-based fallback to plain 
pages, so
+       // files written with it keep their dictionary pages.
+       tbl = addDictionaryColumnsFile(t, tbl, "dictionary-pages", plain,
+               
`[{"id":1,"s":"a","b":null},{"id":2,"s":"b","b":"eQ=="},{"id":3,"s":"a","b":"eA=="}]`,
+               []parquet.WriterProperty{parquet.WithMaxRowGroupLength(2), 
parquet.WithCompression(compress.Codecs.Snappy)})
+       tbl = addDictionaryColumnsFile(t, tbl, "plain-pages", plain,
+               `[{"id":4,"s":"c","b":"dw=="}]`,
+               []parquet.WriterProperty{parquet.WithDictionaryDefault(false)})
+       tbl = addDictionaryColumnsFile(t, tbl, "dictionary-fallback", plain,
+               `[{"id":5,"s":null,"b":"dg=="},{"id":6,"s":"e","b":"dQ=="}]`,
+               // One dictionary-encoded page, then plain pages once the 
dictionary
+               // outgrows its limit.
+               []parquet.WriterProperty{
+                       parquet.WithCompression(compress.Codecs.Snappy), 
parquet.WithDictionaryPageSizeLimit(6),
+                       parquet.WithDataPageSize(1), parquet.WithBatchSize(1),
+               })
+       tbl = addDictionaryColumnsFile(t, tbl, "stored-large-types",
+               fileSchema(arrow.BinaryTypes.LargeString, 
arrow.BinaryTypes.LargeBinary),
+               `[{"id":7,"s":"a","b":"eA=="}]`, nil, pqarrow.WithStoreSchema())
+       tbl = addDictionaryColumnsFile(t, tbl, "stored-ordered-int8-dictionary",
+               fileSchema(
+                       &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.String, Ordered: true},
+                       &arrow.DictionaryType{IndexType: 
arrow.PrimitiveTypes.Int8, ValueType: arrow.BinaryTypes.Binary, Ordered: true}),
+               `[{"id":8,"s":"f","b":"dA=="}]`, nil, pqarrow.WithStoreSchema())
+       tbl = addDictionaryColumnsFile(t, tbl, "missing-columns", 
arrow.NewSchema([]arrow.Field{id}, nil),
+               `[{"id":9}]`, nil)
+
+       // Columns added after the files were written: every file lacks the
+       // parents of the requested nested leaves.
+       tx := tbl.NewTransaction()
+       require.NoError(t, tx.UpdateSchema(true, false).
+               AddColumn([]string{"st"}, &iceberg.StructType{FieldList: 
[]iceberg.NestedField{
+                       {ID: 1, Name: "x", Type: iceberg.PrimitiveTypes.String},
+               }}, "", false, nil).
+               AddColumn([]string{"l"}, &iceberg.ListType{ElementID: 1, 
Element: iceberg.PrimitiveTypes.String}, "", false, nil).
+               AddColumn([]string{"m"}, &iceberg.MapType{
+                       KeyID: 1, KeyType: iceberg.PrimitiveTypes.String, 
ValueID: 2, ValueType: iceberg.PrimitiveTypes.String,
+               }, "", false, nil).
+               Commit())
+       tbl, err := tx.Commit(t.Context())
+       require.NoError(t, err)
+
+       for _, largeTypes := range []string{"false", "true"} {
+               t.Run("use_large_types="+largeTypes, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+                       ctx := compute.WithAllocator(t.Context(), mem)
+
+                       arrTbl, err := tbl.Scan(
+                               table.WithDictionaryColumns("s", "b", "st.x", 
"l.element", "m.key", "m.value"),
+                               
table.WithOptions(iceberg.Properties{table.ScanOptionArrowUseLargeTypes: 
largeTypes}),
+                       ).ToArrowTable(ctx)
+                       require.NoError(t, err)
+                       defer arrTbl.Release()
+
+                       list := "list"
+                       if largeTypes == "true" {
+                               list = "large_list"
+                       }
+                       assert.Equal(t, []string{
+                               "int64",
+                               "dictionary<values=utf8, indices=int32, 
ordered=false>",
+                               "dictionary<values=binary, indices=int32, 
ordered=false>",
+                               "struct<x: dictionary<values=utf8, 
indices=int32, ordered=false> nullable>",
+                               list + "<element: dictionary<values=utf8, 
indices=int32, ordered=false>, nullable>",
+                               "map<dictionary<values=utf8, indices=int32, 
ordered=false>, dictionary<values=utf8, indices=int32, ordered=false>, 
items_nullable>",
+                       }, arrowTypeStrings(arrTbl.Schema()))
+
+                       rows := tableRows(t, arrTbl)
+                       slices.SortFunc(rows, func(a, b []any) int { return 
int(a[0].(int64) - b[0].(int64)) })
+                       assert.Equal(t, [][]any{
+                               {int64(1), "a", nil, nil, nil, nil},
+                               {int64(2), "b", "y", nil, nil, nil},
+                               {int64(3), "a", "x", nil, nil, nil},
+                               {int64(4), "c", "w", nil, nil, nil},
+                               {int64(5), nil, "v", nil, nil, nil},
+                               {int64(6), "e", "u", nil, nil, nil},
+                               {int64(7), "a", "x", nil, nil, nil},
+                               {int64(8), "f", "t", nil, nil, nil},
+                               {int64(9), "z", nil, nil, nil, nil},
+                       }, rows)
+               })
+       }
+
+       t.Run("incompatible file type", func(t *testing.T) {
+               path := tbl.Location() + "/data/int32-s.parquet"
+               writeParquetFile(t, path,
+                       arrow.NewSchema([]arrow.Field{id, fieldWithID("s", 2, 
arrow.PrimitiveTypes.Int32)}, nil), `[{"id":10,"s":1}]`)
+               info, err := os.Stat(path)
+               require.NoError(t, err)
+               df, err := 
iceberg.NewDataFileBuilder(*iceberg.UnpartitionedSpec, iceberg.EntryContentData,
+                       path, iceberg.ParquetFile, nil, nil, nil, 1, 
info.Size())
+               require.NoError(t, err)
+
+               _, records, err := tbl.Scan(table.WithDictionaryColumns("s")).
+                       ReadTasks(t.Context(), []table.FileScanTask{{File: 
df.Build()}})
+               require.NoError(t, err)
+               var rec arrow.RecordBatch
+               for rec, err = range records {
+                       if err != nil {
+                               break
+                       }
+                       rec.Release()
+               }
+               require.ErrorIs(t, err, iceberg.ErrResolve)
+       })
+}
+
+func arrowTypeStrings(sc *arrow.Schema) []string {
+       types := make([]string, sc.NumFields())
+       for i, f := range sc.Fields() {
+               types[i] = f.Type.String()
+       }
+
+       return types
+}
+
+// Re-encoding a decoded batch gives a dictionary of only that batch's values,
+// while a Parquet dictionary read accumulates the row group's dictionary
+// across batches, so dictionary lengths show which path produced a batch.
+func TestWithDictionaryColumnsReadsParquetDictionaries(t *testing.T) {
+       dictionaryLengths := func(t *testing.T, scan *table.Scan) []int {
+               t.Helper()
+
+               _, records, err := scan.ToArrowRecords(t.Context())
+               require.NoError(t, err)
+               var lengths []int
+               var walk func(col arrow.Array)
+               walk = func(col arrow.Array) {
+                       switch c := col.(type) {
+                       case *array.Dictionary:
+                               lengths = append(lengths, c.Dictionary().Len())
+                       case *array.Struct:
+                               walk(c.Field(0))
+                       case *array.Map:
+                               walk(c.Keys())
+                               walk(c.Items())
+                       case *array.List:
+                               walk(c.ListValues())
+                       default:
+                               t.Fatalf("unexpected column type %s", 
col.DataType())
+                       }
+               }
+               for rec, err := range records {
+                       require.NoError(t, err)
+                       for _, col := range rec.Columns()[1:] {
+                               walk(col)
+                       }
+                       rec.Release()
+               }
+
+               return lengths
+       }
+
+       t.Run("split tasks", func(t *testing.T) {
+               schema := iceberg.NewSchema(0,
+                       iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+                       iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String},
+                       iceberg.NestedField{ID: 3, Name: "st", Type: 
&iceberg.StructType{FieldList: []iceberg.NestedField{
+                               {ID: 5, Name: "x", Type: 
iceberg.PrimitiveTypes.String},
+                       }}},
+                       iceberg.NestedField{ID: 4, Name: "l", Type: 
&iceberg.ListType{ElementID: 6, Element: iceberg.PrimitiveTypes.String}},
+                       iceberg.NestedField{ID: 7, Name: "m", Type: 
&iceberg.MapType{
+                               KeyID: 8, KeyType: 
iceberg.PrimitiveTypes.String, ValueID: 9, ValueType: 
iceberg.PrimitiveTypes.String,
+                       }},
+               )
+               tbl := newDictionaryColumnsTable(t, schema, iceberg.Properties{
+                       table.ParquetRowGroupLimitKey: "2",
+                       table.ReadSplitTargetSizeKey:  "1",
+               })
+               tbl = appendRows(t, tbl, `[
+                       
{"id":1,"s":"a","st":{"x":"a"},"l":["a"],"m":[{"key":"a","value":"a"}]},
+                       
{"id":2,"s":"b","st":{"x":"b"},"l":["b"],"m":[{"key":"b","value":"b"}]},
+                       
{"id":3,"s":"c","st":{"x":"c"},"l":["c"],"m":[{"key":"c","value":"c"}]},
+                       
{"id":4,"s":"d","st":{"x":"d"},"l":["d"],"m":[{"key":"d","value":"d"}]}]`)
+
+               scan := tbl.Scan(table.WithDictionaryColumns("s", "st.x", 
"l.element", "m.key", "m.value"),
+                       table.WithArrowBatchSize(1))
+               tasks, err := scan.PlanFiles(t.Context())
+               require.NoError(t, err)
+               require.Len(t, tasks, 2)
+               require.Equal(t, tasks[0].File.FilePath(), 
tasks[1].File.FilePath())
+
+               assert.Equal(t, []int{1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 
1, 2, 2, 2, 2, 2}, dictionaryLengths(t, scan))
+       })
+
+       t.Run("name mapping", func(t *testing.T) {
+               schema := iceberg.NewSchema(0,
+                       iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+                       iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String},
+               )
+               tbl := newDictionaryColumnsTable(t, schema, 
nameMappingProperties(t, schema.NameMapping()))
+               tbl = addDictionaryColumnsFile(t, tbl, "without-field-ids", 
arrow.NewSchema([]arrow.Field{
+                       {Name: "id", Type: arrow.PrimitiveTypes.Int64},
+                       {Name: "s", Type: arrow.BinaryTypes.String, Nullable: 
true},
+               }, nil), `[{"id":1,"s":"a"},{"id":2,"s":"b"}]`, nil)
+
+               scan := tbl.Scan(table.WithDictionaryColumns("s"), 
table.WithArrowBatchSize(1))
+               assert.Equal(t, []int{1, 2}, dictionaryLengths(t, scan))
+       })
+}
+
+func TestWithDictionaryColumnsValidation(t *testing.T) {
+       // The table has no snapshot, so these scans have no tasks.
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+               iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String},
+               iceberg.NestedField{ID: 3, Name: "u", Type: 
iceberg.PrimitiveTypes.UUID},
+               iceberg.NestedField{ID: 4, Name: "f", Type: 
iceberg.MustFixedTypeOf(4)},
+               iceberg.NestedField{ID: 5, Name: "g", Type: 
iceberg.GeometryType{}},
+       )
+       tbl := newDictionaryColumnsTable(t, schema, 
iceberg.Properties{table.PropertyFormatVersion: "3"})
+
+       for _, tc := range []struct {
+               name string
+               opts []table.ScanOption
+               err  error
+       }{
+               {"unknown column", 
[]table.ScanOption{table.WithDictionaryColumns("missing")}, 
iceberg.ErrInvalidSchema},
+               {"case sensitive", 
[]table.ScanOption{table.WithDictionaryColumns("S")}, iceberg.ErrInvalidSchema},
+               {"uuid", []table.ScanOption{table.WithDictionaryColumns("u")}, 
iceberg.ErrInvalidArgument},
+               {"fixed", []table.ScanOption{table.WithDictionaryColumns("f")}, 
iceberg.ErrInvalidArgument},
+               {"geometry", 
[]table.ScanOption{table.WithDictionaryColumns("g")}, 
iceberg.ErrInvalidArgument},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       _, _, err := 
tbl.Scan(tc.opts...).ToArrowRecords(t.Context())
+                       require.ErrorIs(t, err, tc.err)
+               })
+       }
+
+       for _, tc := range []struct {
+               name   string
+               opts   []table.ScanOption
+               fields []arrow.Field
+       }{
+               {"case insensitive", []table.ScanOption{
+                       table.WithSelectedFields("id", "s"), 
table.WithCaseSensitive(false), table.WithDictionaryColumns("S"),
+               }, []arrow.Field{
+                       {Name: "id", Type: arrow.PrimitiveTypes.Int64},
+                       {Name: "s", Type: dictUTF8, Nullable: true},
+               }},
+               {"unprojected column", []table.ScanOption{
+                       table.WithSelectedFields("id"), 
table.WithDictionaryColumns("s"),
+               }, []arrow.Field{
+                       {Name: "id", Type: arrow.PrimitiveTypes.Int64},
+               }},
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       sc, records, err := 
tbl.Scan(tc.opts...).ToArrowRecords(t.Context())
+                       require.NoError(t, err)
+                       for _, err := range records {
+                               require.NoError(t, err)
+                       }
+                       assert.True(t, arrow.NewSchema(tc.fields, 
nil).Equal(sc), sc.String())
+               })
+       }
+
+       t.Run("renamed column with time travel", func(t *testing.T) {
+               tbl := newDictionaryColumnsTable(t, iceberg.NewSchema(0,
+                       iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+                       iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String},
+               ), nil)
+               tbl = appendRows(t, tbl, `[{"id":1,"s":"a"}]`)
+               before := tbl.CurrentSnapshot().SnapshotID
+               tx := tbl.NewTransaction()
+               require.NoError(t, tx.UpdateSchema(true, 
false).RenameColumn([]string{"s"}, "renamed").Commit())
+               tbl, err := tx.Commit(t.Context())
+               require.NoError(t, err)
+
+               mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+               defer mem.AssertSize(t, 0)
+               ctx := compute.WithAllocator(t.Context(), mem)
+               sc, records, err := tbl.Scan(table.WithSnapshotID(before), 
table.WithDictionaryColumns("s")).ToArrowRecords(ctx)
+               require.NoError(t, err)
+               for rec, err := range records {
+                       require.NoError(t, err)
+                       rec.Release()
+               }
+               assert.Equal(t, []string{"int64", "dictionary<values=utf8, 
indices=int32, ordered=false>"}, arrowTypeStrings(sc))
+
+               _, _, err = tbl.Scan(table.WithSnapshotID(before), 
table.WithDictionaryColumns("renamed")).ToArrowRecords(t.Context())
+               require.ErrorIs(t, err, iceberg.ErrInvalidSchema)
+       })
+}
+
+func TestWithDictionaryColumnsDeletes(t *testing.T) {
+       st := iceberg.NestedField{ID: 4, Name: "st", Type: 
&iceberg.StructType{FieldList: []iceberg.NestedField{
+               {ID: 5, Name: "x", Type: iceberg.PrimitiveTypes.String},
+       }}}
+       s := iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String}
+       b := iceberg.NestedField{ID: 3, Name: "b", Type: 
iceberg.PrimitiveTypes.Binary}
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true}, s, b, st)
+       tbl := newDictionaryColumnsTable(t, schema, iceberg.Properties{
+               table.PropertyFormatVersion: "2",
+               table.WriteDeleteModeKey:    table.WriteModeMergeOnRead,
+       })
+       // b holds base64 in JSON: eA== x, eQ== y, eg== z.
+       tbl = appendRows(t, tbl, `[
+               {"id":1,"s":"a","b":"eA==","st":{"x":"p"}},
+               {"id":2,"s":"b","b":"eQ==","st":{"x":"p"}},
+               {"id":3,"s":"a","b":"eQ==","st":{"x":"p"}},
+               {"id":4,"s":"c","b":"eA==","st":{"x":"p"}},
+               {"id":5,"s":"b","b":"eA==","st":{"x":"p"}},
+               {"id":6,"s":"d","b":"eg==","st":{"x":"q"}},
+               {"id":7,"s":"a","b":"eg==","st":{"x":"p"}}]`)
+
+       tbl, err := tbl.Delete(t.Context(), 
iceberg.EqualTo(iceberg.Reference("id"), int64(1)), nil)
+       require.NoError(t, err)
+       for _, key := range []struct {
+               id    int
+               field iceberg.NestedField
+               rows  string
+       }{
+               {2, s, `[{"s":"b"}]`},
+               {3, b, `[{"b":"eQ=="}]`},
+               {5, st, `[{"st":{"x":"q"}}]`},
+       } {
+               sc, err := table.SchemaToArrowSchema(iceberg.NewSchema(0, 
key.field), nil, true, false)
+               require.NoError(t, err)
+               records, release := makeEqDeleteRecords(t, sc, key.rows)
+               tx := tbl.NewTransaction()
+               require.NoError(t, tx.CommitEqualityDeletes(t.Context(), 
[]int{key.id}, records, nil))
+               tbl, err = tx.Commit(t.Context())
+               require.NoError(t, err)
+               release()
+       }
+
+       arrTbl, err := tbl.Scan(
+               table.WithDictionaryColumns("s", "b", "st.x"),
+       ).ToArrowTable(t.Context())
+       require.NoError(t, err)
+       defer arrTbl.Release()
+
+       assert.Equal(t, [][]any{{int64(4), "c", "x", "p"}, {int64(7), "a", "z", 
"p"}}, tableRows(t, arrTbl))
+}
+
+func TestWithDictionaryColumnsChangelog(t *testing.T) {
+       ctx := t.Context()
+       tbl := newChangelogMORTable(t, 2)
+       tbl = appendChangelogRows(t, ctx, tbl)
+       tbl = deleteChangelogID(t, ctx, tbl, 2)
+
+       sc, records, err := 
tbl.NewIncrementalChangelogScan(table.WithDictionaryColumns("data")).ToArrowRecords(ctx)
+       require.NoError(t, err)
+       assert.True(t, arrow.TypeEqual(dictUTF8, sc.Field(1).Type), 
sc.Field(1).Type.String())
+
+       var rows [][]any
+       for rec, err := range records {
+               require.NoError(t, err)
+               require.True(t, sc.Equal(rec.Schema()), rec.Schema().String())
+               for i := range int(rec.NumRows()) {
+                       rows = append(rows, []any{
+                               rowValue(t, rec.Column(0), i), rowValue(t, 
rec.Column(1), i), rec.Column(2).ValueStr(i),
+                       })
+               }
+               rec.Release()
+       }
+       assert.ElementsMatch(t, [][]any{
+               {int64(1), "a", "INSERT"},
+               {int64(2), "b", "INSERT"},
+               {int64(3), "c", "INSERT"},
+               {int64(2), "b", "DELETE"},
+       }, rows)
+
+       t.Run("normalized", func(t *testing.T) {
+               normTbl, start := normalizationTable(t, 2)
+               for _, largeTypes := range []string{"false", "true"} {
+                       t.Run("use_large_types="+largeTypes, func(t *testing.T) 
{
+                               mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                               defer mem.AssertSize(t, 0)
+                               ctx := compute.WithAllocator(t.Context(), mem)
+
+                               sc, records, err := 
normTbl.NewIncrementalChangelogScan(
+                                       table.WithDictionaryColumns("data"),
+                                       
table.WithOptions(iceberg.Properties{table.ScanOptionArrowUseLargeTypes: 
largeTypes}),
+                               
).FromSnapshotExclusive(start).ToNormalizedArrowRecords(ctx, 
table.ChangelogNormalizationOptions{
+                                       ComputeUpdates: true,
+                               })
+                               require.NoError(t, err)
+                               assert.True(t, arrow.TypeEqual(dictUTF8, 
sc.Field(1).Type), sc.Field(1).Type.String())
+
+                               var got [][]any
+                               for rec, err := range records {
+                                       require.NoError(t, err)
+                                       require.True(t, sc.Equal(rec.Schema()), 
rec.Schema().String())
+                                       assert.True(t, 
arrow.TypeEqual(dictUTF8, rec.Column(1).DataType()), 
rec.Column(1).DataType().String())
+                                       for i := range int(rec.NumRows()) {
+                                               got = append(got, []any{
+                                                       rowValue(t, 
rec.Column(0), i),
+                                                       rowValue(t, 
rec.Column(1), i),
+                                                       
rec.Column(2).ValueStr(i),
+                                               })
+                                       }
+                                       rec.Release()
+                               }
+                               assert.Equal(t, [][]any{
+                                       {int64(2), "old", 
string(table.ChangelogOpUpdateBefore)},
+                                       {int64(2), "new", 
string(table.ChangelogOpUpdateAfter)},
+                                       {int64(3), "removed", 
string(table.ChangelogOpDelete)},
+                                       {int64(4), "added", 
string(table.ChangelogOpInsert)},
+                               }, got)
+                       })
+               }
+       })
+}
+
+func TestWithDictionaryColumnsRowFilters(t *testing.T) {
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int64, Required: true},
+               iceberg.NestedField{ID: 2, Name: "s", Type: 
iceberg.PrimitiveTypes.String},
+               iceberg.NestedField{ID: 3, Name: "b", Type: 
iceberg.PrimitiveTypes.Binary},
+               iceberg.NestedField{ID: 4, Name: "st", Type: 
&iceberg.StructType{FieldList: []iceberg.NestedField{
+                       {ID: 5, Name: "x", Type: iceberg.PrimitiveTypes.String},
+               }}},
+       )
+       tbl := newDictionaryColumnsTable(t, schema, nil)
+       // b holds base64 in JSON: eA== x, eQ== y.
+       tbl = appendRows(t, tbl, `[
+               {"id":1,"s":"alpha","b":"eA==","st":{"x":"p"}},
+               {"id":2,"s":"alpine","b":"eQ==","st":{"x":"q"}},
+               {"id":3,"s":"beta","b":"eA==","st":{"x":"p"}},
+               {"id":4,"s":null,"b":null,"st":{"x":"q"}}]`)
+
+       wantTypes := []string{
+               "int64",
+               "dictionary<values=utf8, indices=int32, ordered=false>",
+               "dictionary<values=binary, indices=int32, ordered=false>",
+               "struct<x: dictionary<values=utf8, indices=int32, 
ordered=false> nullable>",
+       }
+
+       for _, tc := range []struct {
+               name   string
+               filter iceberg.BooleanExpression
+               want   [][]any
+       }{
+               {
+                       name:   "string equal",
+                       filter: iceberg.EqualTo(iceberg.Reference("s"), 
"alpha"),
+                       want:   [][]any{{int64(1), "alpha", "x", "p"}},
+               },
+               {
+                       name:   "string in",
+                       filter: iceberg.IsIn(iceberg.Reference("s"), "alpha", 
"beta"),
+                       want: [][]any{
+                               {int64(1), "alpha", "x", "p"},
+                               {int64(3), "beta", "x", "p"},
+                       },
+               },
+               {
+                       name:   "string starts_with",
+                       filter: iceberg.StartsWith(iceberg.Reference("s"), 
"alp"),
+                       want: [][]any{
+                               {int64(1), "alpha", "x", "p"},
+                               {int64(2), "alpine", "y", "q"},
+                       },
+               },
+               {
+                       name:   "string is_null",
+                       filter: iceberg.IsNull(iceberg.Reference("s")),
+                       want:   [][]any{{int64(4), nil, nil, "q"}},
+               },
+               {
+                       name:   "string not_null",
+                       filter: iceberg.NotNull(iceberg.Reference("s")),
+                       want: [][]any{
+                               {int64(1), "alpha", "x", "p"},
+                               {int64(2), "alpine", "y", "q"},
+                               {int64(3), "beta", "x", "p"},
+                       },
+               },
+               {
+                       name:   "binary equal",
+                       filter: iceberg.EqualTo(iceberg.Reference("b"), 
[]byte("x")),
+                       want: [][]any{
+                               {int64(1), "alpha", "x", "p"},
+                               {int64(3), "beta", "x", "p"},
+                       },
+               },
+               {
+                       name:   "nested struct string equal",
+                       filter: iceberg.EqualTo(iceberg.Reference("st.x"), "q"),
+                       want: [][]any{
+                               {int64(2), "alpine", "y", "q"},
+                               {int64(4), nil, nil, "q"},
+                       },
+               },
+       } {
+               t.Run(tc.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+                       ctx := compute.WithAllocator(t.Context(), mem)
+
+                       arrTbl, err := tbl.Scan(
+                               table.WithDictionaryColumns("s", "b", "st.x"),
+                               table.WithRowFilter(tc.filter),
+                       ).ToArrowTable(ctx)
+                       require.NoError(t, err)
+                       defer arrTbl.Release()
+
+                       assert.Equal(t, wantTypes, 
arrowTypeStrings(arrTbl.Schema()))
+                       assert.Equal(t, tc.want, tableRows(t, arrTbl))
+               })
+       }
+}
diff --git a/table/scanner.go b/table/scanner.go
index d41aaf9f8..b5acc8532 100644
--- a/table/scanner.go
+++ b/table/scanner.go
@@ -572,6 +572,10 @@ type Scan struct {
        // map cannot silently drop it.
        arrowBatchSize int
 
+       // dictionaryColumns holds the names given to WithDictionaryColumns,
+       // resolved to field IDs only when the scan reads.
+       dictionaryColumns []string
+
        // readRecords is a scan-local reader seam; nil uses 
(*arrowScan).GetRecords.
        // Tests can wrap it to observe the task slice handed to the Arrow 
reader.
        readRecords func(*arrowScan, context.Context, []FileScanTask) 
(*arrow.Schema, iter.Seq2[arrow.RecordBatch, error], error)
@@ -749,6 +753,46 @@ func (scan *Scan) Projection() (*iceberg.Schema, error) {
        return schema, nil
 }
 
+func (scan *Scan) dictionaryFieldIDs(projected *iceberg.Schema) (set[int], 
error) {
+       if len(scan.dictionaryColumns) == 0 {
+               return nil, nil
+       }
+
+       schema, err := scan.effectiveSchema()
+       if err != nil {
+               return nil, err
+       }
+
+       ids := make(set[int], len(scan.dictionaryColumns))
+       for _, name := range scan.dictionaryColumns {
+               var (
+                       field iceberg.NestedField
+                       ok    bool
+               )
+               if scan.caseSensitive {
+                       field, ok = schema.FindFieldByName(name)
+               } else {
+                       field, ok = schema.FindFieldByNameCaseInsensitive(name)
+               }
+               if !ok {
+                       return nil, fmt.Errorf("%w: could not find dictionary 
column %s", iceberg.ErrInvalidSchema, name)
+               }
+
+               switch field.Type.(type) {
+               case iceberg.StringType, iceberg.BinaryType:
+               default:
+                       return nil, fmt.Errorf("%w: dictionary column %s has 
type %s, only string and binary columns can be read as dictionaries",
+                               iceberg.ErrInvalidArgument, name, field.Type)
+               }
+
+               if _, ok := projected.FindFieldByID(field.ID); ok {
+                       ids[field.ID] = struct{}{}
+               }
+       }
+
+       return ids, nil
+}
+
 func (scan *Scan) effectiveSchema() (*iceberg.Schema, error) {
        if scan.selectorErr != nil {
                return nil, scan.selectorErr
@@ -2379,6 +2423,11 @@ func (scan *Scan) arrowScanForTasks(ctx context.Context, 
tasks []FileScanTask) (
                return nil, nil, nil, err
        }
 
+       dictionaryFieldIDs, err := scan.dictionaryFieldIDs(schema)
+       if err != nil {
+               return nil, nil, nil, err
+       }
+
        // Bind task residuals against the schema selected by this scan, which 
may
        // be an older snapshot schema rather than the table's current schema.
        readTasks, err = bindReadTasksResiduals(effectiveSchema, tasks, 
scan.caseSensitive)
@@ -2416,6 +2465,7 @@ func (scan *Scan) arrowScanForTasks(ctx context.Context, 
tasks []FileScanTask) (
                options:            scan.options,
                concurrency:        scan.concurrency,
                arrowBatchSize:     scan.arrowBatchSize,
+               dictionaryFieldIDs: dictionaryFieldIDs,
        }, readTasks, releasePlanIO, nil
 }
 
diff --git a/table/table.go b/table/table.go
index e89d24119..2c3f134da 100644
--- a/table/table.go
+++ b/table/table.go
@@ -1525,6 +1525,32 @@ func WithArrowBatchSize(n int) ScanOption {
        }
 }
 
+// WithDictionaryColumns returns the named string and binary columns as Arrow
+// dictionary arrays. Names may be dotted paths to nested fields. They are
+// resolved when the scan reads, against the schema it reads with, honoring
+// [WithCaseSensitive].
+//
+// Requested columns always have type dictionary<int32, utf8> or
+// dictionary<int32, binary>, in the declared schema and in every batch, even
+// with the arrow.use_large_types option or when a data file stores the column
+// plain, as a large type, or as another dictionary type. Columns that are not
+// requested keep their usual types.
+//
+// The dictionary can differ from one batch to the next, including within a
+// file, so callers must not rely on dictionary identity across batches.
+//
+// Filtering on a requested column decodes the dictionary for each batch to
+// evaluate the predicate, so a filtered scan may not be faster.
+//
+// Reading fails if a name does not exist or names a column of another type. A
+// valid name that the scan does not project is ignored. Repeated calls replace
+// the earlier list.
+func WithDictionaryColumns(names ...string) ScanOption {
+       return func(scan *Scan) {
+               scan.dictionaryColumns = slices.Clone(names)
+       }
+}
+
 func (t Table) Scan(opts ...ScanOption) *Scan {
        directive, directiveErr := t.ScanPlanningDirective()
        s := &Scan{
diff --git a/website/src/api.md b/website/src/api.md
index f525cf3da..cbc05533d 100644
--- a/website/src/api.md
+++ b/website/src/api.md
@@ -272,6 +272,14 @@ scan := tbl.Scan(
 
 For the predicate vocabulary, see [Row Filter Syntax](./row-filter-syntax.md).
 
+### Dictionary-encoded columns
+
+```go
+scan := tbl.Scan(table.WithDictionaryColumns("region", "event.name"))
+```
+
+`WithDictionaryColumns` returns the named string and binary columns as Arrow 
dictionary arrays. Requested columns always have type `dictionary<int32, utf8>` 
or `dictionary<int32, binary>`, even with `arrow.use_large_types`. The 
dictionary can change from one batch to the next, so don't rely on dictionary 
identity across batches. Filtering on a requested column decodes the dictionary 
for each batch to evaluate the predicate, so a filtered scan may not be faster.
+
 ### Time travel
 
 ```go

Reply via email to