Skip to content

Instantly share code, notes, and snippets.

Created August 18, 2016 18:42
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Retrieve mean and standard deviation from Cassandra, writing values to a file
package com.streamsets.example.cassandra;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import java.util.Date;
public class GetMeanSD {
private static final long timeRangeMillis = 3600L * 1000L;
private static final long sleepMillis = 60L * 1000L;
private static final int sensorId = 1;
private static final String resourceDir = "/home/pi/streamsets-datacollector-";
private static final String cassandraHost = "";
private static final String keyspace = "mykeyspace";
public static void main(String[] args) throws Exception {
Cluster cluster = Cluster.builder().addContactPoint(cassandraHost).build();
Session session = cluster.connect(keyspace);
// Use a PreparedStatement since we'll be issuing the same query many times
PreparedStatement statement = session.prepare("SELECT COUNT(*), AVG(temperature), STDEV(temperature) " +
"FROM sensor_readings " +
"WHERE sensor_id = ? " +
"AND TIME > ?");
BoundStatement boundStatement = new BoundStatement(statement);
while (true) {
long startMillis = System.currentTimeMillis() - timeRangeMillis;
ResultSet results = session.execute(boundStatement.bind(sensorId, new Date(startMillis)));
Row row =;
long count = row.getLong("count");
double avg = row.getDouble("system.avg(temperature)"),
sd = row.getDouble("mykeyspace.stdev(temperature)");
System.out.println("COUNT: "+count+", AVG: "+avg+", SD: "+sd);
try (PrintWriter writer = new PrintWriter(resourceDir + "mean.txt", "UTF-8")) {
writer.format("%g", avg);
try (PrintWriter writer = new PrintWriter(resourceDir + "sd.txt", "UTF-8")) {
writer.format("%g", sd);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment