KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ GoLang Table to Struct?

  • rahul_asati04

    Member
    March 20, 2022 at 12:00 am

    This site has a good example to insert and select data from kdb process.

    https://janrock.medium.com/kdb-golang-oanda-e9bec0570799

     

    Here is an updated example from that site to show selecting kdb data in go process and storing that in go structure.

     

    KDB  `trade`  table

     

    q)trade 
    time sym price 
    --------------------------------------- 
    2015.10.19D18:40:22.982760448 a 100 
    2009.02.21D21:21:02.534721216 b 200

     

     

    Go Code

     

    package main import ( "time" "fmt" kdb "github.com/sv/kdbgo" ) 
    // Go struct to store KDB table type trade struct { Ts time.Time Sym string Price int64 } 
    // Function to convert KDB data to GO struct 
    func tableToStruct(tbl kdb.Table) []trade {
    var data = []trade{} 
    rowCount := int(tbl.Data[0].Len()) 
    for i := 0; i < rowCount; i++ {
     rec := trade{
    Ts: tbl.Data[0].Index(i).(time.Time), 
    Sym: tbl.Data[1].Index(i).(string), 
    Price: tbl.Data[2].Index(i).(int64)
    } 
    data = append(data, rec) 
    }
    return data
    } 
    
    func main() { 
    con, err := kdb.DialKDB("localhost", 5000, "") 
    if err != nil { 
    fmt.Println("Failed to connect: %v", err) 
    }
    
    ktbl, err := con.Call("select time, sym, price from trade")
    if err != nil 
    { 
    fmt.Println("Query failed: %v", err) 
    return 
    }
    
    series := tableToStruct(ktbl.Data.(kdb.Table)) 
    for _, v := range series 
    { 
    fmt.Printf("Timestamp: %v | Sym: %v | Price: %v n", v.Ts, v.Sym, v.Price) 
    } 
    con.Close()
     }

     

    Go Output:

    $ go run go-kdb.go

    Timestamp: 2015-10-19 18:40:22.982760448 +0000 UTC | Sym: a | Price: 100

    Timestamp: 2009-02-21 21:21:02.534721216 +0000 UTC | Sym: b | Price: 200

     

Log in to reply.