How do I create a Table object in Python for an existing Cassandra table?

372 Views Asked by At

I have some tables in a keyspace and I want query like ORM in python DataStax driver

I have lots of tables with huge schema. any other method to create a table object without writing the Table class

eg: if I have a table called test_table then
table_object=Table(table_name,metadata,autoload=True)

2

There are 2 best solutions below

1
On

You haven't provided a lot of information so I'm not really sure what you're after. In any case, you might be interested in Models in the Python driver.

Here's an example from the docs for a class Person:

from cassandra.cqlengine import columns
from cassandra.cqlengine.models import Model

 class Person(Model):
     id = columns.UUID(primary_key=True)
     first_name  = columns.Text()
     last_name = columns.Text()

which maps to this CQL table:

CREATE TABLE cqlengine.person (
    id uuid,
    first_name text,
    last_name text,
    PRIMARY KEY (id)
)

You can then perform CRUD operations on the table using the Person object.

For details and more examples, see Models with the Cassandra Python driver. Cheers!

0
On

I used this function for getting Cassandra table object in pyspark

def get_table(keys_space_name, table_name):
    table_df = spark.read\
        .format("org.apache.spark.sql.cassandra")\
        .option("spark.cassandra.connection.host","127.0.0.1")\
        .option("spark.cassandra.connection.port", "9042")\
        .options(table='test', keyspace='test_keyspace')\
        .load()
    return table_df