【问题标题】:Is it possible to use variables in cql commands in cql scripts?是否可以在 cql 脚本中的 cql 命令中使用变量?
【发布时间】:2015-08-03 03:07:42
【问题描述】:

在 CQL 脚本中使用时,有没有办法在 CQL 命令中传递变量,例如:

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

欢迎提出任何建议。

【问题讨论】:

    标签: cassandra cql cqlsh


    【解决方案1】:

    不,CQL 确实没有办法定义变量、运行循环以及基于这些变量进行更新/查询。

    作为替代方案,我通常将DataStax Python driver 用于此类简单的任务/脚本。这是我不久前用来从 CSV 文件填充产品颜色的 Python 脚本的摘录。

    # 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)
    

    欲了解更多信息,请查看 DataStax 教程Getting Started with Apache Cassandra and Python

    【讨论】:

      【解决方案2】:

      是的,您可以通过以下方式传递变量:

      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()
      

      【讨论】:

        猜你喜欢
        • 2015-01-03
        • 1970-01-01
        • 2017-09-09
        • 2023-03-06
        • 1970-01-01
        • 2017-01-30
        • 2016-10-29
        • 2023-03-25
        相关资源
        最近更新 更多