---
metadata:
  - name: generator
    content: Diplodoc Platform v5.70.0
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/ru/flow/go/examples/shuffle.md
    type: text/markdown
    title: Markdown version
  - href: https://ytsaurus.tech/docs/ru/llms.txt?revision=d1460a800885385aa850a1578c0d21951c4247ed
    rel: describedby
---
> **Documentation Index:** Fetch the complete configuration index at https://ytsaurus.tech/docs/ru/llms.txt?revision=d1460a800885385aa850a1578c0d21951c4247ed

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

Пример [пайплайна](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#pipeline) из двух Go-[компьютейшенов](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#stream-and-computation): source-компьютейшен парсит JSON и отправляет типизированные [сообщения](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#message), transform-компьютейшен ведёт подсчёт событий во внешнем [стейте](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#state). Между ними стоят нативные passthrough-компьютейшены, перегруппирующие событие по четырём разным ключам.

[Исходный код](https://github.com/ytsaurus/ytsaurus/tree/main/yt/yt/flow/examples/go/shuffle)

## Структура {#structure}

- `reader` (source, `TSwiftOrderedSourceCompanionComputation`) — `eventMapper`: парсит JSON из колонки `data` и отправляет типизированное сообщение в [стрим](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#stream-and-computation) `event`.
- `shuffle_a` … `shuffle_d` — нативные `TSwiftPassthroughComputation`, объявленные в [спеке](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#spec-and-dynamic-spec). Каждый перегруппирует поток по своему ключу (`key_a` … `key_d`) и публикует его в отдельный стрим `event_a` … `event_d`. Go-кода у них нет.
- `reducer` (transform, `TTransformCompanionComputation`) — `eventReducer`: подписан на все четыре стрима и считает число приходов значения во внешнем стейте `/shuffle-state`.

Событие, записанное в очередь один раз, доходит до редьюсера четырьмя разными путями, поэтому учитывается четыре раза. Компаньон обслуживает только концы пайплайна — `reader` и `reducer`.

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

Точка входа: регистрация source- и transform-компьютейшенов одним вызовом `pipeline.Add`.

[Исходный код: `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}

JSON-структура, которую входная очередь несёт в колонке `data`. Четыре ключа независимы друг от друга — именно это даёт shuffle-стадиям то, по чему перегруппировывать:

```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"`
}
```

Source-функция, которая преобразует входную строку в `sourceMessage`, разбирает JSON в `event` и публикует типизированное сообщение: перегруппировать поток можно только по колонке стрима, поэтому распарсенные ключи выносятся в отдельные поля.

```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}

Transform-функция с внешним стейтом для подсчёта событий:

```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}

- Пайплайн из нескольких компьютейшенов: [сорс](https://ytsaurus.tech/docs/ru/flow/concepts/glossary.md#source) на `flow.NewRowSourceComputation` плюс трансформ на `flow.NewRowComputation`. Оба регистрируются одним `pipeline.Add`.
- Парсинг JSON и создание типизированного сообщения: `msg.ConvertTo(&input)` → `json.Unmarshal` → `flow.ConvertFrom(rt, event)` → `out.AddMessage(msg)`.
- Внешний стейт через `flow.OpenExternalState(rt, "/shuffle-state", msg)`: `ConvertTo` читает счётчик в структуру, `ConvertFrom` сохраняет обновление. Имя внешнего стейта — абсолютный путь, совпадающий с ключом в `external_state_managers` спеки.
- `state.ConvertTo` возвращает признак наличия строки: для ключа, по которому стейт ещё не записывался, счётчик начинается с нуля.
- Перегруппировка потока — задача нативных passthrough-компьютейшенов: одно и то же значение можно посчитать по нескольким разрезам, не написав ни строчки Go-кода для самих shuffle-стадий.
<!-- endsource: ru/_includes/flow/go/examples/shuffle.md -->

<!-- source: ru/_includes/flow/go/examples/shuffle_also.md -->
## См. также

- [Быстрый старт (Go)](https://ytsaurus.tech/docs/ru/flow/go/getting-started.md)
- [Computation (Go)](https://ytsaurus.tech/docs/ru/flow/go/computation.md)
- [External State (Go)](https://ytsaurus.tech/docs/ru/flow/go/external-state.md)
- [Тестирование (Go)](https://ytsaurus.tech/docs/ru/flow/go/testing.md)
- [Аналогичный пример на C++](https://ytsaurus.tech/docs/ru/flow/cpp/examples/shuffle.md)
<!-- endsource: ru/_includes/flow/go/examples/shuffle_also.md -->
