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/arrow-go.git
The following commit(s) were added to refs/heads/main by this push:
new bfccc933 fix(parquet/file): write `null_count` statistics for GEOMETRY
and GEOGRAPHY column chunks (#1533)
bfccc933 is described below
commit bfccc933edb1560b60538c02d391dc1742c77732
Author: Colton Loftus <[email protected]>
AuthorDate: Thu Nov 12 11:57:23 2026 -0500
fix(parquet/file): write `null_count` statistics for GEOMETRY and GEOGRAPHY
column chunks (#1533)
## Summary
Follow-up to #1504. GEOMETRY and GEOGRAPHY column chunks now get a
`ColumnMetaData.statistics` block that holds only `null_count`. min/max
are still not written.
The Parquet spec says min/max must not be written for types whose sort
order is undefined, such as GEOMETRY and GEOGRAPHY. However, it also
says writers SHOULD always write `null_count`, even for these types.
arrow-go, like Arrow C++, left out the whole `Statistics` block for
these types, so the footer had no null count at all. The Rust writer and
DuckDB's writer both write a `Statistics` block holding only
`null_count` for geometry columns, and this PR does the same.
This change also lets DuckDB skip row groups using the bounding boxes
from #1504. DuckDB v2.0.0 ignores a chunk's `geospatial_statistics` when
`statistics` is unset
([`parquet_statistics.cpp`](https://github.com/duckdb/duckdb/blob/v2.0.0/extension/parquet/parquet_statistics.cpp),
the early return before `TransformParquetStatistics`). So until now it
read every row group of files arrow-go writes, even though their
bounding boxes were correct.
## What this PR changes
All changes are in `parquet/file/column_writer.go`:
- **Setup:** when statistics are enabled for a GEOMETRY or GEOGRAPHY
byte-array column, the writer counts that column's nulls. GEOMETRY still
also gets the #1504 geospatial statistics.
- **Counting nulls:** `WriteDefinitionLevels` counts every definition
level below the maximum as a null. All write paths go through it:
normal, spaced, Arrow offsets, and dictionary indices. This is the same
"levels minus values" count the typed statistics use for other columns.
- **`Close`:** calls `SetStats` with only `null_count` set. min, max,
`min_value`, `max_value` and `distinct_count` stay unset.
## Points to review
1. **GEOGRAPHY gets a null count too.** It still gets no geospatial
statistics (see #1504), but the spec recommends `null_count` for every
column, and that number is easy to get right. If you'd rather keep this
to GEOMETRY only, it's a one-line change.
2. **The null count is written even when the bounding box isn't.** #1504
drops the geospatial statistics for invalid WKB, for dictionary-index
writes, and for chunks that are all null. The null count is still
correct in all three cases, so the `Statistics` block is written anyway.
3. **The reader side is unchanged.** `ColumnChunkMetaData.StatsSet()`
and `Statistics()` still report nothing for undefined-sort-order
columns, so nothing in arrow-go starts trusting min/max for them.
`GeoStatistics()` is also unchanged.
4. **Page-level statistics are not written** for these columns. Readers
don't need them to use the chunk's geospatial statistics.
5. **Existing issue, out of scope:** data page v2 headers take
`num_nulls` from the page statistics. Columns with an undefined sort
order have no page statistics, so their v2 page headers record 0 nulls
even when the page has nulls. This affects every such column, not only
geometry, so it would be better fixed separately.
## Testing
- **New test `TestGeoColumnNullCountStatistics`** in
`parquet/file/column_writer_geo_test.go`. It decodes the footer thrift
and checks exactly which fields are set. Each case runs with dictionary
encoding on and off, and with data page v1 and v2:
- GEOMETRY with nulls, written through `WriteBatch`,
`WriteBatchSpacedWithError` and `WriteBatchArrow`: `null_count` is
correct, the min/max fields are unset, and the geospatial statistics are
unchanged.
- GEOMETRY without nulls, a required GEOMETRY column, an all-null chunk,
and invalid WKB.
- GEOGRAPHY: `null_count` is written and there are no geospatial
statistics.
- Statistics disabled: neither block is written.
- Reader round trip: `GeoStatistics()` still returns the box, and
`StatsSet()` / `Statistics()` still report no typed statistics.
- **DuckDB v2.0.0 with the spatial extension** (one-off script, not
committed): with a two-row-group file and a filter on a box inside one
group's extent, DuckDB now scans 1 of 2 row groups (2.52 MB → 1.27 MB
read) for `&&`, `ST_Intersects` and `ST_Within`. On `main` it scans
both.
## Related
- DuckDB could also read `geospatial_statistics` when `statistics` is
unset. That would be correct too, and it would help files from other
writers that leave out the block. This PR works with DuckDB v2.0.0 as
released.
---
parquet/file/column_writer.go | 41 ++++++++-
parquet/file/column_writer_geo_test.go | 158 +++++++++++++++++++++++++++++++--
2 files changed, 190 insertions(+), 9 deletions(-)
diff --git a/parquet/file/column_writer.go b/parquet/file/column_writer.go
index 93ea4cff..1aeef29a 100644
--- a/parquet/file/column_writer.go
+++ b/parquet/file/column_writer.go
@@ -125,7 +125,19 @@ type columnWriter struct {
// It is tracked once per column chunk (i.e. per row group), never per
// page since Parquet format defines GeospatialStatistics only on
// ColumnMetaData
- geoStatistics *metadata.GeoStatistics
+ geoStatistics *metadata.GeoStatistics
+
+ // countGeoNulls is set for GEOMETRY and GEOGRAPHY columns with
+ // statistics enabled. Their sort order is undefined, so they have no
+ // typed statistics, but the chunk still gets a Statistics block holding
+ // only null_count (the spec forbids min/max for these types, but says
+ // writers should still write null_count). Some readers, such as DuckDB,
+ // ignore geospatial_statistics unless a Statistics block is present.
+ countGeoNulls bool
+ // geoNullCount is the number of null values written to this chunk,
+ // counted from the definition levels when countGeoNulls is set.
+ geoNullCount int64
+
bloomFilter metadata.BloomFilterBuilder
dictBloomPopulated bool
@@ -186,9 +198,14 @@ func newColumnWriterBase(metaData
*metadata.ColumnChunkMetaDataBuilder, pager Pa
ret.chunkStatistics = metadata.NewStatistics(ret.descr,
props.Allocator())
}
- if _, ok := ret.descr.LogicalType().(schema.GeometryLogicalType); ok &&
- ret.descr.PhysicalType() == parquet.Types.ByteArray &&
props.StatisticsEnabledFor(ret.descr.Path()) {
- ret.geoStatistics = metadata.NewGeoStatistics()
+ if props.StatisticsEnabledFor(ret.descr.Path()) &&
ret.descr.PhysicalType() == parquet.Types.ByteArray {
+ switch ret.descr.LogicalType().(type) {
+ case schema.GeometryLogicalType:
+ ret.geoStatistics = metadata.NewGeoStatistics()
+ ret.countGeoNulls = true
+ case schema.GeographyLogicalType:
+ ret.countGeoNulls = true
+ }
}
ret.defEncoder.Init(parquet.Encodings.RLE,
ret.descr.MaxDefinitionLevel(), ret.defLevelSink)
@@ -242,6 +259,16 @@ func (w *columnWriter) WriteDataPage(page DataPage) error {
}
func (w *columnWriter) WriteDefinitionLevels(levels []int16) {
+ if w.countGeoNulls {
+ // every level below the max definition level is a null value,
which
+ // matches how typed statistics count nulls (levels minus
values)
+ maxDefLevel := w.descr.MaxDefinitionLevel()
+ for _, v := range levels {
+ if v < maxDefLevel {
+ w.geoNullCount++
+ }
+ }
+ }
w.defEncoder.EncodeNoFlush(levels)
}
@@ -738,6 +765,12 @@ func (w *columnWriter) Close() (err error) {
if w.rowsWritten > 0 && chunkStats.IsSet() {
w.metaData.SetStats(chunkStats)
}
+ if w.rowsWritten > 0 && w.countGeoNulls {
+ // null_count only: min/max must not be written for a
type whose
+ // sort order is undefined
+ var nullStats metadata.EncodedStatistics
+
w.metaData.SetStats(*nullStats.SetNullCount(w.geoNullCount))
+ }
if w.rowsWritten > 0 && w.geoStatistics != nil {
w.metaData.SetGeoStatistics(w.geoStatistics)
}
diff --git a/parquet/file/column_writer_geo_test.go
b/parquet/file/column_writer_geo_test.go
index 4a05e521..55be702f 100644
--- a/parquet/file/column_writer_geo_test.go
+++ b/parquet/file/column_writer_geo_test.go
@@ -19,6 +19,7 @@ package file_test
import (
"bytes"
"encoding/binary"
+ "fmt"
"math"
"os"
"path"
@@ -26,6 +27,8 @@ import (
"github.com/apache/arrow-go/v18/parquet"
"github.com/apache/arrow-go/v18/parquet/file"
+ format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
+ "github.com/apache/arrow-go/v18/parquet/internal/thrift"
"github.com/apache/arrow-go/v18/parquet/metadata"
"github.com/apache/arrow-go/v18/parquet/schema"
"github.com/stretchr/testify/assert"
@@ -43,8 +46,18 @@ func geoPoint(x, y float64) parquet.ByteArray {
func writeGeoFile(t *testing.T, props *parquet.WriterProperties, write
func(*file.ByteArrayColumnChunkWriter)) *file.Reader {
t.Helper()
- geom, err := schema.NewPrimitiveNodeLogical("geom",
parquet.Repetitions.Optional,
- schema.GeometryLogicalType{}, parquet.Types.ByteArray, -1, -1)
+ buf := writeGeoColumn(t, schema.GeometryLogicalType{},
parquet.Repetitions.Optional, props, write)
+ rdr, err := file.NewParquetReader(bytes.NewReader(buf))
+ require.NoError(t, err)
+ t.Cleanup(func() { rdr.Close() })
+ return rdr
+}
+
+// writeGeoColumn writes a file with a single row group holding one byte array
+// column of the given logical type, and returns the file's bytes.
+func writeGeoColumn(t *testing.T, lt schema.LogicalType, rep
parquet.Repetition, props *parquet.WriterProperties, write
func(*file.ByteArrayColumnChunkWriter)) []byte {
+ t.Helper()
+ geom, err := schema.NewPrimitiveNodeLogical("geom", rep, lt,
parquet.Types.ByteArray, -1, -1)
require.NoError(t, err)
root, err := schema.NewGroupNode("schema",
parquet.Repetitions.Required, schema.FieldList{geom}, -1)
require.NoError(t, err)
@@ -58,11 +71,21 @@ func writeGeoFile(t *testing.T, props
*parquet.WriterProperties, write func(*fil
require.NoError(t, cw.Close())
require.NoError(t, rg.Close())
require.NoError(t, w.Close())
+ return buf.Bytes()
+}
- rdr, err := file.NewParquetReader(bytes.NewReader(buf.Bytes()))
+// footerColumnMeta decodes the file footer and returns the thrift metadata of
+// the first column chunk, so tests can check exactly which fields are set.
+func footerColumnMeta(t *testing.T, buf []byte) *format.ColumnMetaData {
+ t.Helper()
+ require.Greater(t, len(buf), 8)
+ footerLen := int(binary.LittleEndian.Uint32(buf[len(buf)-8:]))
+ var fmd format.FileMetaData
+ _, err := thrift.DeserializeThrift(&fmd,
buf[len(buf)-8-footerLen:len(buf)-8])
require.NoError(t, err)
- t.Cleanup(func() { rdr.Close() })
- return rdr
+ require.Len(t, fmd.RowGroups, 1)
+ require.Len(t, fmd.RowGroups[0].Columns, 1)
+ return fmd.RowGroups[0].Columns[0].MetaData
}
func TestGeometryColumnGeoStatistics(t *testing.T) {
@@ -207,3 +230,128 @@ func TestGeoStatisticsReferenceFiles(t *testing.T) {
}
})
}
+
+func TestGeoColumnNullCountStatistics(t *testing.T) {
+ assertNullCountOnly := func(t *testing.T, md *format.ColumnMetaData,
want int64) {
+ t.Helper()
+ require.True(t, md.IsSetStatistics(), "statistics block should
be written")
+ st := md.Statistics
+ require.True(t, st.IsSetNullCount())
+ assert.Equal(t, want, st.GetNullCount())
+ assert.False(t, st.IsSetMin())
+ assert.False(t, st.IsSetMax())
+ assert.False(t, st.IsSetMinValue())
+ assert.False(t, st.IsSetMaxValue())
+ assert.False(t, st.IsSetDistinctCount())
+ }
+
+ for _, dict := range []bool{false, true} {
+ for _, v := range []parquet.DataPageVersion{parquet.DataPageV1,
parquet.DataPageV2} {
+ props :=
parquet.NewWriterProperties(parquet.WithStats(true),
+ parquet.WithDictionaryDefault(dict),
parquet.WithDataPageVersion(v))
+ suffix := fmt.Sprintf(" (dict=%v, page v%d)", dict, v+1)
+
+ t.Run("GEOMETRY with nulls"+suffix, func(t *testing.T) {
+ buf := writeGeoColumn(t,
schema.GeometryLogicalType{}, parquet.Repetitions.Optional, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{geoPoint(-122.4, 37.8), geoPoint(-73.9,
40.7)}, []int16{1, 0, 1, 0}, nil)
+ require.NoError(t, err)
+ _, err =
cw.WriteBatchSpacedWithError([]parquet.ByteArray{geoPoint(5, 60), nil},
[]int16{1, 0}, nil, []byte{0b01}, 0)
+ require.NoError(t, err)
+ _, err = cw.WriteBatchArrow(geoPoint(1,
2), []int32{0, 21, 21}, []int16{1, 0}, nil)
+ require.NoError(t, err)
+ })
+ md := footerColumnMeta(t, buf)
+ assertNullCountOnly(t, md, 4)
+
+ // the geospatial statistics are unchanged
+ gs := md.GetGeospatialStatistics()
+ require.NotNil(t, gs)
+ require.NotNil(t, gs.Bbox)
+ assert.Equal(t, []float64{-122.4, 5, 2, 60},
[]float64{gs.Bbox.Xmin, gs.Bbox.Xmax, gs.Bbox.Ymin, gs.Bbox.Ymax})
+ assert.Equal(t, []int32{1}, gs.GeospatialTypes)
+ })
+
+ t.Run("GEOMETRY without nulls"+suffix, func(t
*testing.T) {
+ buf := writeGeoColumn(t,
schema.GeometryLogicalType{}, parquet.Repetitions.Optional, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{geoPoint(1, 2), geoPoint(3, 4)}, []int16{1,
1}, nil)
+ require.NoError(t, err)
+ })
+ md := footerColumnMeta(t, buf)
+ assertNullCountOnly(t, md, 0)
+ assert.True(t, md.IsSetGeospatialStatistics())
+ })
+
+ t.Run("required GEOMETRY"+suffix, func(t *testing.T) {
+ buf := writeGeoColumn(t,
schema.GeometryLogicalType{}, parquet.Repetitions.Required, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{geoPoint(1, 2), geoPoint(3, 4)}, nil, nil)
+ require.NoError(t, err)
+ })
+ assertNullCountOnly(t, footerColumnMeta(t,
buf), 0)
+ })
+
+ t.Run("GEOMETRY all null"+suffix, func(t *testing.T) {
+ buf := writeGeoColumn(t,
schema.GeometryLogicalType{}, parquet.Repetitions.Optional, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err := cw.WriteBatch(nil, []int16{0,
0, 0}, nil)
+ require.NoError(t, err)
+ })
+ md := footerColumnMeta(t, buf)
+ assertNullCountOnly(t, md, 3)
+ assert.False(t, md.IsSetGeospatialStatistics())
+ })
+
+ t.Run("GEOMETRY with invalid WKB"+suffix, func(t
*testing.T) {
+ // the bounding box is dropped, but the null
count is still valid
+ buf := writeGeoColumn(t,
schema.GeometryLogicalType{}, parquet.Repetitions.Optional, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{[]byte("not wkb")}, []int16{1, 0}, nil)
+ require.NoError(t, err)
+ })
+ md := footerColumnMeta(t, buf)
+ assertNullCountOnly(t, md, 1)
+ assert.False(t, md.IsSetGeospatialStatistics())
+ })
+
+ t.Run("GEOGRAPHY"+suffix, func(t *testing.T) {
+ buf := writeGeoColumn(t,
schema.GeographyLogicalType{}, parquet.Repetitions.Optional, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{geoPoint(1, 2)}, []int16{0, 1, 0}, nil)
+ require.NoError(t, err)
+ })
+ md := footerColumnMeta(t, buf)
+ assertNullCountOnly(t, md, 2)
+ assert.False(t, md.IsSetGeospatialStatistics())
+ })
+ }
+ }
+
+ t.Run("statistics disabled", func(t *testing.T) {
+ for _, lt := range
[]schema.LogicalType{schema.GeometryLogicalType{},
schema.GeographyLogicalType{}} {
+ props :=
parquet.NewWriterProperties(parquet.WithStats(false))
+ buf := writeGeoColumn(t, lt,
parquet.Repetitions.Optional, props, func(cw *file.ByteArrayColumnChunkWriter) {
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{geoPoint(1, 2)}, []int16{1, 0}, nil)
+ require.NoError(t, err)
+ })
+ md := footerColumnMeta(t, buf)
+ assert.False(t, md.IsSetStatistics(), "%s", lt)
+ assert.False(t, md.IsSetGeospatialStatistics(), "%s",
lt)
+ }
+ })
+
+ t.Run("reader round trip", func(t *testing.T) {
+ props := parquet.NewWriterProperties(parquet.WithStats(true))
+ rdr := writeGeoFile(t, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ _, err := cw.WriteBatch([]parquet.ByteArray{geoPoint(1,
2)}, []int16{1, 0}, nil)
+ require.NoError(t, err)
+ })
+ col, err := rdr.MetaData().RowGroup(0).ColumnChunk(0)
+ require.NoError(t, err)
+ require.NotNil(t, col.GeoStatistics())
+
+ // the sort order is undefined, so the reader still reports no
+ // typed statistics and never trusts a min/max for the column
+ ok, err := col.StatsSet()
+ require.NoError(t, err)
+ assert.False(t, ok)
+ stats, err := col.Statistics()
+ require.NoError(t, err)
+ assert.Nil(t, stats)
+ })
+}