Retrieve mean and standard deviation from Cassandra, writing values to a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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