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 83d6e62f feat(parquet/file): Write geospatial parquet row group
statistics for GEOMETRY column chunks (#1504)
83d6e62f is described below
commit 83d6e62f6c1751ee6df374d3484ad53c3db6a55e
Author: Colton Loftus <[email protected]>
AuthorDate: Wed Nov 11 12:37:01 2026 -0500
feat(parquet/file): Write geospatial parquet row group statistics for
GEOMETRY column chunks (#1504)
## Summary
As discussed in
[apache/iceberg-go#989](https://github.com/apache/iceberg-go/issues/989#issuecomment-6680086033),
arrow-go currently doesn't write geospatial statistics for GEOMETRY
row groups which limits query performance.
The Parquet spec has a `GeospatialStatistics` field on `ColumnMetaData`.
It holds a bounding
box (X/Y, plus optional Z/M) and the list of geometry types seen in the
column chunk. arrow-go could already read and write the
GEOMETRY/GEOGRAPHY logical types, but it never filled in their
statistics field.
This PR makes the column writer compute those statistics for
**GEOMETRY** columns as it writes them, and stores
them in the footer. GEOGRAPHY columns are deliberately left out and
intended as a follow up PR.
Apologies in advance that this is a fairly long write up. However, I
think the verbosity is useful for giving context for the code review.
---
<details>
<summary><strong>Context for Iceberg-go and the new end to end write
path</strong></summary>
When iceberg-go writes a geometry column, three repos are involved:
- **iceberg-go**
- Maps Iceberg `geometry`/`geography` types and their CRS to the
geoarrow Arrow extension type
(`table/arrow_utils.go`).
- Computes the Iceberg manifest bounds and null counts for geo columns
from the Arrow data, not from Parquet
stats (`table/internal/geo_codec.go`, `geoBoundsAccumulator` in
`table/internal/parquet_files.go`).
- It has to, because arrow-go writes no `Statistics` block (min/max/null
count) for types with an undefined
sort order, like GEOMETRY and GEOGRAPHY. The spec only rules out min/max
for these types. It says writers
SHOULD always write `null_count`, and the Rust writer does. arrow-go
(like Arrow C++) leaves the whole
block out, so the footer has no null count for iceberg-go to read.
- **geoarrow-go**
- Defines the `geoarrow.wkb` Arrow extension type and maps it to and
from the Parquet GEOMETRY/GEOGRAPHY
logical types, including CRS and edges (`wkb.go`, `metadata.go`).
- **arrow-go**
- Defines the Parquet GEOMETRY/GEOGRAPHY logical types
(`parquet/schema/logical_types.go`, released in
v18.8.0).
- Provides the pqarrow hooks that let an extension type pick its Parquet
logical type on write and read
(`ExtensionCustomParquetType`, `ExtensionCustomArrowReadType`, released
in v18.8.0).
- **This PR:** computes the column chunk `GeospatialStatistics` (bbox
and geometry types) while writing, and
stores them in the footer.
A write flows like this:
```
Iceberg schema
→ geoarrow.NewWKBType(...) (geoarrow-go; Binary or
LargeBinary storage)
→ pqarrow.NewFileWriter (arrow-go)
→ ParquetLogicalType() hook (geoarrow-go) → column is
GEOMETRY(crs) / GEOGRAPHY(crs, algo)
→ columnWriter sees GeometryLogicalType (arrow-go, NEW) → builds
GeoStatistics while writing
→ Close() → SetGeoStatistics → footer (arrow-go, NEW)
```
On the read side, any reader can call
`rdr.MetaData().RowGroup(i).ColumnChunk(j).GeoStatistics()`.
</details>
## What this PR changes
- **New WKB parser** (`parquet/internal/geospatial/bounder.go`): reads
WKB bytes and tracks the min/max of each
dimension plus the geometry types seen. No geometry library needed.
- **New `GeoStatistics` type** (`parquet/metadata/geo_statistics.go`):
wraps the parser and converts to/from the
thrift footer struct.
- **Reader and writer hooks** (`parquet/metadata/column_chunk.go`):
`ColumnChunkMetaData.GeoStatistics()` to
read, `ColumnChunkMetaDataBuilder.SetGeoStatistics()` to write.
- **Column writer** (`parquet/file/column_writer.go`): creates the
statistics for GEOMETRY columns when stats are
enabled, and writes them to the footer on `Close()`.
- **Write paths** (`column_writer_types.gen.go.tmpl` + generated file,
`byte_array_column_writer_arrow.go`): every
ByteArray write path feeds values to the statistics. `WriteDictIndices`
invalidates them instead (item 3).
- **Tests:** `bounder_test.go` (WKB edge cases),
`geo_statistics_test.go` (thrift round trip and update paths),
`column_writer_geo_test.go` (end to end through the writer and reader).
## Non-obvious logic/ points to align on before merging
I've tried to go with a sane default for all of these, but figured it's
best practice to be explicit.
### 1. GEOGRAPHY columns get no statistics
The spec allows GEOGRAPHY statistics, but computing them correctly needs
fairly complex geodesic math. My plan is to leave this out of scope and
revisit as a follow-up if there is demand among users.
Reading is left out too: `GeoStatistics()` returns nil for GEOGRAPHY
columns, even when another tool (such as
DataFusion) wrote statistics for them. Those boxes can wrap across the
antimeridian (`xmin > xmax`), which the
new type doesn't represent. Reading GEOGRAPHY statistics, including
wraparound boxes, can be part of the same
follow-up.
### 2. A single bad value drops the statistics for the whole column
chunk
If any value isn't valid WKB, or has a NaN coordinate (other than a
fully-NaN empty point), the whole chunk's
statistics are marked invalid and nothing is written. That's safe, since
readers can never prune wrongly, but
it's stricter than some other tools.
**Alternative:** skip only the bad value. That keeps pruning, at the
cost of a bbox that doesn't cover every row
(the spec doesn't say what to do here).
### 3. Arrow dictionary arrays invalidate the statistics
`WriteDictIndices` (used by pqarrow for `Dictionary<…, binary>` arrays)
only receives integer indices; the
dictionary was already given to the encoder. Rather than decode the
dictionary, the PR invalidates the
statistics, and that sticks for the rest of the chunk. iceberg-go and
geoarrow-go never produce dictionary
arrays of WKB, so this doesn't affect them.
### 4. Z/M bounds are written if *any* geometry has Z/M
If one geometry in the chunk has Z, the footer gets Z bounds that cover
only those geometries. That matches the
reference writer. iceberg-go's manifest only emits Z/M when *every*
geometry has them, because Iceberg's bound
semantics are different. Both are right for their own format, but the
footer bbox and the Iceberg manifest
bounds for the same file can differ on Z/M. Should be noted that this
isn't bug in a cross-check test.
### 5. Only top-level geometry types are recorded
`geospatial_types` lists the type of each *row*: a GeometryCollection
containing a Point Z records `[7]`, not
`[7, 1001]`. Coordinates of nested children still count toward the
bounds, so that example produces Z bounds
while the only type listed is 2D. This matches the spec's "type codes of
all instances" wording, where an
instance is a row.
### 6. The parser is lenient in some places
These are accepted and not validated. Tests don't pin any of this
behavior, so tightening them later is easy.
- **EWKB** (the PostGIS Z/M/SRID flags) is accepted and normalized to
ISO codes. The SRID is skipped. The spec
says values are ISO WKB, but accepting EWKB costs nothing and handles
files written by PostGIS-style tools.
- **Multi\* child types aren't checked:** a MultiPoint that contains a
LineString is accepted.
- **Child dimensions aren't checked against the parent's:** a Point Z
inside a 2D collection is accepted (see 5).
- **±Inf coordinates** are accepted and end up in the bbox.
### 7. Chunks with no written geometries store nothing
`toThrift` returns nil when no non-null geometry was seen, so all-null
row groups get no
`GeospatialStatistics`. The reference writer stores an empty struct (no
types, no bbox). Both mean "no
information" to a reader, so I think it is fine.
### 8. Public API surface
New exported names in `parquet/metadata`: the `GeoStatistics` type and
its methods, `NewGeoStatistics`,
`UpdateGeoStatisticsFromArrowOffsets` (a generic function, because Go
methods can't have type parameters), and
`ColumnChunkMetaData.GeoStatistics()` /
`ColumnChunkMetaDataBuilder.SetGeoStatistics()`. The `Update*`,
`Merge`, `Reset` and `Invalidate` methods mostly exist for the writer.
It's possible that fewer public methods may be desired. For example,
readers only need the accessors, so the writer-only methods could be
made unexported. `Merge` is
unused today, but it's the obvious way to union row groups into a
file-level box.
### 9. Write-time cost / benchmarking
Statistics are on by default, so every GEOMETRY write now parses each
WKB value once. The parser doesn't
allocate per value and stops at the first error, but there's no
benchmark yet. Callers who don't want the cost
can turn statistics off for the column with `parquet.WithStatsFor(path,
false)`.
### 10. Minor Geometry logic overlap in both arrow-go and geoarrow-go
Both repos now deal with geometry, but at different layers:
- **arrow-go works at the Parquet layer.** It defines the
GEOMETRY/GEOGRAPHY logical types that describe a column
in the file footer (CRS, edge algorithm). With this PR, it also has a
small WKB parser that reads every
coordinate to compute the bounding box and geometry types for the
statistics.
- **geoarrow-go works at the Arrow layer.** It defines the in-memory
extension types (`geoarrow.wkb` and native
types like point and polygon), with CRS and edges stored as Arrow
metadata. It implements the pqarrow hooks
that map its types to arrow-go's Parquet logical types. For WKB it only
reads the 5-byte header (geometry type
and dimension), and it uses go-geom when full decoding is needed.
arrow-go has its own parser instead of reusing geoarrow-go for three
reasons:
- geoarrow-go imports arrow-go, so arrow-go can't import geoarrow-go
without a dependency cycle.
- The statistics are computed in the Parquet column writer, which only
sees raw bytes and the Parquet logical
type, not the Arrow extension type. Code that writes with
`file.ByteArrayColumnChunkWriter` directly, without
pqarrow or geoarrow-go, still gets statistics.
- The parser only scans coordinates, so arrow-go doesn't need to depend
on go-geom.
I had Opus 5.5 help me generate the WKB parser in
`parquet/internal/geospatial/bounder.go`. It passes tests as expected
and I think it looks reasonable to me, however I certainly could have
overlooked parts of the WKB spec / there are likely ways to optimize
parsing further. There is a legitimate question if at some point all the
geospatial logic relevant to arrow along with go-geom should be included
here to reduce this logic. This probably makes more sense to discuss
later in the future though if GEOGRAPHY needs to be added here.
## Testing
- `go test ./parquet/...` passes, with `PARQUET_TEST_DATA` and
`ARROW_TEST_DATA` pointed at the submodules
(`pqarrow` panics without them, unrelated to this PR).
- `go generate` for `column_writer_types.gen.go` produces no diff, so
the generated file matches the template.
- **Cross-check against the reference files** in
`parquet-testing/data/geospatial/` (one-off, not committed). The
values were decoded and rewritten through this writer, and the footer
stats compared:
- `geospatial.parquet`: 30 of 31 row groups match exactly, covering
every geometry type × XY/XYZ/XYM/XYZM,
collections, empty geometries and nulls. The one difference is the
all-null row group (item 7).
- `crs-default`, `crs-srid`, `crs-projjson`: match.
- `geospatial-with-nan.parquet`: differs on purpose (item 2).
- **Iceberg end-to-end:** geoarrow-go (`fc2b33c`) and iceberg-go
(`b1206c6`) pass their full test suites with a `replace`
pointing at this branch. A one-off iceberg-go test that writes through
`WriteDataFile` confirmed: GEOMETRY
footer stats match the manifest X/Y bounds; GEOGRAPHY and all-null
columns get no footer stats; mixed
`POINT Z` + `POINT` gives footer Z bounds while the manifest is XY only
(item 4).
---------
Co-authored-by: Matt Topol <[email protected]>
---
parquet/file/byte_array_column_writer_arrow.go | 12 +
parquet/file/column_writer.go | 21 +-
parquet/file/column_writer_geo_test.go | 209 ++++++++++
parquet/file/column_writer_types.gen.go | 25 ++
parquet/file/column_writer_types.gen.go.tmpl | 31 ++
parquet/internal/geospatial/bounder.go | 273 +++++++++++++
parquet/internal/geospatial/bounder_test.go | 510 +++++++++++++++++++++++++
parquet/metadata/column_chunk.go | 27 ++
parquet/metadata/geo_statistics.go | 158 ++++++++
parquet/metadata/geo_statistics_test.go | 305 +++++++++++++++
10 files changed, 1569 insertions(+), 2 deletions(-)
diff --git a/parquet/file/byte_array_column_writer_arrow.go
b/parquet/file/byte_array_column_writer_arrow.go
index ce99540c..04b328f1 100644
--- a/parquet/file/byte_array_column_writer_arrow.go
+++ b/parquet/file/byte_array_column_writer_arrow.go
@@ -72,6 +72,9 @@ func writeArrowValues[T byteArrayArrowOffset](w
*ByteArrayColumnChunkWriter, val
panic("parquet: current byte-array encoder does not
support Arrow offsets")
}
enc.PutArrow(values, offsets)
+ if w.geoStatistics != nil {
+
metadata.UpdateGeoStatisticsFromArrowOffsets(w.geoStatistics, values, offsets,
nil, 0)
+ }
if w.pageStatistics != nil {
w.pageStatistics.(*metadata.ByteArrayStatistics).UpdateFromArrowOffsets(values,
offsets, numNulls)
}
@@ -84,6 +87,9 @@ func writeArrowValues[T byteArrayArrowOffset](w
*ByteArrayColumnChunkWriter, val
panic("parquet: current byte-array encoder does not
support Arrow offsets")
}
enc.PutArrow64(values, offsets)
+ if w.geoStatistics != nil {
+
metadata.UpdateGeoStatisticsFromArrowOffsets(w.geoStatistics, values, offsets,
nil, 0)
+ }
if w.pageStatistics != nil {
w.pageStatistics.(*metadata.ByteArrayStatistics).UpdateFromArrowOffsets64(values,
offsets, numNulls)
}
@@ -110,6 +116,9 @@ func writeArrowValuesSpaced[T byteArrayArrowOffset](w
*ByteArrayColumnChunkWrite
} else {
enc.PutArrow(values, offsets)
}
+ if w.geoStatistics != nil {
+
metadata.UpdateGeoStatisticsFromArrowOffsets(w.geoStatistics, values, offsets,
validBits, validBitsOffset)
+ }
if w.pageStatistics != nil {
stats :=
w.pageStatistics.(*metadata.ByteArrayStatistics)
stats.UpdateFromArrowOffsetsSpaced(values, offsets,
validBits, validBitsOffset, numSpaced-numRead)
@@ -128,6 +137,9 @@ func writeArrowValuesSpaced[T byteArrayArrowOffset](w
*ByteArrayColumnChunkWrite
} else {
enc.PutArrow64(values, offsets)
}
+ if w.geoStatistics != nil {
+
metadata.UpdateGeoStatisticsFromArrowOffsets(w.geoStatistics, values, offsets,
validBits, validBitsOffset)
+ }
if w.pageStatistics != nil {
stats :=
w.pageStatistics.(*metadata.ByteArrayStatistics)
stats.UpdateFromArrowOffsetsSpaced64(values, offsets,
validBits, validBitsOffset, numSpaced-numRead)
diff --git a/parquet/file/column_writer.go b/parquet/file/column_writer.go
index aa1f0726..93ea4cff 100644
--- a/parquet/file/column_writer.go
+++ b/parquet/file/column_writer.go
@@ -115,8 +115,17 @@ type columnWriter struct {
repEncoder encoding.LevelEncoder
mem memory.Allocator
- pageStatistics metadata.TypedStatistics
- chunkStatistics metadata.TypedStatistics
+ pageStatistics metadata.TypedStatistics
+ chunkStatistics metadata.TypedStatistics
+
+ // geoStatistics holds the bounding box stats for GEOMETRY
+ // columns, and is nil for all other columns. Since Geospatial
+ // types have an UNKNOWN sort order, they never get typed
+ // statistics and are stored separately from other statistics.
+ // 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
bloomFilter metadata.BloomFilterBuilder
dictBloomPopulated bool
@@ -177,6 +186,11 @@ 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()
+ }
+
ret.defEncoder.Init(parquet.Encodings.RLE,
ret.descr.MaxDefinitionLevel(), ret.defLevelSink)
ret.repEncoder.Init(parquet.Encodings.RLE,
ret.descr.MaxRepetitionLevel(), ret.repLevelSink)
@@ -724,6 +738,9 @@ func (w *columnWriter) Close() (err error) {
if w.rowsWritten > 0 && chunkStats.IsSet() {
w.metaData.SetStats(chunkStats)
}
+ if w.rowsWritten > 0 && w.geoStatistics != nil {
+ w.metaData.SetGeoStatistics(w.geoStatistics)
+ }
// Only advertise PLAIN_DICTIONARY / fallback encodings in the
column
// chunk's encoding list when a dictionary page was actually
written.
// When fallback discards the dictionary before any
dict-encoded page
diff --git a/parquet/file/column_writer_geo_test.go
b/parquet/file/column_writer_geo_test.go
new file mode 100644
index 00000000..4a05e521
--- /dev/null
+++ b/parquet/file/column_writer_geo_test.go
@@ -0,0 +1,209 @@
+// 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 file_test
+
+import (
+ "bytes"
+ "encoding/binary"
+ "math"
+ "os"
+ "path"
+ "testing"
+
+ "github.com/apache/arrow-go/v18/parquet"
+ "github.com/apache/arrow-go/v18/parquet/file"
+ "github.com/apache/arrow-go/v18/parquet/metadata"
+ "github.com/apache/arrow-go/v18/parquet/schema"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func geoPoint(x, y float64) parquet.ByteArray {
+ b := make([]byte, 21)
+ b[0] = 1
+ binary.LittleEndian.PutUint32(b[1:], 1)
+ binary.LittleEndian.PutUint64(b[5:], math.Float64bits(x))
+ binary.LittleEndian.PutUint64(b[13:], math.Float64bits(y))
+ return b
+}
+
+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)
+ require.NoError(t, err)
+ root, err := schema.NewGroupNode("schema",
parquet.Repetitions.Required, schema.FieldList{geom}, -1)
+ require.NoError(t, err)
+
+ var buf bytes.Buffer
+ w := file.NewParquetWriter(&buf, root, file.WithWriterProps(props))
+ rg := w.AppendRowGroup()
+ cw, err := rg.NextColumn()
+ require.NoError(t, err)
+ write(cw.(*file.ByteArrayColumnChunkWriter))
+ require.NoError(t, cw.Close())
+ require.NoError(t, rg.Close())
+ require.NoError(t, w.Close())
+
+ rdr, err := file.NewParquetReader(bytes.NewReader(buf.Bytes()))
+ require.NoError(t, err)
+ t.Cleanup(func() { rdr.Close() })
+ return rdr
+}
+
+func TestGeometryColumnGeoStatistics(t *testing.T) {
+ for _, dict := range []bool{false, true} {
+ props := parquet.NewWriterProperties(parquet.WithStats(true),
parquet.WithDictionaryDefault(dict))
+ rdr := writeGeoFile(t, props, func(cw
*file.ByteArrayColumnChunkWriter) {
+ // batch 1: dense with one null; batch 2: spaced
+ _, err :=
cw.WriteBatch([]parquet.ByteArray{geoPoint(-122.4, 37.8), geoPoint(-73.9,
40.7)}, []int16{1, 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)
+ })
+
+ col, err := rdr.MetaData().RowGroup(0).ColumnChunk(0)
+ require.NoError(t, err)
+ gs := col.GeoStatistics()
+ require.NotNil(t, gs, "dict=%v", dict)
+ assert.True(t, gs.HasBoundingBox())
+ assert.Equal(t, -122.4, gs.XMin())
+ assert.Equal(t, 5.0, gs.XMax())
+ assert.Equal(t, 37.8, gs.YMin())
+ assert.Equal(t, 60.0, gs.YMax())
+ assert.False(t, gs.HasZ())
+ assert.False(t, gs.HasM())
+ assert.Equal(t, []int32{1}, gs.GeometryTypes())
+ }
+}
+
+func TestGeometryColumnArrowOffsetsGeoStatistics(t *testing.T) {
+ props := parquet.NewWriterProperties(parquet.WithStats(true),
parquet.WithDictionaryDefault(false))
+ a, b := geoPoint(1, 2), geoPoint(3, 4)
+ data := append(append([]byte{}, a...), b...)
+ rdr := writeGeoFile(t, props, func(cw *file.ByteArrayColumnChunkWriter)
{
+ _, err := cw.WriteBatchArrow(data, []int32{0, 21, 42},
[]int16{1, 1}, nil)
+ require.NoError(t, err)
+ _, err = cw.WriteBatchArrow64(data, []int64{0, 21, 42},
[]int16{1, 1}, nil)
+ require.NoError(t, err)
+ })
+ col, err := rdr.MetaData().RowGroup(0).ColumnChunk(0)
+ require.NoError(t, err)
+ gs := col.GeoStatistics()
+ require.NotNil(t, gs)
+ assert.Equal(t, []float64{1, 3, 2, 4}, []float64{gs.XMin(), gs.XMax(),
gs.YMin(), gs.YMax()})
+}
+
+func TestGeometryColumnInvalidWKBOmitsGeoStatistics(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),
[]byte("not wkb")}, []int16{1, 1}, nil)
+ require.NoError(t, err)
+ })
+ col, err := rdr.MetaData().RowGroup(0).ColumnChunk(0)
+ require.NoError(t, err)
+ assert.Nil(t, col.GeoStatistics())
+}
+
+func TestGeometryColumnStatsDisabled(t *testing.T) {
+ props := parquet.NewWriterProperties(parquet.WithStats(false))
+ rdr := writeGeoFile(t, props, func(cw *file.ByteArrayColumnChunkWriter)
{
+ _, err := cw.WriteBatch([]parquet.ByteArray{geoPoint(1, 2)},
[]int16{1}, nil)
+ require.NoError(t, err)
+ })
+ col, err := rdr.MetaData().RowGroup(0).ColumnChunk(0)
+ require.NoError(t, err)
+ assert.Nil(t, col.GeoStatistics())
+}
+
+func TestGeoStatisticsReferenceFiles(t *testing.T) {
+ dir := os.Getenv("PARQUET_TEST_DATA")
+ if dir == "" {
+ dir = "../../parquet-testing/data"
+ t.Log("PARQUET_TEST_DATA not set, using
../../parquet-testing/data")
+ }
+ dir = path.Join(dir, "geospatial")
+ assert.DirExists(t, dir)
+
+ geomColumn := func(t *testing.T, rdr *file.Reader) int {
+ t.Helper()
+ idx := rdr.MetaData().Schema.ColumnIndexByName("geometry")
+ require.GreaterOrEqual(t, idx, 0)
+ return idx
+ }
+
+ t.Run("GEOMETRY statistics are returned", func(t *testing.T) {
+ rdr, err := file.OpenParquetFile(path.Join(dir,
"crs-default.parquet"), false)
+ require.NoError(t, err)
+ defer rdr.Close()
+
+ col, err :=
rdr.MetaData().RowGroup(0).ColumnChunk(geomColumn(t, rdr))
+ require.NoError(t, err)
+ gs := col.GeoStatistics()
+ require.NotNil(t, gs)
+ assert.True(t, gs.HasBoundingBox())
+ })
+
+ t.Run("NaN coordinates are skipped like the reference writer", func(t
*testing.T) {
+ // One geometry in this file is an all-NaN linestring. The
reference
+ // writer ignores it and still records a bounding box for the
others,
+ // recomputing from the values must give the same statistics.
+ rdr, err := file.OpenParquetFile(path.Join(dir,
"geospatial-with-nan.parquet"), false)
+ require.NoError(t, err)
+ defer rdr.Close()
+
+ idx := geomColumn(t, rdr)
+ col, err := rdr.MetaData().RowGroup(0).ColumnChunk(idx)
+ require.NoError(t, err)
+ want := col.GeoStatistics()
+ require.NotNil(t, want)
+ assert.Equal(t, []float64{10, 130, 20, 140},
[]float64{want.XMin(), want.XMax(), want.YMin(), want.YMax()})
+ assert.Equal(t, []int32{3001, 3002}, want.GeometryTypes())
+
+ cr, err := rdr.RowGroup(0).Column(idx)
+ require.NoError(t, err)
+ n := rdr.NumRows()
+ values := make([]parquet.ByteArray, n)
+ defLevels := make([]int16, n)
+ _, read, err :=
cr.(*file.ByteArrayColumnChunkReader).ReadBatch(n, values, defLevels, nil)
+ require.NoError(t, err)
+
+ got := metadata.NewGeoStatistics()
+ got.Update(values[:read])
+ require.True(t, got.Valid())
+ assert.Equal(t, want.GeometryTypes(), got.GeometryTypes())
+ assert.Equal(t,
+ []float64{want.XMin(), want.XMax(), want.YMin(),
want.YMax(), want.ZMin(), want.ZMax(), want.MMin(), want.MMax()},
+ []float64{got.XMin(), got.XMax(), got.YMin(),
got.YMax(), got.ZMin(), got.ZMax(), got.MMin(), got.MMax()})
+ })
+
+ t.Run("GEOGRAPHY statistics are not returned", func(t *testing.T) {
+ // This file has GEOGRAPHY statistics in every row group, some
with
+ // bounding boxes that wrap across the antimeridian.
+ rdr, err := file.OpenParquetFile(path.Join(dir,
"geography-lines.parquet"), false)
+ require.NoError(t, err)
+ defer rdr.Close()
+
+ idx := geomColumn(t, rdr)
+ require.IsType(t, schema.GeographyLogicalType{},
rdr.MetaData().Schema.Column(idx).LogicalType())
+ for rg := 0; rg < rdr.NumRowGroups(); rg++ {
+ col, err := rdr.MetaData().RowGroup(rg).ColumnChunk(idx)
+ require.NoError(t, err)
+ assert.Nil(t, col.GeoStatistics(), "row group %d", rg)
+ }
+ })
+}
diff --git a/parquet/file/column_writer_types.gen.go
b/parquet/file/column_writer_types.gen.go
index 906ecdbe..465dbe79 100644
--- a/parquet/file/column_writer_types.gen.go
+++ b/parquet/file/column_writer_types.gen.go
@@ -2063,6 +2063,21 @@ func (w *ByteArrayColumnChunkWriter)
WriteDictIndices(indices arrow.Array, defLe
dictEncoder := w.currentEncoder.(encoding.DictEncoder)
+ // Geospatial statistics (bounding box + geometry types) are built by
parsing
+ // each WKB value as it is written.
+ // However, this path is different: the caller (pqarrow's
writeDictionaryArrow) has
+ // already handed the dictionary to the encoder via PutDictionary, and
we
+ // only receive integer indices into it. We never see the actual
geometries
+ // for these rows, so we cannot fold them into the bounding box.
+ //
+ // Rather than decode the dictionary here we mark the
+ // statistics invalid. Invalidation is sticky for the rest of this
column
+ // chunk: later dense writes do not restore it, and no geospatial
statistics
+ // are written to the column chunk metadata on Close.
+ if w.geoStatistics != nil {
+ w.geoStatistics.Invalidate()
+ }
+
w.doBatches(int64(length), repLevels, func(offset, batch int64) {
info := w.maybeCalculateValidityBits(levelSliceOrNil(defLevels,
offset, batch), batch)
@@ -2089,6 +2104,9 @@ func (w *ByteArrayColumnChunkWriter)
WriteDictIndices(indices arrow.Array, defLe
func (w *ByteArrayColumnChunkWriter) writeValues(values []parquet.ByteArray,
numNulls int64) {
w.currentEncoder.(encoding.ByteArrayEncoder).Put(values)
+ if w.geoStatistics != nil {
+ w.geoStatistics.Update(values)
+ }
if w.pageStatistics != nil {
w.pageStatistics.(*metadata.ByteArrayStatistics).Update(values,
numNulls)
}
@@ -2103,6 +2121,13 @@ func (w *ByteArrayColumnChunkWriter)
writeValuesSpaced(spacedValues []parquet.By
} else {
w.currentEncoder.(encoding.ByteArrayEncoder).Put(spacedValues)
}
+ if w.geoStatistics != nil {
+ if len(spacedValues) != int(numRead) {
+ w.geoStatistics.UpdateSpaced(spacedValues, validBits,
validBitsOffset)
+ } else {
+ w.geoStatistics.Update(spacedValues)
+ }
+ }
if w.pageStatistics != nil {
nulls := numValues - numRead
w.pageStatistics.(*metadata.ByteArrayStatistics).UpdateSpaced(spacedValues,
validBits, validBitsOffset, nulls)
diff --git a/parquet/file/column_writer_types.gen.go.tmpl
b/parquet/file/column_writer_types.gen.go.tmpl
index c9e1ad7a..87573d28 100644
--- a/parquet/file/column_writer_types.gen.go.tmpl
+++ b/parquet/file/column_writer_types.gen.go.tmpl
@@ -428,6 +428,23 @@ func (w *{{.Name}}ColumnChunkWriter)
WriteDictIndices(indices arrow.Array, defLe
}
dictEncoder := w.currentEncoder.(encoding.DictEncoder)
+{{- if eq .Name "ByteArray"}}
+
+ // Geospatial statistics (bounding box + geometry types) are built by parsing
+ // each WKB value as it is written.
+ // However, this path is different: the caller (pqarrow's
writeDictionaryArrow) has
+ // already handed the dictionary to the encoder via PutDictionary, and we
+ // only receive integer indices into it. We never see the actual geometries
+ // for these rows, so we cannot fold them into the bounding box.
+ //
+ // Rather than decode the dictionary here we mark the
+ // statistics invalid. Invalidation is sticky for the rest of this column
+ // chunk: later dense writes do not restore it, and no geospatial statistics
+ // are written to the column chunk metadata on Close.
+ if w.geoStatistics != nil {
+ w.geoStatistics.Invalidate()
+ }
+{{- end}}
w.doBatches(int64(length), repLevels, func(offset, batch int64) {
info := w.maybeCalculateValidityBits(levelSliceOrNil(defLevels, offset,
batch), batch)
@@ -455,6 +472,11 @@ func (w *{{.Name}}ColumnChunkWriter)
WriteDictIndices(indices arrow.Array, defLe
func (w *{{.Name}}ColumnChunkWriter) writeValues(values []{{.name}}, numNulls
int64) {
w.currentEncoder.(encoding.{{.Name}}Encoder).Put(values)
+{{- if eq .Name "ByteArray"}}
+ if w.geoStatistics != nil {
+ w.geoStatistics.Update(values)
+ }
+{{- end}}
if w.pageStatistics != nil {
{{- if ne .Name "FixedLenByteArray"}}
w.pageStatistics.(*metadata.{{.Name}}Statistics).Update(values, numNulls)
@@ -477,6 +499,15 @@ func (w *{{.Name}}ColumnChunkWriter)
writeValuesSpaced(spacedValues []{{.name}},
} else {
w.currentEncoder.(encoding.{{.Name}}Encoder).Put(spacedValues)
}
+{{- if eq .Name "ByteArray"}}
+ if w.geoStatistics != nil {
+ if len(spacedValues) != int(numRead) {
+ w.geoStatistics.UpdateSpaced(spacedValues, validBits, validBitsOffset)
+ } else {
+ w.geoStatistics.Update(spacedValues)
+ }
+ }
+{{- end}}
if w.pageStatistics != nil {
nulls := numValues - numRead
{{- if ne .Name "FixedLenByteArray"}}
diff --git a/parquet/internal/geospatial/bounder.go
b/parquet/internal/geospatial/bounder.go
new file mode 100644
index 00000000..4280c0e2
--- /dev/null
+++ b/parquet/internal/geospatial/bounder.go
@@ -0,0 +1,273 @@
+// 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 geospatial computes the bounding box and geometry type set of
+// WKB-encoded geometries for Parquet geospatial statistics. It has no
+// dependency on any geometry library: it only walks WKB coordinates.
+package geospatial
+
+import (
+ "encoding/binary"
+ "math"
+ "slices"
+)
+
+// Coordinate dimensions, in the order they are indexed in a Bounder.
+const (
+ DimX = iota
+ DimY
+ DimZ
+ DimM
+ numDims
+)
+
+const (
+ ewkbZ = 0x80000000
+ ewkbM = 0x40000000
+ ewkbSRID = 0x20000000
+
+ maxNesting = 64
+)
+
+// Bounder accumulates the per-dimension min/max and the set of ISO WKB
geometry
+// type codes of the geometries it is given. NaN ordinates are ignored, so they
+// never appear in the bounds. If any value is not valid WKB the Bounder
becomes
+// invalid and its results must not be written.
+//
+// The zero value is not usable, use NewBounder.
+type Bounder struct {
+ min, max [numDims]float64
+ types map[int32]struct{}
+ invalid bool
+}
+
+// NewBounder returns an empty, valid Bounder.
+func NewBounder() *Bounder {
+ b := &Bounder{}
+ b.Reset()
+ return b
+}
+
+// NewBounderFrom builds a Bounder from previously computed results, such as
+// those read back from a file footer. A dimension is considered present
+// when min <= max.
+func NewBounderFrom(min, max [4]float64, types []int32) *Bounder {
+ b := &Bounder{min: min, max: max, types: make(map[int32]struct{},
len(types))}
+ for _, t := range types {
+ b.types[t] = struct{}{}
+ }
+ return b
+}
+
+// Reset clears all accumulated state and makes the Bounder valid again.
+func (b *Bounder) Reset() {
+ for i := range b.min {
+ b.min[i], b.max[i] = math.Inf(1), math.Inf(-1)
+ }
+ b.types = make(map[int32]struct{})
+ b.invalid = false
+}
+
+// Invalidate marks the results as unusable, for example when values were
+// written that cannot be inspected.
+func (b *Bounder) Invalidate() { b.invalid = true }
+
+// Valid reports whether every value seen so far was valid WKB.
+func (b *Bounder) Valid() bool { return !b.invalid }
+
+// HasDim reports whether at least one coordinate was seen in dimension dim.
+func (b *Bounder) HasDim(dim int) bool { return b.min[dim] <= b.max[dim] }
+
+// Min returns the minimum for dim, only meaningful if HasDim(dim).
+func (b *Bounder) Min(dim int) float64 { return b.min[dim] }
+
+// Max returns the maximum for dim, only meaningful if HasDim(dim).
+func (b *Bounder) Max(dim int) float64 { return b.max[dim] }
+
+// Types returns the sorted ISO WKB geometry type codes seen
+// (e.g. 1 = Point, 1001 = Point Z, 2003 = LineString M, 3001 ...).
+func (b *Bounder) Types() []int32 {
+ out := make([]int32, 0, len(b.types))
+ for t := range b.types {
+ out = append(out, t)
+ }
+ slices.Sort(out)
+ return out
+}
+
+// Empty reports whether no geometry has been seen at all.
+func (b *Bounder) Empty() bool { return len(b.types) == 0 }
+
+// Update adds a single WKB-encoded geometry.
+func (b *Bounder) Update(wkb []byte) {
+ if b.invalid {
+ return
+ }
+
+ // a failed parse may have partially updated the bounds, but the
+ // invalid flag means they are never used.
+ r := reader{buf: wkb}
+ code, ok := b.readGeometry(&r, 0)
+ if !ok || len(r.buf) != 0 {
+ b.invalid = true
+ return
+ }
+ b.types[code] = struct{}{}
+}
+
+type reader struct {
+ buf []byte
+}
+
+func (r *reader) u8() (byte, bool) {
+ if len(r.buf) < 1 {
+ return 0, false
+ }
+ v := r.buf[0]
+ r.buf = r.buf[1:]
+ return v, true
+}
+
+func (r *reader) u32(order binary.ByteOrder) (uint32, bool) {
+ if len(r.buf) < 4 {
+ return 0, false
+ }
+ v := order.Uint32(r.buf)
+ r.buf = r.buf[4:]
+ return v, true
+}
+
+func (b *Bounder) readGeometry(r *reader, depth int) (isoCode int32, ok bool) {
+ if depth > maxNesting {
+ return 0, false
+ }
+
+ bo, ok := r.u8()
+ if !ok {
+ return 0, false
+ }
+ var order binary.ByteOrder
+ switch bo {
+ case 0:
+ order = binary.BigEndian
+ case 1:
+ order = binary.LittleEndian
+ default:
+ return 0, false
+ }
+
+ raw, ok := r.u32(order)
+ if !ok {
+ return 0, false
+ }
+
+ // accept both ISO (1000/2000/3000 offsets) and EWKB (high bit flags)
+ hasZ, hasM := raw&ewkbZ != 0, raw&ewkbM != 0
+ if raw&ewkbSRID != 0 {
+ if _, ok := r.u32(order); !ok {
+ return 0, false
+ }
+ }
+ code := raw &^ (ewkbZ | ewkbM | ewkbSRID)
+ switch code / 1000 {
+ case 0:
+ case 1:
+ hasZ = true
+ case 2:
+ hasM = true
+ case 3:
+ hasZ, hasM = true, true
+ default:
+ return 0, false
+ }
+ base := code % 1000
+
+ var dims [numDims]int
+ n := 0
+ dims[n], n = DimX, n+1
+ dims[n], n = DimY, n+1
+ if hasZ {
+ dims[n], n = DimZ, n+1
+ }
+ if hasM {
+ dims[n], n = DimM, n+1
+ }
+ ndims := dims[:n]
+
+ isoCode = int32(base)
+ if hasZ {
+ isoCode += 1000
+ }
+ if hasM {
+ isoCode += 2000
+ }
+
+ switch base {
+ case 1: // Point
+ return isoCode, b.readCoords(r, order, ndims, 1)
+ case 2: // LineString
+ cnt, ok := r.u32(order)
+ return isoCode, ok && b.readCoords(r, order, ndims, uint64(cnt))
+ case 3: // Polygon
+ rings, ok := r.u32(order)
+ if !ok || uint64(rings)*4 > uint64(len(r.buf)) {
+ return 0, false
+ }
+ for i := uint32(0); i < rings; i++ {
+ cnt, ok := r.u32(order)
+ if !ok || !b.readCoords(r, order, ndims, uint64(cnt)) {
+ return 0, false
+ }
+ }
+ return isoCode, true
+ case 4, 5, 6, 7: // Multi* and GeometryCollection
+ cnt, ok := r.u32(order)
+ // every child is at least 5 bytes
+ if !ok || uint64(cnt)*5 > uint64(len(r.buf)) {
+ return 0, false
+ }
+ for range cnt {
+ if _, ok := b.readGeometry(r, depth+1); !ok {
+ return 0, false
+ }
+ }
+ return isoCode, true
+ }
+ return 0, false
+}
+
+func (b *Bounder) readCoords(r *reader, order binary.ByteOrder, dims []int,
count uint64) bool {
+ size := uint64(len(dims)) * 8
+ if count*size > uint64(len(r.buf)) {
+ return false
+ }
+
+ for i := uint64(0); i < count; i++ {
+ for _, d := range dims {
+ v := math.Float64frombits(order.Uint64(r.buf))
+ r.buf = r.buf[8:]
+ // NaN ordinates are skipped rather than invalidating
the
+ // statistics: POINT EMPTY is encoded as all-NaN, and
one bad
+ // coordinate should not prevent pruning on the other
values.
+ if math.IsNaN(v) {
+ continue
+ }
+ b.min[d] = math.Min(b.min[d], v)
+ b.max[d] = math.Max(b.max[d], v)
+ }
+ }
+ return true
+}
diff --git a/parquet/internal/geospatial/bounder_test.go
b/parquet/internal/geospatial/bounder_test.go
new file mode 100644
index 00000000..1e0a4db1
--- /dev/null
+++ b/parquet/internal/geospatial/bounder_test.go
@@ -0,0 +1,510 @@
+// 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 geospatial_test
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+ "testing"
+
+ "github.com/apache/arrow-go/v18/parquet/internal/geospatial"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type byteOrder interface {
+ binary.ByteOrder
+ binary.AppendByteOrder
+}
+
+func wkb(order byteOrder, code uint32, parts ...any) []byte {
+ var out []byte
+ if order == byteOrder(binary.BigEndian) {
+ out = append(out, 0)
+ } else {
+ out = append(out, 1)
+ }
+ out = order.AppendUint32(out, code)
+ for _, p := range parts {
+ switch v := p.(type) {
+ case float64:
+ out = order.AppendUint64(out, math.Float64bits(v))
+ case uint32:
+ out = order.AppendUint32(out, v)
+ case []byte:
+ out = append(out, v...)
+ default:
+ // catch e.g. an untyped 0 that was meant to be 0.0
+ panic(fmt.Sprintf("wkb: unsupported part %T", p))
+ }
+ }
+ return out
+}
+
+func TestBounder(t *testing.T) {
+ le, be := byteOrder(binary.LittleEndian), byteOrder(binary.BigEndian)
+
+ b := geospatial.NewBounder()
+ assert.True(t, b.Empty())
+
+ b.Update(wkb(le, 1, -122.4, 37.8))
+ b.Update(wkb(be, 2, uint32(2), 10.0, -5.0, 20.0, 50.0))
+ assert.True(t, b.Valid())
+ assert.Equal(t, []int32{1, 2}, b.Types())
+ assert.Equal(t, -122.4, b.Min(geospatial.DimX))
+ assert.Equal(t, 20.0, b.Max(geospatial.DimX))
+ assert.Equal(t, -5.0, b.Min(geospatial.DimY))
+ assert.Equal(t, 50.0, b.Max(geospatial.DimY))
+ assert.False(t, b.HasDim(geospatial.DimZ))
+ assert.False(t, b.HasDim(geospatial.DimM))
+
+ // Z and M, polygon, and a nested collection
+ b.Update(wkb(le, 1003, uint32(1), uint32(2), 0.0, 0.0, 7.0, 1.0, 1.0,
-3.0))
+ b.Update(wkb(le, 2001, uint32(1), 0.0, 0.0)) // invalid: truncated
+ assert.False(t, b.Valid())
+
+ b = geospatial.NewBounder()
+ b.Update(wkb(le, 1003, uint32(1), uint32(2), 0.0, 0.0, 7.0, 1.0, 1.0,
-3.0))
+ b.Update(wkb(le, 2002, uint32(1), 0.0, 0.0, 4.0))
+ b.Update(wkb(le, 7, uint32(1), wkb(le, 1, 100.0, 1.0)))
+ assert.True(t, b.Valid())
+ assert.Equal(t, []int32{7, 1003, 2002}, b.Types())
+ assert.True(t, b.HasDim(geospatial.DimZ))
+ assert.Equal(t, -3.0, b.Min(geospatial.DimZ))
+ assert.Equal(t, 7.0, b.Max(geospatial.DimZ))
+ assert.Equal(t, 4.0, b.Min(geospatial.DimM))
+ assert.Equal(t, 100.0, b.Max(geospatial.DimX))
+
+ // EWKB Z flag normalizes to the ISO code
+ b = geospatial.NewBounder()
+ b.Update(wkb(le, 1|0x80000000, 1.0, 2.0, 3.0))
+ assert.Equal(t, []int32{1001}, b.Types())
+}
+
+func TestBounderEmptyPointAndInvalid(t *testing.T) {
+ le := byteOrder(binary.LittleEndian)
+ nan := math.NaN()
+
+ b := geospatial.NewBounder()
+ b.Update(wkb(le, 1, nan, nan))
+ assert.True(t, b.Valid())
+ assert.False(t, b.HasDim(geospatial.DimX))
+ assert.Equal(t, []int32{1}, b.Types())
+
+ for name, v := range map[string][]byte{
+ "empty": {},
+ "bad order": {2, 1, 0, 0, 0},
+ "truncated": wkb(le, 1, 1.0),
+ "trailing": append(wkb(le, 1, 1.0, 2.0), 0),
+ "bad type": wkb(le, 99, 1.0, 2.0),
+ "huge count": wkb(le, 2, uint32(math.MaxUint32)),
+ "huge rings": wkb(le, 3, uint32(math.MaxUint32)),
+ "huge children": wkb(le, 7, uint32(math.MaxUint32)),
+ } {
+ b := geospatial.NewBounder()
+ b.Update(v)
+ assert.False(t, b.Valid(), name)
+ }
+
+ // invalid is sticky until Reset
+ b = geospatial.NewBounder()
+ b.Update(nil)
+ assert.False(t, b.Valid())
+ b.Reset()
+ assert.True(t, b.Valid())
+}
+
+const (
+ ewkbZ = 0x80000000
+ ewkbM = 0x40000000
+ ewkbSRID = 0x20000000
+)
+
+// bounds is the expected extent of one dimension. A nil *bounds means the
+// dimension must be absent.
+type bounds struct{ min, max float64 }
+
+func assertDim(t *testing.T, b *geospatial.Bounder, dim int, want *bounds, msg
string) {
+ t.Helper()
+ if want == nil {
+ assert.False(t, b.HasDim(dim), "%s: dim %d should be absent",
msg, dim)
+ return
+ }
+ if assert.True(t, b.HasDim(dim), "%s: dim %d should be present", msg,
dim) {
+ assert.Equal(t, *want, bounds{b.Min(dim), b.Max(dim)}, "%s: dim
%d", msg, dim)
+ }
+}
+
+func TestBounderGeometryTypes(t *testing.T) {
+ for _, order := range []byteOrder{binary.LittleEndian,
binary.BigEndian} {
+ o := order
+ tests := []struct {
+ name string
+ wkb []byte
+ types []int32
+ x, y bounds
+ }{
+ {
+ name: "Point", types: []int32{1},
+ wkb: wkb(o, 1, 1.5, -2.5),
+ x: bounds{1.5, 1.5}, y: bounds{-2.5, -2.5},
+ },
+ {
+ name: "LineString", types: []int32{2},
+ wkb: wkb(o, 2, uint32(3), 0.0, 0.0, 10.0, -1.0,
5.0, 20.0),
+ x: bounds{0, 10}, y: bounds{-1, 20},
+ },
+ {
+ // the hole is inside the shell, so only the
shell sets the extent
+ name: "Polygon with hole", types: []int32{3},
+ wkb: wkb(o, 3, uint32(2),
+ uint32(5), 0.0, 0.0, 10.0, 0.0, 10.0,
10.0, 0.0, 10.0, 0.0, 0.0,
+ uint32(4), 2.0, 2.0, 3.0, 2.0, 3.0,
3.0, 2.0, 2.0),
+ x: bounds{0, 10}, y: bounds{0, 10},
+ },
+ {
+ name: "MultiPoint", types: []int32{4},
+ wkb: wkb(o, 4, uint32(2), wkb(o, 1, -1.0,
-1.0), wkb(o, 1, 1.0, 1.0)),
+ x: bounds{-1, 1}, y: bounds{-1, 1},
+ },
+ {
+ name: "MultiLineString", types: []int32{5},
+ wkb: wkb(o, 5, uint32(2),
+ wkb(o, 2, uint32(2), 0.0, 0.0, 1.0,
1.0),
+ wkb(o, 2, uint32(2), 5.0, 5.0, 6.0,
-6.0)),
+ x: bounds{0, 6}, y: bounds{-6, 5},
+ },
+ {
+ name: "MultiPolygon", types: []int32{6},
+ wkb: wkb(o, 6, uint32(2),
+ wkb(o, 3, uint32(1), uint32(4), 0.0,
0.0, 4.0, 0.0, 4.0, 4.0, 0.0, 0.0),
+ wkb(o, 3, uint32(1), uint32(4), -8.0,
-8.0, -7.0, -8.0, -7.0, -7.0, -8.0, -8.0)),
+ x: bounds{-8, 4}, y: bounds{-8, 4},
+ },
+ {
+ name: "GeometryCollection", types: []int32{7},
+ wkb: wkb(o, 7, uint32(2),
+ wkb(o, 1, 9.0, 9.0),
+ wkb(o, 2, uint32(2), -9.0, 0.0, 0.0,
0.0)),
+ x: bounds{-9, 9}, y: bounds{0, 9},
+ },
+ }
+
+ for _, tt := range tests {
+ name := fmt.Sprintf("%s/%v", tt.name, order)
+ b := geospatial.NewBounder()
+ b.Update(tt.wkb)
+ require.True(t, b.Valid(), name)
+ assert.Equal(t, tt.types, b.Types(), name)
+ assertDim(t, b, geospatial.DimX, &tt.x, name)
+ assertDim(t, b, geospatial.DimY, &tt.y, name)
+ assertDim(t, b, geospatial.DimZ, nil, name)
+ assertDim(t, b, geospatial.DimM, nil, name)
+ }
+ }
+}
+
+func TestBounderDimensions(t *testing.T) {
+ le, be := byteOrder(binary.LittleEndian), byteOrder(binary.BigEndian)
+
+ tests := []struct {
+ name string
+ wkb []byte
+ types []int32
+ z, m *bounds
+ }{
+ {
+ name: "ISO Point Z", types: []int32{1001},
+ wkb: wkb(le, 1001, 1.0, 2.0, 3.0),
+ z: &bounds{3, 3},
+ },
+ {
+ // the third ordinate of an M geometry is M, not Z
+ name: "ISO Point M", types: []int32{2001},
+ wkb: wkb(le, 2001, 1.0, 2.0, 3.0),
+ m: &bounds{3, 3},
+ },
+ {
+ name: "ISO Point ZM", types: []int32{3001},
+ wkb: wkb(le, 3001, 1.0, 2.0, 3.0, 4.0),
+ z: &bounds{3, 3}, m: &bounds{4, 4},
+ },
+ {
+ name: "ISO LineString ZM", types: []int32{3002},
+ wkb: wkb(be, 3002, uint32(2), 0.0, 0.0, -1.0, 10.0,
1.0, 1.0, 1.0, 20.0),
+ z: &bounds{-1, 1}, m: &bounds{10, 20},
+ },
+ {
+ name: "EWKB M flag", types: []int32{2001},
+ wkb: wkb(le, 1|ewkbM, 1.0, 2.0, 5.0),
+ m: &bounds{5, 5},
+ },
+ {
+ name: "EWKB Z and M flags", types: []int32{3001},
+ wkb: wkb(le, 1|ewkbZ|ewkbM, 1.0, 2.0, 3.0, 4.0),
+ z: &bounds{3, 3}, m: &bounds{4, 4},
+ },
+ {
+ name: "EWKB Z flag on LineString", types: []int32{1002},
+ wkb: wkb(be, 2|ewkbZ, uint32(1), 1.0, 2.0, 3.0),
+ z: &bounds{3, 3},
+ },
+ {
+ // the SRID is skipped and must not be read as a
coordinate
+ name: "EWKB SRID", types: []int32{1},
+ wkb: wkb(le, 1|ewkbSRID, uint32(4326), 1.0, 2.0),
+ },
+ {
+ name: "EWKB SRID and Z", types: []int32{1001},
+ wkb: wkb(le, 1|ewkbZ|ewkbSRID, uint32(4326), 1.0, 2.0,
3.0),
+ z: &bounds{3, 3},
+ },
+ {
+ // an EWKB flag on an ISO Z code adds nothing new
+ name: "EWKB Z flag on ISO Z code", types: []int32{1001},
+ wkb: wkb(le, 1001|ewkbZ, 1.0, 2.0, 3.0),
+ z: &bounds{3, 3},
+ },
+ {
+ // only the top-level type is recorded, but nested Z
+ // coordinates still count towards the Z bounds
+ name: "Point Z inside 2D collection", types: []int32{7},
+ wkb: wkb(le, 7, uint32(1), wkb(le, 1001, 1.0, 2.0,
3.0)),
+ z: &bounds{3, 3},
+ },
+ }
+
+ for _, tt := range tests {
+ b := geospatial.NewBounder()
+ b.Update(tt.wkb)
+ require.True(t, b.Valid(), tt.name)
+ assert.Equal(t, tt.types, b.Types(), tt.name)
+ assert.True(t, b.HasDim(geospatial.DimX), tt.name)
+ assertDim(t, b, geospatial.DimZ, tt.z, tt.name)
+ assertDim(t, b, geospatial.DimM, tt.m, tt.name)
+ }
+}
+
+func TestBounderEmptyGeometries(t *testing.T) {
+ le := byteOrder(binary.LittleEndian)
+ nan := math.NaN()
+
+ // each is valid and records its type, but has no extent
+ for _, tt := range []struct {
+ name string
+ wkb []byte
+ types []int32
+ }{
+ {"LineString EMPTY", wkb(le, 2, uint32(0)), []int32{2}},
+ {"Polygon EMPTY", wkb(le, 3, uint32(0)), []int32{3}},
+ {"Polygon with an empty ring", wkb(le, 3, uint32(1),
uint32(0)), []int32{3}},
+ {"MultiPoint EMPTY", wkb(le, 4, uint32(0)), []int32{4}},
+ {"MultiPolygon EMPTY", wkb(le, 6, uint32(0)), []int32{6}},
+ {"GeometryCollection EMPTY", wkb(le, 7, uint32(0)), []int32{7}},
+ {"Point Z EMPTY", wkb(le, 1001, nan, nan, nan), []int32{1001}},
+ {"Point ZM EMPTY", wkb(le, 3001, nan, nan, nan, nan),
[]int32{3001}},
+ {"MultiPoint of POINT EMPTY", wkb(le, 4, uint32(1), wkb(le, 1,
nan, nan)), []int32{4}},
+ } {
+ b := geospatial.NewBounder()
+ b.Update(tt.wkb)
+ require.True(t, b.Valid(), tt.name)
+ assert.False(t, b.Empty(), tt.name)
+ assert.Equal(t, tt.types, b.Types(), tt.name)
+ for dim := range 4 {
+ assertDim(t, b, dim, nil, tt.name)
+ }
+ }
+
+ // an empty point next to a real one adds nothing to the extent
+ b := geospatial.NewBounder()
+ b.Update(wkb(le, 4, uint32(2), wkb(le, 1, nan, nan), wkb(le, 1, 3.0,
4.0)))
+ require.True(t, b.Valid())
+ assertDim(t, b, geospatial.DimX, &bounds{3, 3}, "mixed")
+ assertDim(t, b, geospatial.DimY, &bounds{4, 4}, "mixed")
+}
+
+func TestBounderSkipsNaN(t *testing.T) {
+ le := byteOrder(binary.LittleEndian)
+ nan := math.NaN()
+
+ // NaN ordinates are ignored per dimension: they never reach the bounds
+ // and never invalidate the Bounder.
+ for _, tt := range []struct {
+ name string
+ wkb []byte
+ types []int32
+ x, y, z, m *bounds
+ }{
+ {"all-NaN LineString", wkb(le, 2, uint32(2), nan, nan, nan,
nan), []int32{2}, nil, nil, nil, nil},
+ {"NaN point in LineString", wkb(le, 2, uint32(2), nan, nan,
1.0, 2.0), []int32{2}, &bounds{1, 1}, &bounds{2, 2}, nil, nil},
+ {"NaN X only", wkb(le, 1, nan, 5.0), []int32{1}, nil,
&bounds{5, 5}, nil, nil},
+ {"NaN in Polygon ring", wkb(le, 3, uint32(1), uint32(2), 1.0,
nan, 3.0, 4.0), []int32{3}, &bounds{1, 3}, &bounds{4, 4}, nil, nil},
+ {"NaN only in Z", wkb(le, 1001, 1.0, 2.0, nan), []int32{1001},
&bounds{1, 1}, &bounds{2, 2}, nil, nil},
+ {"NaN only in M", wkb(le, 3001, 1.0, 2.0, 3.0, nan),
[]int32{3001}, &bounds{1, 1}, &bounds{2, 2}, &bounds{3, 3}, nil},
+ {"partial NaN child", wkb(le, 4, uint32(1), wkb(le, 1, nan,
1.0)), []int32{4}, nil, &bounds{1, 1}, nil, nil},
+ } {
+ b := geospatial.NewBounder()
+ b.Update(tt.wkb)
+ require.True(t, b.Valid(), tt.name)
+ assert.Equal(t, tt.types, b.Types(), tt.name)
+ assertDim(t, b, geospatial.DimX, tt.x, tt.name)
+ assertDim(t, b, geospatial.DimY, tt.y, tt.name)
+ assertDim(t, b, geospatial.DimZ, tt.z, tt.name)
+ assertDim(t, b, geospatial.DimM, tt.m, tt.name)
+ }
+
+ // a geometry that is entirely NaN does not stop the others from
+ // contributing to the bounds
+ b := geospatial.NewBounder()
+ b.Update(wkb(le, 1, 10.0, 20.0))
+ b.Update(wkb(le, 2, uint32(2), nan, nan, nan, nan))
+ b.Update(wkb(le, 1, 30.0, 40.0))
+ require.True(t, b.Valid())
+ assert.Equal(t, []int32{1, 2}, b.Types())
+ assertDim(t, b, geospatial.DimX, &bounds{10, 30}, "mixed")
+ assertDim(t, b, geospatial.DimY, &bounds{20, 40}, "mixed")
+}
+
+func TestBounderInvalidEdgeCases(t *testing.T) {
+ le := byteOrder(binary.LittleEndian)
+
+ for name, v := range map[string][]byte{
+ "Point with extra coord": wkb(le, 1, 1.0, 2.0, 3.0),
+ "Point Z missing Z": wkb(le, 1001, 1.0, 2.0),
+
+ // unsupported type codes
+ "type 0 (Geometry)": wkb(le, 0, 1.0, 2.0),
+ "type 8": wkb(le, 8, uint32(0)),
+ "type 15 (PolyhedralSurface)": wkb(le, 15, uint32(0)),
+ "type 17 (TIN)": wkb(le, 17, uint32(0)),
+ "dimension offset 4000": wkb(le, 4001, 1.0, 2.0),
+
+ // headers and counts
+ "only byte order": {1},
+ "truncated type": {1, 1, 0},
+ "truncated SRID": append(wkb(le, 1|ewkbSRID), 0xE6,
0x10),
+ "missing count": wkb(le, 2),
+ "huge ring point count": wkb(le, 3, uint32(1),
uint32(math.MaxUint32)),
+ "huge MultiPoint count": wkb(le, 4, uint32(math.MaxUint32)),
+ "fewer points than count": wkb(le, 2, uint32(3), 0.0, 0.0, 1.0,
1.0),
+ "fewer rings than count": wkb(le, 3, uint32(2), uint32(1),
0.0, 0.0),
+
+ // problems inside a child
+ "truncated child": wkb(le, 7, uint32(1), wkb(le, 1,
1.0)),
+ "fewer children than count": wkb(le, 7, uint32(2), wkb(le, 1,
1.0, 1.0)),
+ "bad child byte order": wkb(le, 7, uint32(1),
[]byte{0xFF}, wkb(le, 1, 1.0, 1.0)[1:]),
+ "bad child type": wkb(le, 7, uint32(1), wkb(le, 99,
1.0, 1.0)),
+ "trailing after children": append(wkb(le, 7, uint32(1),
wkb(le, 1, 1.0, 1.0)), 0),
+ } {
+ b := geospatial.NewBounder()
+ b.Update(v)
+ assert.False(t, b.Valid(), name)
+ }
+}
+
+func TestBounderMixedByteOrders(t *testing.T) {
+ le, be := byteOrder(binary.LittleEndian), byteOrder(binary.BigEndian)
+
+ // each child declares its own byte order
+ b := geospatial.NewBounder()
+ b.Update(wkb(be, 4, uint32(2), wkb(le, 1, 1.0, -1.0), wkb(be, 1, 2.0,
-2.0)))
+ require.True(t, b.Valid())
+ assert.Equal(t, []int32{4}, b.Types())
+ assertDim(t, b, geospatial.DimX, &bounds{1, 2}, "x")
+ assertDim(t, b, geospatial.DimY, &bounds{-2, -1}, "y")
+}
+
+func TestBounderEveryTruncationIsInvalid(t *testing.T) {
+ le, be := byteOrder(binary.LittleEndian), byteOrder(binary.BigEndian)
+
+ full := wkb(le, 7, uint32(3),
+ wkb(be, 3, uint32(1), uint32(4), 0.0, 0.0, 1.0, 0.0, 1.0, 1.0,
0.0, 0.0),
+ wkb(le, 1002, uint32(2), 0.0, 0.0, 0.0, 1.0, 1.0, 1.0),
+ wkb(le, 1|ewkbSRID, uint32(4326), 5.0, 5.0))
+
+ b := geospatial.NewBounder()
+ b.Update(full)
+ require.True(t, b.Valid())
+
+ for n := range len(full) {
+ b := geospatial.NewBounder()
+ b.Update(full[:n])
+ assert.False(t, b.Valid(), "prefix of %d/%d bytes", n,
len(full))
+ }
+}
+
+func TestBounderNestingDepth(t *testing.T) {
+ le := byteOrder(binary.LittleEndian)
+
+ // a point wrapped in n single-element collections
+ nested := func(n int) []byte {
+ g := wkb(le, 1, 1.0, 2.0)
+ for range n {
+ g = wkb(le, 7, uint32(1), g)
+ }
+ return g
+ }
+
+ b := geospatial.NewBounder()
+ b.Update(nested(64))
+ assert.True(t, b.Valid(), "64 levels of nesting is the limit")
+ assertDim(t, b, geospatial.DimX, &bounds{1, 1}, "x")
+
+ b = geospatial.NewBounder()
+ b.Update(nested(65))
+ assert.False(t, b.Valid(), "65 levels of nesting is too deep")
+}
+
+func TestBounderAccumulation(t *testing.T) {
+ le := byteOrder(binary.LittleEndian)
+
+ // types are deduplicated and sorted, bounds cover every value
+ b := geospatial.NewBounder()
+ b.Update(wkb(le, 1001, 5.0, 5.0, 5.0))
+ b.Update(wkb(le, 1, -1.0, 0.0))
+ b.Update(wkb(le, 7, uint32(0)))
+ b.Update(wkb(le, 1, 10.0, 0.0))
+ require.True(t, b.Valid())
+ assert.Equal(t, []int32{1, 7, 1001}, b.Types())
+ assertDim(t, b, geospatial.DimX, &bounds{-1, 10}, "x")
+ assertDim(t, b, geospatial.DimZ, &bounds{5, 5}, "z")
+
+ // once invalid, later values are ignored
+ types := b.Types()
+ b.Update([]byte("not wkb"))
+ b.Update(wkb(le, 2, uint32(1), 100.0, 100.0))
+ assert.False(t, b.Valid())
+ assert.Equal(t, types, b.Types())
+}
+
+func TestNewBounderFrom(t *testing.T) {
+ inf := math.Inf(1)
+ min := [4]float64{0, 1, inf, 7}
+ max := [4]float64{10, 2, -inf, 7}
+
+ b := geospatial.NewBounderFrom(min, max, []int32{3001, 1, 1})
+ assert.True(t, b.Valid())
+ assert.False(t, b.Empty())
+ assert.Equal(t, []int32{1, 3001}, b.Types())
+ assertDim(t, b, geospatial.DimX, &bounds{0, 10}, "x")
+ assertDim(t, b, geospatial.DimY, &bounds{1, 2}, "y")
+ assertDim(t, b, geospatial.DimZ, nil, "z (min > max)")
+ assertDim(t, b, geospatial.DimM, &bounds{7, 7}, "m (min == max)")
+
+ assert.True(t, geospatial.NewBounderFrom(min, max, nil).Empty())
+}
diff --git a/parquet/metadata/column_chunk.go b/parquet/metadata/column_chunk.go
index c5ae5029..436b9c4a 100644
--- a/parquet/metadata/column_chunk.go
+++ b/parquet/metadata/column_chunk.go
@@ -260,6 +260,24 @@ func (c *ColumnChunkMetaData) StatsSet() (bool, error) {
return c.writerVersion.HasCorrectStatistics(c.Type(),
c.descr.LogicalType(), encoded, c.descr.SortOrder()), nil
}
+// GeoStatistics returns the geospatial statistics (bounding box and geometry
+// types) of a GEOMETRY column chunk, or nil if the writer did not record any.
+//
+// It always returns nil for GEOGRAPHY columns, even if the file has statistics
+// for them. Their edges follow the Earth's surface and their bounding boxes
may
+// wrap across the antimeridian (xmin > xmax), which GeoStatistics does not
+// represent.
+func (c *ColumnChunkMetaData) GeoStatistics() *GeoStatistics {
+ if _, ok := c.descr.LogicalType().(schema.GeometryLogicalType); !ok {
+ return nil
+ }
+ t := c.columnMeta.GetGeospatialStatistics()
+ if t == nil {
+ return nil
+ }
+ return geoStatisticsFromThrift(t)
+}
+
func (c *ColumnChunkMetaData) Equals(other *ColumnChunkMetaData) bool {
return reflect.DeepEqual(c.columnMeta, other.columnMeta)
}
@@ -349,6 +367,14 @@ func (c *ColumnChunkMetaDataBuilder) SetStats(val
EncodedStatistics) {
c.chunk.MetaData.Statistics = val.ToThrift()
}
+// SetGeoStatistics records the geospatial statistics for the chunk. Nothing is
+// written if the statistics are invalid or no geometry was written.
+func (c *ColumnChunkMetaDataBuilder) SetGeoStatistics(val *GeoStatistics) {
+ if t := val.toThrift(); t != nil {
+ c.chunk.MetaData.GeospatialStatistics = t
+ }
+}
+
// ChunkMetaInfo is a helper struct for passing the offset and size information
// for finishing the building of column chunk metadata
type ChunkMetaInfo struct {
@@ -474,6 +500,7 @@ func (c *ColumnChunkMetaDataBuilder)
PopulateCryptoData(encryptor encryption.Enc
// Keep redacted metadata version for old
readers
c.chunk.MetaData.Statistics = nil
c.chunk.MetaData.EncodingStats = nil
+ c.chunk.MetaData.GeospatialStatistics = nil
}
}
}
diff --git a/parquet/metadata/geo_statistics.go
b/parquet/metadata/geo_statistics.go
new file mode 100644
index 00000000..aadf550e
--- /dev/null
+++ b/parquet/metadata/geo_statistics.go
@@ -0,0 +1,158 @@
+// 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 metadata
+
+import (
+ "math"
+
+ "github.com/apache/arrow-go/v18/internal/bitutils"
+ "github.com/apache/arrow-go/v18/parquet"
+ format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
+ "github.com/apache/arrow-go/v18/parquet/internal/geospatial"
+)
+
+// GeoStatistics holds the geospatial statistics of a GEOMETRY column chunk:
+// the bounding box of all coordinates and the set of geometry types (as ISO
+// WKB codes, e.g. 1 = Point, 1002 = LineString Z) that were written.
+//
+// NaN coordinates are ignored. If any value was not valid WKB, the statistics
+// are invalid and are never written to the file.
+type GeoStatistics struct {
+ b *geospatial.Bounder
+}
+
+// NewGeoStatistics returns empty, valid geospatial statistics.
+func NewGeoStatistics() *GeoStatistics {
+ return &GeoStatistics{b: geospatial.NewBounder()}
+}
+
+// Invalidate marks the statistics as unusable, e.g. when values were written
+// without being inspected.
+func (g *GeoStatistics) Invalidate() { g.b.Invalidate() }
+
+// Valid reports whether the statistics can be trusted.
+func (g *GeoStatistics) Valid() bool { return g.b.Valid() }
+
+// IsEmpty reports whether no non-null geometry was seen.
+func (g *GeoStatistics) IsEmpty() bool { return g.b.Empty() }
+
+// HasBoundingBox reports whether any coordinate was seen. It is false for,
+// e.g., a chunk consisting only of empty points.
+func (g *GeoStatistics) HasBoundingBox() bool { return
g.b.HasDim(geospatial.DimX) }
+
+// XMin, XMax, YMin and YMax are the bounds of the X and Y coordinates, only
+// meaningful if HasBoundingBox is true.
+func (g *GeoStatistics) XMin() float64 { return g.b.Min(geospatial.DimX) }
+func (g *GeoStatistics) XMax() float64 { return g.b.Max(geospatial.DimX) }
+func (g *GeoStatistics) YMin() float64 { return g.b.Min(geospatial.DimY) }
+func (g *GeoStatistics) YMax() float64 { return g.b.Max(geospatial.DimY) }
+
+// HasZ and HasM report whether any Z or M coordinates were seen.
+func (g *GeoStatistics) HasZ() bool { return g.b.HasDim(geospatial.DimZ) }
+func (g *GeoStatistics) HasM() bool { return g.b.HasDim(geospatial.DimM) }
+
+// ZMin, ZMax, MMin and MMax are only meaningful if HasZ/HasM is true.
+func (g *GeoStatistics) ZMin() float64 { return g.b.Min(geospatial.DimZ) }
+func (g *GeoStatistics) ZMax() float64 { return g.b.Max(geospatial.DimZ) }
+func (g *GeoStatistics) MMin() float64 { return g.b.Min(geospatial.DimM) }
+func (g *GeoStatistics) MMax() float64 { return g.b.Max(geospatial.DimM) }
+
+// GeometryTypes returns the sorted ISO WKB geometry type codes that were seen.
+func (g *GeoStatistics) GeometryTypes() []int32 { return g.b.Types() }
+
+// Update adds a slice of non-null WKB values.
+func (g *GeoStatistics) Update(values []parquet.ByteArray) {
+ for _, v := range values {
+ g.b.Update(v)
+ }
+}
+
+// UpdateSpaced adds values where validBits marks which entries are non-null.
+func (g *GeoStatistics) UpdateSpaced(values []parquet.ByteArray, validBits
[]byte, validBitsOffset int64) {
+ if validBits == nil {
+ g.Update(values)
+ return
+ }
+ bitutils.VisitSetBitRunsNoErr(validBits, validBitsOffset,
int64(len(values)), func(pos, length int64) {
+ g.Update(values[pos : pos+length])
+ })
+}
+
+// UpdateGeoStatisticsFromArrowOffsets adds the values described by an Arrow
value buffer
+// and offsets (32 or 64-bit). validBits may be nil if there are no nulls.
+func UpdateGeoStatisticsFromArrowOffsets[T ~int32 | ~int64](g *GeoStatistics,
values []byte, offsets []T, validBits []byte, validBitsOffset int64) {
+ if len(offsets) < 2 {
+ return
+ }
+ n := int64(len(offsets) - 1)
+ visit := func(pos, length int64) {
+ for i := pos; i < pos+length; i++ {
+ g.b.Update(values[offsets[i]:offsets[i+1]])
+ }
+ }
+ if validBits == nil {
+ visit(0, n)
+ return
+ }
+ bitutils.VisitSetBitRunsNoErr(validBits, validBitsOffset, n, visit)
+}
+
+// toThrift returns the thrift form, or nil if the statistics are invalid or
+// nothing was written.
+func (g *GeoStatistics) toThrift() *format.GeospatialStatistics {
+ if !g.Valid() || g.IsEmpty() {
+ return nil
+ }
+
+ ret := format.NewGeospatialStatistics()
+ ret.GeospatialTypes = g.GeometryTypes()
+ if !g.HasBoundingBox() {
+ return ret
+ }
+
+ bbox := format.NewBoundingBox()
+ bbox.Xmin, bbox.Xmax = g.XMin(), g.XMax()
+ bbox.Ymin, bbox.Ymax = g.YMin(), g.YMax()
+ if g.HasZ() {
+ zmin, zmax := g.ZMin(), g.ZMax()
+ bbox.Zmin, bbox.Zmax = &zmin, &zmax
+ }
+ if g.HasM() {
+ mmin, mmax := g.MMin(), g.MMax()
+ bbox.Mmin, bbox.Mmax = &mmin, &mmax
+ }
+ ret.Bbox = bbox
+ return ret
+}
+
+func geoStatisticsFromThrift(t *format.GeospatialStatistics) *GeoStatistics {
+ var min, max [4]float64
+ for i := range min {
+ min[i], max[i] = math.Inf(1), math.Inf(-1)
+ }
+ if bb := t.GetBbox(); bb != nil {
+ min[geospatial.DimX], max[geospatial.DimX] = bb.GetXmin(),
bb.GetXmax()
+ min[geospatial.DimY], max[geospatial.DimY] = bb.GetYmin(),
bb.GetYmax()
+ if bb.IsSetZmin() && bb.IsSetZmax() {
+ min[geospatial.DimZ], max[geospatial.DimZ] =
bb.GetZmin(), bb.GetZmax()
+ }
+ if bb.IsSetMmin() && bb.IsSetMmax() {
+ min[geospatial.DimM], max[geospatial.DimM] =
bb.GetMmin(), bb.GetMmax()
+ }
+ }
+ return &GeoStatistics{b: geospatial.NewBounderFrom(min, max,
t.GetGeospatialTypes())}
+}
diff --git a/parquet/metadata/geo_statistics_test.go
b/parquet/metadata/geo_statistics_test.go
new file mode 100644
index 00000000..3a379682
--- /dev/null
+++ b/parquet/metadata/geo_statistics_test.go
@@ -0,0 +1,305 @@
+// 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 metadata
+
+import (
+ "encoding/binary"
+ "math"
+ "testing"
+
+ "github.com/apache/arrow-go/v18/arrow/memory"
+ "github.com/apache/arrow-go/v18/parquet"
+ "github.com/apache/arrow-go/v18/parquet/internal/encryption"
+ "github.com/apache/arrow-go/v18/parquet/schema"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// wkbPoint encodes a little-endian ISO WKB point with the given type code
+// (1 = XY, 1001 = XYZ, 2001 = XYM, 3001 = XYZM) and coordinates.
+func wkbPoint(code uint32, coords ...float64) parquet.ByteArray {
+ out := []byte{1}
+ out = binary.LittleEndian.AppendUint32(out, code)
+ for _, c := range coords {
+ out = binary.LittleEndian.AppendUint64(out, math.Float64bits(c))
+ }
+ return out
+}
+
+func newGeoStats(values ...parquet.ByteArray) *GeoStatistics {
+ g := NewGeoStatistics()
+ g.Update(values)
+ return g
+}
+
+// assertSameGeoStats checks that every accessor of got matches want.
+func assertSameGeoStats(t *testing.T, want, got *GeoStatistics) {
+ t.Helper()
+ assert.Equal(t, want.Valid(), got.Valid(), "Valid")
+ assert.Equal(t, want.IsEmpty(), got.IsEmpty(), "IsEmpty")
+ assert.Equal(t, want.GeometryTypes(), got.GeometryTypes(),
"GeometryTypes")
+ require.Equal(t, want.HasBoundingBox(), got.HasBoundingBox(),
"HasBoundingBox")
+ if want.HasBoundingBox() {
+ assert.Equal(t, []float64{want.XMin(), want.XMax(),
want.YMin(), want.YMax()},
+ []float64{got.XMin(), got.XMax(), got.YMin(),
got.YMax()}, "XY bounds")
+ }
+ require.Equal(t, want.HasZ(), got.HasZ(), "HasZ")
+ if want.HasZ() {
+ assert.Equal(t, []float64{want.ZMin(), want.ZMax()},
[]float64{got.ZMin(), got.ZMax()}, "Z bounds")
+ }
+ require.Equal(t, want.HasM(), got.HasM(), "HasM")
+ if want.HasM() {
+ assert.Equal(t, []float64{want.MMin(), want.MMax()},
[]float64{got.MMin(), got.MMax()}, "M bounds")
+ }
+}
+
+func ptr(v float64) *float64 { return &v }
+
+func TestGeoStatisticsThriftRoundTrip(t *testing.T) {
+ tests := []struct {
+ name string
+ values []parquet.ByteArray
+ types []int32
+ xy [4]float64 // xmin, xmax, ymin, ymax
+ zmin, zmax *float64
+ mmin, mmax *float64
+ }{
+ {
+ name: "XY",
+ values: []parquet.ByteArray{wkbPoint(1, -1, 10),
wkbPoint(1, 3, -2)},
+ types: []int32{1},
+ xy: [4]float64{-1, 3, -2, 10},
+ },
+ {
+ name: "XYZ",
+ values: []parquet.ByteArray{wkbPoint(1001, 1, 2, 30),
wkbPoint(1001, 4, 5, -6)},
+ types: []int32{1001},
+ xy: [4]float64{1, 4, 2, 5},
+ zmin: ptr(-6), zmax: ptr(30),
+ },
+ {
+ name: "XYM",
+ values: []parquet.ByteArray{wkbPoint(2001, 1, 2, 7),
wkbPoint(2001, 0, 0, 9)},
+ types: []int32{2001},
+ xy: [4]float64{0, 1, 0, 2},
+ mmin: ptr(7), mmax: ptr(9),
+ },
+ {
+ name: "XYZM",
+ values: []parquet.ByteArray{wkbPoint(3001, 1, 2, 3, 4),
wkbPoint(3001, 5, 6, 7, 8)},
+ types: []int32{3001},
+ xy: [4]float64{1, 5, 2, 6},
+ zmin: ptr(3), zmax: ptr(7),
+ mmin: ptr(4), mmax: ptr(8),
+ },
+ {
+ // Z bounds come only from the Z point, the XY point
still
+ // contributes to the XY bounds.
+ name: "mixed XY and XYZ",
+ values: []parquet.ByteArray{wkbPoint(1, 100, 100),
wkbPoint(1001, 1, 2, 3)},
+ types: []int32{1, 1001},
+ xy: [4]float64{1, 100, 2, 100},
+ zmin: ptr(3), zmax: ptr(3),
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ g := newGeoStats(tt.values...)
+
+ th := g.toThrift()
+ require.NotNil(t, th)
+ assert.Equal(t, tt.types, th.GetGeospatialTypes())
+ bb := th.GetBbox()
+ require.NotNil(t, bb)
+ assert.Equal(t, tt.xy, [4]float64{bb.GetXmin(),
bb.GetXmax(), bb.GetYmin(), bb.GetYmax()})
+ assert.Equal(t, tt.zmin, bb.Zmin)
+ assert.Equal(t, tt.zmax, bb.Zmax)
+ assert.Equal(t, tt.mmin, bb.Mmin)
+ assert.Equal(t, tt.mmax, bb.Mmax)
+
+ assertSameGeoStats(t, g, geoStatisticsFromThrift(th))
+ })
+ }
+}
+
+func TestGeoStatisticsOnlyEmptyPoints(t *testing.T) {
+ // POINT EMPTY is encoded with NaN coordinates. It records a geometry
type
+ // but contributes no extent, so the thrift form has types and no bbox.
+ g := newGeoStats(wkbPoint(1, math.NaN(), math.NaN()))
+ assert.False(t, g.IsEmpty())
+ assert.False(t, g.HasBoundingBox())
+
+ th := g.toThrift()
+ require.NotNil(t, th)
+ assert.Equal(t, []int32{1}, th.GetGeospatialTypes())
+ assert.Nil(t, th.GetBbox())
+
+ back := geoStatisticsFromThrift(th)
+ assertSameGeoStats(t, g, back)
+}
+
+func TestGeoStatisticsToThriftOmitted(t *testing.T) {
+ t.Run("nothing written", func(t *testing.T) {
+ g := NewGeoStatistics()
+ assert.True(t, g.Valid())
+ assert.True(t, g.IsEmpty())
+ assert.Nil(t, g.toThrift())
+ })
+
+ t.Run("invalid WKB", func(t *testing.T) {
+ g := newGeoStats(wkbPoint(1, 1, 2), parquet.ByteArray("not
wkb"))
+ assert.False(t, g.Valid())
+ assert.Nil(t, g.toThrift())
+ })
+
+ t.Run("invalidated", func(t *testing.T) {
+ g := newGeoStats(wkbPoint(1, 1, 2))
+ g.Invalidate()
+ assert.False(t, g.Valid())
+ assert.Nil(t, g.toThrift())
+ })
+}
+
+func TestGeoStatisticsNaNIgnored(t *testing.T) {
+ // NaN ordinates are left out of the bounds rather than invalidating the
+ // statistics, so the other values can still be used for pruning.
+ g := newGeoStats(wkbPoint(1, 1, 2), wkbPoint(1, math.NaN(), 10),
wkbPoint(1, 3, 4))
+ require.True(t, g.Valid())
+ assert.Equal(t, []float64{1, 3, 2, 10}, []float64{g.XMin(), g.XMax(),
g.YMin(), g.YMax()})
+
+ th := g.toThrift()
+ require.NotNil(t, th)
+ bb := th.GetBbox()
+ require.NotNil(t, bb)
+ assert.Equal(t, []float64{1, 3, 2, 10}, []float64{bb.Xmin, bb.Xmax,
bb.Ymin, bb.Ymax})
+}
+
+func TestGeoStatisticsUpdateSpaced(t *testing.T) {
+ // The null slots hold bytes that are not WKB, so the statistics would
+ // become invalid if they were read.
+ garbage := parquet.ByteArray("garbage")
+ values := []parquet.ByteArray{wkbPoint(1, 1, 2), garbage, wkbPoint(1,
3, 4), garbage}
+ want := newGeoStats(wkbPoint(1, 1, 2), wkbPoint(1, 3, 4))
+
+ t.Run("no offset", func(t *testing.T) {
+ g := NewGeoStatistics()
+ g.UpdateSpaced(values, []byte{0b0101}, 0)
+ assertSameGeoStats(t, want, g)
+ })
+
+ t.Run("with offset", func(t *testing.T) {
+ // the same validity, starting at bit 3
+ g := NewGeoStatistics()
+ g.UpdateSpaced(values, []byte{0b0101 << 3}, 3)
+ assertSameGeoStats(t, want, g)
+ })
+
+ t.Run("nil validity", func(t *testing.T) {
+ g := NewGeoStatistics()
+ g.UpdateSpaced(values[:1], nil, 0)
+ assertSameGeoStats(t, newGeoStats(wkbPoint(1, 1, 2)), g)
+ })
+}
+
+func convertOffsets[T ~int32 | ~int64](offsets []int) []T {
+ out := make([]T, len(offsets))
+ for i, o := range offsets {
+ out[i] = T(o)
+ }
+ return out
+}
+
+// testArrowOffsets expects the second of three values to be null.
+func testArrowOffsets[T ~int32 | ~int64](t *testing.T, data []byte, offsets
[]T, want *GeoStatistics) {
+ t.Run("no offset", func(t *testing.T) {
+ g := NewGeoStatistics()
+ UpdateGeoStatisticsFromArrowOffsets(g, data, offsets,
[]byte{0b101}, 0)
+ assertSameGeoStats(t, want, g)
+ })
+ t.Run("with offset", func(t *testing.T) {
+ // the same validity, starting at bit 2
+ g := NewGeoStatistics()
+ UpdateGeoStatisticsFromArrowOffsets(g, data, offsets,
[]byte{0b101 << 2}, 2)
+ assertSameGeoStats(t, want, g)
+ })
+}
+
+func TestUpdateGeoStatisticsFromArrowOffsets(t *testing.T) {
+ a, b := wkbPoint(1, 1, 2), wkbPoint(1, 3, 4)
+ garbage := []byte("bad")
+ var data []byte
+ data = append(data, a...)
+ data = append(data, garbage...)
+ data = append(data, b...)
+ offsets := []int{0, len(a), len(a) + len(garbage), len(data)}
+ want := newGeoStats(a, b)
+
+ t.Run("int32", func(t *testing.T) { testArrowOffsets(t, data,
convertOffsets[int32](offsets), want) })
+ t.Run("int64", func(t *testing.T) { testArrowOffsets(t, data,
convertOffsets[int64](offsets), want) })
+
+ t.Run("nil validity", func(t *testing.T) {
+ g := NewGeoStatistics()
+ UpdateGeoStatisticsFromArrowOffsets(g, a, []int32{0,
int32(len(a))}, nil, 0)
+ assertSameGeoStats(t, newGeoStats(a), g)
+ })
+
+ t.Run("fewer than two offsets", func(t *testing.T) {
+ g := NewGeoStatistics()
+ UpdateGeoStatisticsFromArrowOffsets(g, data, []int32{0}, nil, 0)
+ UpdateGeoStatisticsFromArrowOffsets(g, data, []int32{}, nil, 0)
+ assert.True(t, g.Valid())
+ assert.True(t, g.IsEmpty())
+ })
+}
+
+func TestGeoStatisticsRedactedFromPlaintextFooter(t *testing.T) {
+ // With a column encrypted with its own key and a plaintext footer, a
+ // redacted copy of ColumnMetaData is left in the footer for old
readers.
+ // The bounding box must not be part of that copy.
+ const (
+ footerKey = "0123456789012345"
+ columnKey = "1234567890123450"
+ )
+ encProps := parquet.NewFileEncryptionProperties(footerKey,
+ parquet.WithPlaintextFooter(),
+
parquet.WithEncryptedColumns(parquet.ColumnPathToEncryptionPropsMap{
+ "geom": parquet.NewColumnEncryptionProperties("geom",
parquet.WithKey(columnKey)),
+ }))
+ props :=
parquet.NewWriterProperties(parquet.WithEncryptionProperties(encProps))
+
+ node, err := schema.NewPrimitiveNodeLogical("geom",
parquet.Repetitions.Optional,
+ schema.GeometryLogicalType{}, parquet.Types.ByteArray, -1, -1)
+ require.NoError(t, err)
+ sc := schema.NewSchema(schema.MustGroup(schema.NewGroupNode("schema",
+ parquet.Repetitions.Required, schema.FieldList{node}, -1)))
+ col := sc.Column(0)
+
+ bldr := NewColumnChunkMetaDataBuilder(props, col)
+ bldr.SetGeoStatistics(newGeoStats(wkbPoint(1, -122.4, 37.8),
wkbPoint(1, 5, 60)))
+ require.NotNil(t, bldr.Contents().MetaData.GeospatialStatistics)
+
+ require.NoError(t, bldr.Finish(ChunkMetaInfo{NumValues: 2,
DataPageOffset: 4}, false, false, EncodingStats{}))
+ encryptor :=
encryption.NewFileEncryptor(props.FileEncryptionProperties(),
memory.DefaultAllocator)
+ require.NoError(t,
bldr.PopulateCryptoData(encryptor.GetColumnMetaEncryptor(col.Path())))
+
+ chunk := bldr.Contents()
+ assert.NotEmpty(t, chunk.EncryptedColumnMetadata)
+ require.NotNil(t, chunk.MetaData)
+ assert.Nil(t, chunk.MetaData.Statistics)
+ assert.Nil(t, chunk.MetaData.GeospatialStatistics)
+}