Skip to content

Instantly share code, notes, and snippets.

@metadaddy
Created August 18, 2016 18:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metadaddy/7ff67a1d43a6625e86e85828aede36a4 to your computer and use it in GitHub Desktop.
Save metadaddy/7ff67a1d43a6625e86e85828aede36a4 to your computer and use it in GitHub Desktop.
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.io.PrintWriter;
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-1.4.0.0/resources/";
private static final String cassandraHost = "192.168.69.141";
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 = results.one();
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);
}
Thread.sleep(sleepMillis);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment