Word Count in YTsaurus Flow (Go)

The simplest example of a stateful pipeline in Go: counting the occurrences of every word in an internal YSON state.

Source code

Structure

The pipeline consists of two computations:

  • reader — a native source (TSwiftPassthroughOrderedSourceComputation) declared directly in the spec: it reads the queue and publishes the rows to the words stream. It has no Go code.
  • mapper — a transform computation (TTransformCompanionComputation) served by the companion: it reads the words stream and updates the counter of the word in the internal state.

The messages are grouped by word (group_by_schema with farm_hash(word) and word), so the state of the key being processed is the counter of exactly one word. The result of the pipeline lies in the internal state table: nothing is sent further along the graph.

main.go

The entry point: creating the pipeline, registering the only computation, and starting it.

Source code: main.go

type wordMessage struct {
	flow.YSONMessage
	Word string `yson:"word"`
}

func main() {
	pipeline := flow.NewPipeline()
	pipeline.AddStreams(flow.NewYSONStream[wordMessage]("words"))
	pipeline.Add(flow.NewRowComputation("mapper", &wordCountMapper{}))

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

word_count_mapper.go

The state value is an ordinary Go structure with YSON tags: it is stored in the internal state table exactly in this form.


type wordCountState struct {
	Word  string `yson:"word"`
	Count int64  `yson:"count"`
}

The flow.RowFunction that opens the internal state by the name word-state through flow.OpenYSONState and increments the counter:


type wordCountMapper struct{}

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

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

	state, err := flow.OpenYSONState[wordCountState](rt, wordStateName, msg)
	if err != nil {
		return err
	}

	fresh := state.Empty()
	counter := state.Value()
	if fresh {
		counter.Word = input.Word
	}
	counter.Count++
	return nil
}

Key patterns

  • The simplest stateful pipeline with a single computation on the companion side: the source stays native, and no Go code is needed for it.
  • Internal YSON state through flow.OpenYSONState[T](rt, name, msg): Value() returns a mutable structure that the SDK saves after a successful batch.
  • The state name (word-state) matches the name from parameters.internal_states of the computation in the spec.
  • The state key is defined by group_by_schema from the spec — in this case, by the word field.
  • The input is converted into wordMessage once through msg.ConvertTo(&input), after which the handler works with the fields of the structure.

See also

Previous