← Library SliceDeterministic

SliceTopKOp

Returns the indices of the top-K highest scores from a float64 slice, in descending order.

Inputs

FieldTypeDescription
Scores*[]float64Float64 slice of scores

Outputs

FieldTypeDescription
Result[]intIndices of top-K scores, best first

Params

KeyTypeDefaultDescription
kintrequiredNumber of top results to return

Typical Use Cases

  • Taking top-K results after a parallel scoring map
  • Ranking-based selection before SliceAtOp
  • Trimming a reranked list to K items

Complete Runnable Example

Selects the top 3 candidates by relevance score from a batch of AI-scored results.

main.go
package main

import (
	"context"
	"encoding/json"
	"log"
	"os"
	"time"

	"github.com/akennis/sparsi-go/library"
	_ "github.com/akennis/dagor/operator/builtin"

	"github.com/panjf2000/ants/v2"
	"github.com/akennis/dagor"
	"github.com/akennis/dagor/graph"
)

func main() {
	scores := []float64{72.0, 91.5, 58.0, 85.0, 67.5, 95.0}
	library.RegisterConst("scores_val", scores)

	g, err := graph.NewBuilder("topk_demo").
		Vertex("src").Op("scores_val").Output("Result", "wire_in").
		Vertex("tk").Op("SliceTopKOp").
		Params(map[string]string{"k": "3"}).
		Input("Scores", "wire_in").
		Output("Result", "top_indices").
		Build()
	if err != nil {
		log.Fatalf("build: %v", err)
	}

	pool, err := ants.NewPool(4)
	if err != nil {
		log.Fatalf("pool: %v", err)
	}
	defer pool.Release()

	eng, err := dagor.NewEngine(g, pool)
	if err != nil {
		log.Fatalf("engine: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	if err := eng.Run(ctx); err != nil {
		log.Fatalf("run: %v", err)
	}

	out := map[string]any{"scores": scores, "k": 3}
	if raw, ok := eng.GetOutput("top_indices"); ok {
		out["top_indices"] = *raw.(*[]int)
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	enc.Encode(out)
}