Bringing together the Apache Cassandra experts from the community and DataStax.

Want to learn? Have a question? Want to share your expertise? You are in the right place!

Not sure where to begin? Getting Started

 

question

Ryan Quey avatar image
Ryan Quey asked ·

How can I append or prepend to a Collection using Python Driver?

I asked a similar question before regarding the Java driver, but now I'm wondering about the Python driver.


For Python driver 3.24, is it possible to use the models and object mapper classes to append or prepend to a collection column (ie, a SET or a LIST), rather than overwriting it? Of course I could accomplish the same by writing out straight CQL. But is there a straightforward way to do so using the models that I have setup for my app already?

python drivercollections
1 comment
10 |1000 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

It's in the middle of the night for me (1am in Melbourne, Australia) and I'm responding on my mobile.

Let me get one of the Drivers engineers to respond. Cheers!

0 Likes 0 ·

1 Answer

smadhavan avatar image
smadhavan answered ·

@Ryan Quey, you could perform something similar to below example.

For a List:

# appends the elements of the given list to the end of the column
Row.objects(row_id=5).update(list_column__append=[6, 7])

# prepends the elements of the given list to the beginning of the column
Row.objects(row_id=5).update(list_column__prepend=[1, 2])

For Set:

# adds the elements of the given set to the column
Row.objects(row_id=5).update(set_column__add={6})

# removes the elements of the given set to the column
Row.objects(row_id=5).update(set_column__remove={4})

The key to is below:

Using the syntax .update(column_name={x, y, z}) will overwrite the contents of the container, like updating a non container column. However, adding __ to the end of the keyword arg, makes the update call add or remove items from the collection, without overwriting then entire column.

See API documentation for additional reference.

1 comment Share
10 |1000 characters needed characters left characters exceeded

Up to 8 attachments (including images) can be used with a maximum of 1.0 MiB each and 10.0 MiB total.

This is great! I wasn't sure if the python driver supports appends and prepends, since the Java driver doesn't. Thanks

0 Likes 0 ·