问题
Is there a way to pass variables in CQL commands when being used in CQL scripts like:
select * from "Column Family Name" where "ColumnName"='A variable which takes different values';
Any suggestions are welcome.
回答1:
No, CQL really doesn't have a way to define variables, run a loop, and update/query based on those variables.
As an alternative, I typically use the DataStax Python driver for simple tasks/scripts like this. Here is an excerpt from a Python script I used a while back 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, check the DataStax tutorial Getting Started with Apache Cassandra and Python.
回答2:
Yes, you can pass variable in the following way:
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()
来源:https://stackoverflow.com/questions/30373893/is-it-possible-to-use-variables-in-cql-commands-in-cql-scripts