laskoviymishka commented on code in PR #2682: URL: https://github.com/apache/iceberg-go/pull/2682#discussion_r4677676550
########## website/src/cli.md: ########## @@ -237,6 +255,35 @@ iceberg clean-orphan-files --older-than 5d my_db.events iceberg clean-orphan-files --location s3://old-warehouse/my_db/events my_db.events ``` +## File maintenance + +### Data-file compaction + +Preview the groups that compaction would rewrite with `compact analyze`. +Use `compact run` to write replacements. By default it bin-packs each group. +Pass `--sort` to sort each group by the table's default sort order. Review Comment: `--sort` and `--max-group-size` aren't in [v0.7.0's compact commands](https://github.com/apache/iceberg-go/blob/89a9104ec3639d38ab07e4461721cb5270e95571/cmd/iceberg/main.go#L156-L166), so the `@latest` binary from the intro rejects them. Could we say so here? ```suggestion Pass `--sort` to sort each group by the table's default sort order. `--sort` and `--max-group-size` are not in v0.7.0; use the `@main` install for them. ``` ########## website/src/api.md: ########## @@ -647,6 +668,19 @@ _, _, err := cat.CommitTable(ctx, tbl.Identifier(), reqs, []table.Update{update} Constants `table.MainBranch`, `table.BranchRef`, `table.TagRef` live in [`table/refs.go`](https://github.com/apache/iceberg-go/blob/main/table/refs.go). A higher-level builder is on the roadmap. +An append in a transaction targeting a missing branch can create it from Review Comment: Should this say when to use which? The text just above still routes ref creation through `CommitTable` with `SetSnapshotRef` and calls a higher-level builder "on the roadmap", while this paragraph creates the branch implicitly on append ([table.go](https://github.com/apache/iceberg-go/blob/3bb2eea9efd030cc44ab075425b5b89642684a97/table/table.go#L249-L254)). Dropping the roadmap sentence would also work. ########## website/src/getting-started.md: ########## @@ -19,240 +19,131 @@ # Getting Started -This walkthrough takes you from `go get` to a fully written-and-read Iceberg table in a few minutes, using a local SQLite-backed catalog so you do not need any external services. By the end you will have: +Create an Iceberg table in a local SQLite catalog, append three rows with Arrow, +and read the rows back. The program uses a fresh temporary catalog and warehouse +on each run and removes them when it exits. -- An Iceberg catalog stored in a SQLite file -- A table with an Arrow schema -- Data written from Apache Arrow Go and read back -- A schema evolution committed -- A branch created on top of the table +## Install -If you would rather see all the operations as a reference, jump straight to the [API](./api.md). - -## 1. Install +This walkthrough uses Iceberg Go v0.7.0 and requires Go 1.25.9 or later. +Create a new directory and run: ```sh go mod init iceberg-go-tutorial -go get github.com/apache/iceberg-go@latest -go get github.com/apache/arrow-go/v18@latest -go get github.com/uptrace/bun/driver/sqliteshim@latest +go get github.com/apache/[email protected] \ + github.com/apache/arrow-go/[email protected] \ + github.com/uptrace/bun/driver/[email protected] ``` -`iceberg-go` itself only registers the local file system. For S3, GCS, or Azure Blob you would also blank-import the matching backend package, such as `github.com/apache/iceberg-go/io/gocloud/s3`. We are staying on local disk for this tutorial. - -## 2. Open a local catalog +## Create, write, and read a table -The SQL catalog stores its metadata in a database, and the actual data files live under a "warehouse" directory. We will use SQLite for both the catalog DB and a local folder for the warehouse. +Save the following as `main.go`. The SQL catalog stores table registrations in +SQLite. The Iceberg metadata and Parquet data files go in the local warehouse. ```go package main import ( - "context" - "database/sql" - "log" - - "github.com/apache/iceberg-go" - sqlcat "github.com/apache/iceberg-go/catalog/sql" - "github.com/uptrace/bun/driver/sqliteshim" + "context" + "fmt" + "io" + "log" + "os" + "path/filepath" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/iceberg-go" + "github.com/apache/iceberg-go/catalog" + _ "github.com/apache/iceberg-go/catalog/sql" + "github.com/uptrace/bun/driver/sqliteshim" ) -func openCatalog(ctx context.Context) (*sqlcat.Catalog, error) { - db, err := sql.Open(sqliteshim.ShimName, "file:./tutorial-catalog.db?cache=shared") - if err != nil { - return nil, err - } - return sqlcat.NewCatalog(ctx, "default", db, sqlcat.SQLite, iceberg.Properties{ - "warehouse": "file:///tmp/iceberg-tutorial", - "init_catalog_tables": "true", - }) +func run(ctx context.Context) error { + dir, err := os.MkdirTemp("", "iceberg-tutorial-") + if err != nil { + return err + } + defer os.RemoveAll(dir) + + cat, err := catalog.Load(ctx, "tutorial", iceberg.Properties{ + "type": "sql", + "uri": "file:" + filepath.Join(dir, "catalog.db"), + "sql.driver": sqliteshim.ShimName, + "sql.dialect": "sqlite", + "warehouse": "file://" + filepath.Join(dir, "warehouse"), + }) + if err != nil { + return err + } + if closer, ok := cat.(io.Closer); ok { + defer closer.Close() + } + + if err := cat.CreateNamespace(ctx, catalog.ToIdentifier("taxi"), nil); err != nil { + return err + } + trips := catalog.ToIdentifier("taxi", "trips") + schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name: "trip_id", Type: iceberg.PrimitiveTypes.Int64, Required: true}) + tbl, err := cat.CreateTable(ctx, trips, schema) + if err != nil { + return err + } + + arrowSchema := arrow.NewSchema([]arrow.Field{{Name: "trip_id", Type: arrow.PrimitiveTypes.Int64}}, nil) + records := array.NewRecordBuilder(memory.DefaultAllocator, arrowSchema) + defer records.Release() + records.Field(0).(*array.Int64Builder).AppendValues([]int64{1, 2, 3}, nil) + batch := records.NewRecord() + defer batch.Release() + input := array.NewTableFromRecords(arrowSchema, []arrow.Record{batch}) + defer input.Release() + tbl, err = tbl.AppendTable(ctx, input, 1024, nil) + if err != nil { + return err + } + + output, err := tbl.Scan().ToArrowTable(ctx) + if err != nil { + return err + } + defer output.Release() + if tbl.CurrentSnapshot() == nil || output.NumRows() != 3 { + return fmt.Errorf("expected a committed snapshot and 3 rows, got %d rows", output.NumRows()) + } + fmt.Printf("Read %d rows from taxi.trips and verified a committed snapshot.\n", output.NumRows()) + return nil } -``` - -`init_catalog_tables: "true"` lets the catalog create its bookkeeping tables (`iceberg_tables`, `iceberg_namespace_properties`) on first use. Make sure `/tmp/iceberg-tutorial` is writable. -## 3. Create a namespace and a table - -Iceberg organizes tables under namespaces (the analog of databases). We will create one and put a table inside it. - -```go -import ( - "github.com/apache/iceberg-go/catalog" - "github.com/apache/iceberg-go/table" -) - -func createTrips(ctx context.Context, cat *sqlcat.Catalog) (*table.Table, error) { - ns := table.Identifier{"taxi"} - if err := cat.CreateNamespace(ctx, ns, nil); err != nil { - return nil, err - } - - schema := iceberg.NewSchema(1, - iceberg.NestedField{ID: 1, Name: "trip_id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, - iceberg.NestedField{ID: 2, Name: "fare", Type: iceberg.PrimitiveTypes.Float64, Required: false}, - iceberg.NestedField{ID: 3, Name: "borough", Type: iceberg.PrimitiveTypes.String, Required: false}, - ) - - ident := catalog.ToIdentifier("taxi", "trips") - return cat.CreateTable(ctx, ident, schema) +func main() { + if err := run(context.Background()); err != nil { + log.Fatal(err) + } } ``` -If the namespace already exists, `CreateNamespace` returns an error - the example skips error handling for brevity; production code should check for `iceberg.ErrAlreadyExists` and recover. +Run the program: -## 4. Write some Arrow data - -The write path takes either a streaming [`array.RecordReader`](https://pkg.go.dev/github.com/apache/arrow-go/v18/arrow/array#RecordReader) or a fully materialized [`arrow.Table`](https://pkg.go.dev/github.com/apache/arrow-go/v18/arrow#Table). We will build a small Arrow table inline and append it. - -```go -import ( - "github.com/apache/arrow-go/v18/arrow" - "github.com/apache/arrow-go/v18/arrow/array" - "github.com/apache/arrow-go/v18/arrow/memory" -) - -func writeSomeTrips(ctx context.Context, tbl *table.Table) (*table.Table, error) { - mem := memory.NewGoAllocator() - - arrowSchema := arrow.NewSchema([]arrow.Field{ - {Name: "trip_id", Type: arrow.PrimitiveTypes.Int64, Nullable: false}, - {Name: "fare", Type: arrow.PrimitiveTypes.Float64, Nullable: true}, - {Name: "borough", Type: arrow.BinaryTypes.String, Nullable: true}, - }, nil) - - b := array.NewRecordBuilder(mem, arrowSchema) - defer b.Release() - - b.Field(0).(*array.Int64Builder).AppendValues([]int64{1, 2, 3}, nil) - b.Field(1).(*array.Float64Builder).AppendValues([]float64{12.50, 8.75, 22.10}, nil) - b.Field(2).(*array.StringBuilder).AppendValues([]string{"Manhattan", "Brooklyn", "Queens"}, nil) - - rec := b.NewRecord() - defer rec.Release() - - arrowTbl := array.NewTableFromRecords(arrowSchema, []arrow.Record{rec}) - defer arrowTbl.Release() - - return tbl.AppendTable(ctx, arrowTbl, 1024 /* batchSize */, nil) -} -``` - -`AppendTable` returns a refreshed `*table.Table` reflecting the new snapshot. - -## 5. Read the data back - -```go -func readAll(ctx context.Context, tbl *table.Table) error { - arrowTbl, err := tbl.Scan().ToArrowTable(ctx) - if err != nil { - return err - } - defer arrowTbl.Release() - - log.Printf("read %d rows in %d columns", arrowTbl.NumRows(), arrowTbl.NumCols()) - return nil -} -``` - -For larger tables, use streaming so only one batch is in memory at a time: - -```go -arrowSchema, batches, err := tbl.Scan().ToArrowRecords(ctx) -if err != nil { - return err -} -log.Printf("scan schema: %s", arrowSchema) - -for batch, err := range batches { - if err != nil { - return err - } - log.Printf("batch with %d rows", batch.NumRows()) - batch.Release() -} -``` - -## 6. Filter and project - -Use the [predicate DSL](./row-filter-syntax.md) to push filters down into the scan, and `WithSelectedFields` to project columns: - -```go -filter := iceberg.GreaterThan(iceberg.Reference("fare"), float64(10.0)) - -arrowTbl, err := tbl.Scan( - table.WithSelectedFields("trip_id", "fare"), - table.WithRowFilter(filter), -).ToArrowTable(ctx) -``` - -## 7. Evolve the schema - -Most schema changes go through a transaction. Add a `tip` column: - -```go -import "github.com/apache/iceberg-go/table" - -func addTipColumn(ctx context.Context, tbl *table.Table) (*table.Table, error) { - txn := tbl.NewTransaction() - - err := table.NewUpdateSchema(txn, true /* caseSensitive */, false /* allowIncompatible */). - AddColumn([]string{"tip"}, iceberg.PrimitiveTypes.Float64, "Tip in dollars", false, nil). - Commit() - if err != nil { - return nil, err - } - - return txn.Commit(ctx) -} +```sh +go mod tidy +go run . ``` -The returned table has the new schema and a fresh metadata file. - -## 8. Branch the table - -A branch is a named ref that points at a snapshot. Creating one requires a metadata commit that adds the ref - `NewTransactionOnBranch` only writes to a branch that already exists. Two steps: - -```go -import "github.com/apache/iceberg-go/table" - -// Step 1: create the branch via Catalog.CommitTable. -func createExperimentBranch(ctx context.Context, cat *sqlcat.Catalog, tbl *table.Table) (*table.Table, error) { - snap := tbl.CurrentSnapshot() - update := table.NewSetSnapshotRefUpdate( - "experiment", snap.SnapshotID, table.BranchRef, - 0 /* maxRefAgeMs */, 0 /* maxSnapshotAgeMs */, 0 /* minSnapshotsToKeep */, - ) - reqs := []table.Requirement{ - table.AssertTableUUID(tbl.Metadata().TableUUID()), - table.AssertRefSnapshotID("experiment", nil), // branch must not yet exist - } - if _, _, err := cat.CommitTable(ctx, tbl.Identifier(), reqs, []table.Update{update}); err != nil { - return nil, err - } - // Reload so subsequent transactions see the new ref. - return cat.LoadTable(ctx, tbl.Identifier()) -} - -// Step 2: open a transaction on the branch and write. -func writeOnBranch(ctx context.Context, tbl *table.Table, arrowTbl arrow.Table) (*table.Table, error) { - txn, err := tbl.NewTransactionOnBranch("experiment") - if err != nil { - return nil, err - } - if err := txn.AppendTable(ctx, arrowTbl, 1024, nil); err != nil { - return nil, err - } - return txn.Commit(ctx) -} +```text +Read 3 rows from taxi.trips and verified a committed snapshot. ``` -Reads can target the branch with `tbl.Scan().UseRef("experiment")`. +The append returns a new table handle with the committed snapshot. The scan +uses that handle to read the rows back. ## Where to go next -- [API](./api.md) - the full Go surface for catalogs, tables, scans, writes, transactions, schema and partition evolution, snapshot management, maintenance, and views. -- [Configuration](./configuration.md) - cloud credentials, table properties, concurrency, custom catalog and IO registration. -- [CLI](./cli.md) - inspect, expire, compact, branch, and tag from the command line. -- [Row Filter Syntax](./row-filter-syntax.md) and [Expression DSL](./expression-dsl.md) - the predicate DSL in detail. - -The full Iceberg specification, terminology, and engine integration policy live with the main project at [iceberg.apache.org](https://iceberg.apache.org/). +- [Filter and project columns](./api.md#projection-and-filters) or + [stream Arrow record batches](./api.md#streaming-record-batches). +- [Evolve a schema](./api.md#schema-evolution) or + [work with branches and tags](./api.md#branches-and-tags). +- [Configure another catalog](./configuration.md#catalog-options) or Review Comment: Should one of these point at the [file-system credentials section](https://github.com/apache/iceberg-go/blob/3bb2eea9efd030cc44ab075425b5b89642684a97/website/src/configuration.md#L277-L289)? The old tutorial said S3, GCS and Azure need a blank import of the backend package, and that note is gone now. The `ErrIOSchemeNotFound` hint covers it at runtime, so this is minor. ########## website/src/getting-started.md: ########## @@ -19,240 +19,131 @@ # Getting Started -This walkthrough takes you from `go get` to a fully written-and-read Iceberg table in a few minutes, using a local SQLite-backed catalog so you do not need any external services. By the end you will have: +Create an Iceberg table in a local SQLite catalog, append three rows with Arrow, +and read the rows back. The program uses a fresh temporary catalog and warehouse +on each run and removes them when it exits. -- An Iceberg catalog stored in a SQLite file -- A table with an Arrow schema -- Data written from Apache Arrow Go and read back -- A schema evolution committed -- A branch created on top of the table +## Install -If you would rather see all the operations as a reference, jump straight to the [API](./api.md). - -## 1. Install +This walkthrough uses Iceberg Go v0.7.0 and requires Go 1.25.9 or later. Review Comment: Could we add a "bump the Getting Started pin" step to the [post-release tasks](https://github.com/apache/iceberg-go/blob/3bb2eea9efd030cc44ab075425b5b89642684a97/website/src/how-to-release.md#L83-L90)? Nothing there touches this pin or the v0.7.0 link in cli.md, so after the next tag the tutorial stays on v0.7.0 while install.md says `@latest`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
