0

I am using cqlengine, I had few doubts:

If we have a model defined as

class Contact(Model):
   street = columns.Text()
   city = columns.Text()

Can we do something like this

  1. Reference to contact model like mentioned in code below

    class User(Model):

      contact = Contact()
      first_name =coloumns.Text()
      .....`
    
  2. And Reference to User model as list:

    class Company(Model): users = columns.List(User()) .....

Are above correct way to achive the needed functionality, Or any other way ?

Neo
  • 5,070
  • 10
  • 46
  • 65

1 Answers1

1

Not really. Cassandra has no concept of foreign key relations, so neither does cqlengine. When you're modeling relationships like this with cassandra, there are a few approaches you can use, depending on the behavior of the related.

The first would be to duplicate your data. In the case of tying a user to an address, it might make sense to save the full address into the user table. With things that don't change (123 A Street won't magically move to 456 B street), this makes sense. If the user moves locations, you can just update the user table.

The second is to have a unique id for each contact location, and save the relevant ids on the user model, usually in a set. This is often better when 2 related entities change independently of each other, and the overhead of going out and updating the duplicated data each time something is changed is too high for your application.

The third is a variation on the second method, where the relating ids are stored in another table, which acts as a join table (user_id -> contact_id).

In any case, the most important thing to remember when working with cassandra/cqlengine, is that you want to model your data to answer a query. Duplicating your data is ok. Don't try to model your data like you would in an RDBMS.

Blake
  • 841
  • 4
  • 13
  • Understand you point, my concern was not for foreign keys. In the same point of view of keeping data flat, with those references just validating data. For example contact in user model just refers to dictionary of contact. User in company same as list of users. – Neo Aug 12 '14 at 10:30
  • For e.g. a sample user object={"contact": {"street": "",..}, "first_name": ""}, A sample company object= {users: [{first_user_data}, {2nd user_data}]} – Neo Aug 12 '14 at 13:54
  • Ok, I understand. No, cqlengine doesn't have anything like that. We've discussed adding it, but there are so many weird edge cases with references that we decided it would be best left to users. We try to keep the feature set of cqlengine down to just a pythonic abstraction of CQL. That said, it wouldn't be too hard to extend the base column class to add in whatever validation you need. – Blake Aug 12 '14 at 15:51
  • I have used mongokit extensively, which supports above functionality. So was looking for it in cqlengine. – Neo Aug 12 '14 at 16:23