---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.2
alternate:
  - https://ytsaurus.tech/docs/en/flow/go/examples/shuffle.md
  - https://ytsaurus.tech/docs/ru/flow/go/examples/shuffle.md
  - href: https://ytsaurus.tech/docs/en/flow/go/examples/shuffle.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/en/llms.txt?revision=3d4023814c654f56301c5b12ef057a0c6e4e82d1
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/en/llms.txt?revision=3d4023814c654f56301c5b12ef057a0c6e4e82d1

<!-- source: en/_includes/flow/go/examples/shuffle.md -->
# Shuffle in YTsaurus Flow (Go)

An example of a [pipeline](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#pipeline) built from two Go [computations](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation): the source computation parses JSON and sends typed [messages](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#message), and the transform computation counts the events in an external [state](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#state). Between them stand native passthrough computations that regroup the event by four different keys.

[Source code](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/shuffle)

## Structure {#structure}

- `reader` (source, `TSwiftOrderedSourceCompanionComputation`) — `eventMapper`: parses the JSON from the `data` column and sends a typed message to the `event` [stream](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#stream-and-computation).
- `shuffle_a` … `shuffle_d` — native `TSwiftPassthroughComputation` declared in the [spec](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#spec-and-dynamic-spec). Each of them regroups the flow by its own key (`key_a` … `key_d`) and publishes it to a separate stream, `event_a` … `event_d`. They have no Go code.
- `reducer` (transform, `TTransformCompanionComputation`) — `eventReducer`: it is subscribed to all four streams and counts how many times a value arrives, in the external state `/shuffle-state`.

An event written to the queue once reaches the reducer along four different paths, so it is counted four times. The companion serves only the ends of the pipeline — `reader` and `reducer`.

## `main.go` {#main-go}

The entry point: registering the source and transform computations with a single `pipeline.Add` call.

[Source code: `main.go`](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/shuffle/main.go)
```go
func main() {
	pipeline := flow.NewPipeline()
	pipeline.AddStreams(
		flow.NewYSONStream[event](eventStreamID),
		flow.NewYSONStream[event]("event_a"),
		flow.NewYSONStream[event]("event_b"),
		flow.NewYSONStream[event]("event_c"),
		flow.NewYSONStream[event]("event_d"),
	)
	pipeline.Add(
		flow.NewRowSourceComputation("reader", &eventMapper{}),
		flow.NewRowComputation("reducer", &eventReducer{}),
	)

	if err := pipeline.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "shuffle: %v\n", err)
		os.Exit(1)
	}
}
```

## `event_mapper.go` {#event-mapper-go}

The JSON structure that the input queue carries in the `data` column. The four keys are independent of each other — that is exactly what gives the shuffle stages something to regroup by:

```go

type sourceMessage struct {
	flow.YSONMessage
	Data []byte `yson:"data"`
}

type event struct {
	flow.YSONMessage
	KeyA  uint64 `json:"key_a" yson:"key_a"`
	KeyB  uint64 `json:"key_b" yson:"key_b"`
	KeyC  uint64 `json:"key_c" yson:"key_c"`
	KeyD  uint64 `json:"key_d" yson:"key_d"`
	Value string `json:"value" yson:"value"`
}
```

The source function converts the input row into `sourceMessage`, parses the JSON into `event`, and publishes a typed message: a flow can only be regrouped by a stream column, so the parsed keys are moved into separate fields.

```go

type eventMapper struct{}

var _ flow.RowFunction = (*eventMapper)(nil)

func (*eventMapper) OnMessage(
	ctx context.Context,
	rt flow.Runtime,
	msg flow.ExtendedMessage,
	out flow.OutputCollector,
) error {
	var input sourceMessage
	if err := msg.ConvertTo(&input); err != nil {
		return err
	}

	parsed := flow.NewYSONMessage[event](eventStreamID)
	if err := json.Unmarshal(input.Data, parsed); err != nil {
		return fmt.Errorf("parsing the data column: %w", err)
	}
	parsed.Meta.StreamID = eventStreamID
	message, err := flow.ConvertFrom(rt, parsed)
	if err != nil {
		return err
	}

	out.AddMessage(message)
	return nil
}
```

## `event_reducer.go` {#event-reducer-go}

The transform function with an external state for counting the events:

```go

type shuffleState struct {
	Count int64 `yson:"count"`
}

type eventReducer struct{}

var _ flow.RowFunction = (*eventReducer)(nil)

func (*eventReducer) OnMessage(
	ctx context.Context,
	rt flow.Runtime,
	msg flow.ExtendedMessage,
	out flow.OutputCollector,
) error {
	state, err := flow.OpenExternalState(rt, shuffleStateName, msg)
	if err != nil {
		return err
	}

	var counter shuffleState
	if _, err := state.ConvertTo(&counter); err != nil {
		return err
	}
	counter.Count++
	return state.ConvertFrom(&counter)
}
```

## Key patterns {#key-patterns}

- A pipeline of several computations: a [source](https://ytsaurus.tech/docs/en/flow/concepts/glossary.md#source) built on `flow.NewRowSourceComputation` plus a transform built on `flow.NewRowComputation`. Both are registered by a single `pipeline.Add`.
- Parsing JSON and creating a typed message: `msg.ConvertTo(&input)` → `json.Unmarshal` → `flow.ConvertFrom(rt, event)` → `out.AddMessage(msg)`.
- External state through `flow.OpenExternalState(rt, "/shuffle-state", msg)`: `ConvertTo` reads the counter into a structure, `ConvertFrom` saves the update. The name of an external state is an absolute path that matches the key in `external_state_managers` of the spec.
- `state.ConvertTo` returns whether the row exists: for a key the state has never been written for, the counter starts from zero.
- Regrouping the flow is the job of the native passthrough computations: you can count the same value across several cuts without writing a single line of Go code for the shuffle stages themselves.
<!-- endsource: en/_includes/flow/go/examples/shuffle.md -->

<!-- source: en/_includes/flow/go/examples/shuffle_also.md -->
## See also

- [Getting started (Go)](https://ytsaurus.tech/docs/en/flow/go/getting-started.md)
- [Computation (Go)](https://ytsaurus.tech/docs/en/flow/go/computation.md)
- [External State (Go)](https://ytsaurus.tech/docs/en/flow/go/external-state.md)
- [Testing (Go)](https://ytsaurus.tech/docs/en/flow/go/testing.md)
- [Similar example in C++](https://ytsaurus.tech/docs/en/flow/cpp/examples/shuffle.md)
<!-- endsource: en/_includes/flow/go/examples/shuffle_also.md -->
