Search code examples
pythonfiltercassandracql

CQL filter method - python


I have the following CQL table.

session = columns.Date(primary_key=True, partition_key=True, required=True)
entity = columns.Text(primary_key=True, partition_key=True, required=True)
broker = columns.Text(primary_key=True, required=True)
prof = columns.Text(primary_key=True, required=True)
prod = columns.Text(primary_key=True, required=True)
.... 

Reading documentation from cql engine there is a 'filter' method, I can use to filter by (session, entity) -> Partition key or whatever I want.

My problem is the following one, I wan to filter always by (session,entity) but also a possible number of fields, such 'prof' or 'prod' or both of them.

My function to do this is the following one.

def search_by(cls, entity, session, **kwargs): #entity, session, filter
        activity_summary = ActivitySummary.objects \
             .filter(entity=entity, session=session) \
             .filter(kwargs) \
             .allow_filtering()
        return cls._to_dataframe(activity_summary)

Where **kwargs is my variable filter, a dictionary with my primary keys I want to use to filter it ( e.g {'prof':'MAXIMO'} ).

But it doesn't work becaouse it's not matching properly dictionary names with column cql table names.

Any idea? Thanks.


Solution

  • You need to expand the kwargs as you pass them along.

    def search_by(cls, entity, session, **kwargs): #entity, session, filter
            activity_summary = ActivitySummary.objects \
                 .filter(entity=entity, session=session) \
                 .filter(**kwargs) \
                 .allow_filtering()
            return cls._to_dataframe(activity_summary)
    

    Notice .filter(**kwargs) instead of .filter(kwargs)