1

Cassandra table and UDT

CREATE TYPE IF NOT EXISTS phone_type(
   code TEXT,
   phone TEXT,
);

CREATE TABLE IF NOT EXISTS user_by_phone(
    user_id UUID,
    phone FROZEN<phone_type>,
    password TEXT,
    PRIMARY KEY (phone)
);

golang struct

type PhoneType struct {
    Code  string `json:"code"`
    Phone string `json:"phone"`
}
phone := PhoneType{
    Code:  "+1",
    Phone: "7777777777",
}

gqcql query

err := Session.Query("SELECT user_id, password FROM user_by_phone WHERE phone=?;", phone).Scan(
    &user.UserID,
    &user.Password,
)

With this code it returns not found eventhough have a record in cassandra table. How to query by UDT using gocql?

Chandu
  • 962
  • 2
  • 16
  • 33

1 Answers1

2

Try defining your struct like this (use cql instead of json in your struct definition)

type PhoneType struct {
    Code  string `cql:"code"`
    Phone string `cql:"phone"`
}

phone := PhoneType{
    Code:  "+1",
    Phone: "7777777777",
}

as per the example here: https://github.com/gocql/gocql/blob/master/udt_test.go

This then worked for me:

    var id gocql.UUID
    var password string
    
    iter := session.Query("SELECT user_id, password FROM user_by_phone WHERE phone=?;", phone).Iter()
    for iter.Scan(&id, &password) {
        fmt.Println("Phone Record:", id, password)
    }
    if err := iter.Close(); err != nil {
        log.Fatal(err)
    }
bswynn
  • 341
  • 1
  • 3