Sample gocql code to connect to a DataStax Astra database.
This code was created in response to a post on the DataStax Community site "How do I connect to Astra with the gocql driver?".
Satisfy the required Prerequisites in the next section.
Download astra_gocql_connect.go
then build it with:
$ go build astra_gocql_connect.go
Finally, run the executable:
$ ./astra_gocql_connect
-
To compile and run the code, download and install the Go language from https://golang.org/.
-
Install the gocql driver:
$ go get github.com/gocql/gocql
-
An Astra database. Launching an Apache Cassandra™ database only takes a few clicks.
It's free to try with no credit card required. Visit https://www.datastax.com/products/datastax-astra-beta for details.
-
Download the secure connect bundle for your Astra database.
Unzip your copy of
secure-connect-your_astra_db.zip
which will contain the following files:ca.crt cert cert.pfx config.json cqlshrc identity.jks key trustStore.jks
You will need these files to configure the SSL/TLS options.
The
cqlshrc
file contains the connection details for_cqlshrc_host
and_cqlshrc_port
in the code. Here is an example:[connection] hostname = 31fecf38-2491-4d43-b6ce-22562679f1b8-us-east1.db.astra.datastax.com port = 34567 ssl = true
-
To run the sample code as-is, create the table
cities_by_rank
. Note that you can use your own keyspace so modify the code accordingly.CREATE KEYSPACE community WITH replication = {'class': 'NetworkTopologyStrategy', 'caas-dc': '1'};
CREATE TABLE community.cities_by_rank ( rank int PRIMARY KEY, city text, country text );
Load the data in
cities_by_rank.csv
using the cqlshCOPY FROM
command:cqlsh> COPY cities_by_rank (rank,city,country) FROM './cities_by_rank.csv' WITH header = true;
The CSV file contains the top 10 most liveable cities of 2019 rated by The Independent.
rank | city | country
------+------------+-----------
1 | Vienna | Austria
2 | Melbourne | Australia
3 | Sydney | Australia
4 | Osaka | Japan
5 | Calgary | Canada
6 | Vancouver | Canada
7 | Toronto | Canada
8 | Tokyo | Japan
9 | Copenhagen | Denmark
10 | Adelaide | Australia
Source: Helen Coffey, 'This is the world's most liveable city', The Independent, 4 September 2019 (accessed 2 May 2020), https://www.independent.co.uk/travel/news-and-advice/vienna-city-best-quality-life-study-ranked-austria-sydney-melbourne-osaka-a9091016.html
Huge thanks to @dougwettlaufer from DataStax Cloud Engineering for his help with the solution.
If you have any questions, hit me up at DataStax Community. Cheers!