Can variables be used in cql commands in cql scripts?

Is there a way to pass variables in CQL commands when used in CQL scripts, for example:

select * from "Column Family Name" where "ColumnName"='A variable which takes different values'; 

Any suggestions are welcome.

+6
source share
2 answers

No, CQL has no way to define variables, start a loop, and perform an update / query based on these variables.

As an alternative, I usually use the Python DataStax driver for simple tasks / scripts like this. Here is an excerpt from a Python script that I used a while ago to populate product colors from a CSV file.

 # connect to Cassandra auth_provider = PlainTextAuthProvider(username='username', password='currentHorseBatteryStaple') cluster = Cluster(['127.0.0.1'], auth_provider=auth_provider) session = cluster.connect('products') # prepare statements preparedUpdate = session.prepare( """ UPDATE products.productsByItemID SET color=? WHERE itemid=? AND productid=?; """ ) # end prepare statements counter = 0 # read csv file dataFile = csv.DictReader(csvfilename, delimiter=',') for csvRow in dataFile: itemid = csvRow['itemid'] color = csvRow['customcolor'] productid = csvRow['productid'] #update product color session.execute(preparedUpdate,[color,itemid,productid]) counter = counter + 1 # close Cassandra connection session.cluster.shutdown() session.shutdown() print "updated %d colors" % (counter) 

For more information, see the DataStax tutorial Getting Started with Apache Cassandra and Python .

+5
source

Yes, you can pass the variable as follows:

 import com.datastax.spark.connector.{SomeColumns, _} import org.apache.spark.{SparkConf, SparkContext} import com.datastax.spark.connector.cql.CassandraConnector import org.apache.spark.SparkConf import com.datastax.spark.connector import com.datastax.spark.connector._ import org.apache.spark.{Logging, SparkConf} import org.apache.spark.sql.DataFrame import org.apache.spark.sql.{Row, SQLContext, DataFrame} import org.apache.spark.sql.cassandra._ val myvar=1 csc.setKeyspace("test_keyspace") val query="""select a.col1, c.col4, b.col2 from test_keyspace.table1 a inner join test_keyspace.table2 b on a.col1=b.col2 inner join test_keyspace.table3 c on b.col3=c.col4 where a.col1="""+myvar.toString val results=csc.sql(query) results.show() 
0
source

Source: https://habr.com/ru/post/987666/


All Articles