Search code examples
pythoncassandracqlengine

Updating UDT Set with CQLEngine


I'm new to Cassandra and I'm trying to use CQLEngine ORM to update set column which holds UDT but I can't and documentation doesn't say anything about custom types.

My code is;

class MyType(UserType):

    val = columns.Text()
    point = columns.Integer()
    key = columns.Text()

    def __init__(self, val, point, key, **values):
        super().__init__(**values)
        self.val = val
        self.point = point
        self.key = key


class MyModel(Model):

    myid = columns.UUID(primary_key=True)
    set_clm = columns.Set(columns.Integer)
    mytype = columns.Set(UserDefinedType(MyType))

    def __init__(self, set_clm, mytype, **values):
        super().__init__(**values)
        self.myid = uuid4()
        self.set_clm = set_clm
        self.mytype = mytype



s = MyModel.objects(myid="2b3adb7d-9e68-49fc-9aa0-26dbec607f9d").update(
    mytype__add=set(MyType(val="1", point=2, key="3"))
)

MyModel initially holds NULL in set but when I try to update it, I get the following error:

cassandra.InvalidRequest: Error from server: code=2200 [Invalid query] message="Invalid set literal for mytype: value 'point' is not of type frozen<mytype>"

'point' is not of type frozen<mytype> -> This part randomly changes whenever I rerun the code (next time I'd run, I'd get the same error for 'val' column etc).

Can anyone help me how I can add a UDT set?


Solution

  • OK. I've solved it. I'm writing it down for people who'd find it on Google.

    This is the correct way of adding to a set: mytype__add={MyType(val="1", point=2, key="3")}

    and also implement the __hash__ function for MyType such as:

    def __hash__():
        return hash(self.__repr__())
    

    but with a smarter __hash__ function. It's just an example. Hope it helps to someone else.