34

I am trying to execute the CQL commands from shell script. I am able to connect to the cqlsh (CQL version i'm using is 1.1.18) but unable to send the queries to cql.

Any ideas or suggestion how to proceed on this? Do I need to connect to Cassandra and execute few commands (select/update ) with shell script ??

giampaolo
  • 6,906
  • 5
  • 45
  • 73
Immadisetty
  • 341
  • 1
  • 3
  • 3

5 Answers5

51
cqlsh -e "select * from ks.table limit 1;" > ~/output
Bob
  • 5,510
  • 9
  • 48
  • 80
zqhxuyuan
  • 611
  • 5
  • 4
  • 1
    The `-e` flag was not available on cqlsh in version 1.1.18 (which is what the OP's question is about). – Aaron Nov 24 '15 at 15:35
  • 10
    Sure, it wasn't available then. But it's incredibly useful to have the top Google results containing an up-to-date answer. The OP isn't going to accept any answer anyways. – Scott Prive Jul 01 '16 at 14:43
  • 1
    @Aaron My Cqlsh version is 4.1.1. Earlier -e used to work, Not sure what is causing the error now. I am using python 2.7 – SibiCoder Apr 05 '20 at 12:54
16

I'm not sure about Cassandra 1.1.18, but you should be able to accomplish this with the -f flag of cqlsh. Let's say have a file of CQL commands called "commands.cql". I can invoke those commands against my local Cassandra instance like this:

$ cqlsh -f commands.cql -u myusername -p mypassword localhost

If I wanted to invoke that from within a Bash script, the script's code would look something like this:

#!/bin/bash
cqlsh -f commands.cql -u myusername -p mypassword localhost

Save that as an executable file, and run it like any other.

Aaron
  • 55,518
  • 11
  • 116
  • 132
7

Need to connect to cassandra and execute few commands (select / update ) with shell script

You can execute your commands with shell script in next way:

echo "some QUERY; exit" | cqlsh CASSANDRA_HOST -u 'USER' -p 'PASS'
Aleksandr P.
  • 71
  • 1
  • 2
6

The "exit" command in the last suggestion is a bit hacky.

I would propose using xargs with cqlsh -e.

echo "some QUERY;" | xargs cqlsh CASSANDRA_HOST -u 'USER' -p 'PASS' -e

I recently had to use this approach when working with docker, because clqsh -f was not an option (too complex to configure access to the file needed).

arvydasj
  • 63
  • 1
  • 3
2
echo "some QUERY;" | xargs cqlsh CASSANDRA_HOST -u 'USER' -p 'PASS' -e

But what if you Cassandra instance is on a different server to where the shell script is being executed? (Specifically in StreamSets - wouldn't the above require Cassandra installed on the same server such that it has access to the cqlsh lib?)