Python cassandra update statement error 'mismatched input 're' expecting K_WHERE '?

Viewed 603

I am trying to update cassandra database using python client as follows.

def update_content(session, id, content)
  update_statement = """
    UPDATE mytable SET content='{}' WHERE id={}
  """
  session.execute(update_statement.format(content, id))

It works for most of the cases but in some scenarios the content is a string of the form

content = "Content Message -'[re]...)"

which results in error Exception calling application: <Error from server: code=2000 [Syntax error in CQL query] message="line 2:61 mismatched input 're' expecting K_WHERE (

which I am not sure why is it happening? Is cassandra trying to interpret the string as regex somehow.

I tried printing the data before updation and its seems fine

"UPDATE mytable SET content='Content Message -'[re]...)' WHERE id=2"
1 Answers

To avoid such problems you should stop using the .format to create CQL statements, and start to use prepared statements that allow you to:

  • avoid problems with not escaped special characters, like, '
  • allows to do basic type checking
  • get better performance, because query will be parsed once, and only the data will be sent over the wire
  • you'll get token-aware query routing, meaning that query will be sent directly to one of the replicas that holds data for partition

Your code need to be modified as following:

prep_statement = session.prepare('UPDATE mytable SET content=? WHERE id=?')

def update_content(session, id, content):
  session.execute(prep_statement, [content, id])

Please notice that statement need to be prepared only once, because it includes the round-trip to the cluster nodes to perform parsing of the query

Related