Search code examples
groovyinfluxdb

Influx DB 0.9 - specify Duration in Java Driver


I've got a question about retention policy and duration in InfluxDB. I'm using InfluxDB to write time data. The data is supposed to be taken from some text file in groovy, so I've used the following driver to work with Influx DB 0.9.4:

   <dependency>
        <groupId>org.influxdb</groupId>
        <artifactId>influxdb-java</artifactId>
        <version>2.0</version>
    </dependency>

Now I can insert the data (I'm using BatchPoints for this):

BatchPoints batchPoints = BatchPoints
                    .database(dbName)
                    .tag("async", "true")
                    .retentionPolicy("default")
                    .consistency(InfluxDB.ConsistencyLevel.ALL)
                    .build()     

List<Point> points = obtainAllMyMeasurementsHere()
points.each {p ->
   batchPoints.point(p)
}
influxClient.write(batchPoints)

So far so good, but now I want to delete my points automatically after, say 1 week.

As far as I understand I need to work with retention policy and duration but I can't understand where in java exactly I specify this. It looks like all the examples/tests of the java driver of influx db use the "default" retention policy.

So could someone provide a code snippet how am I supposed to create a retention policy from Java Driver? Is it possible?

Thanks


Solution

  • Influxdb java driver doesn't have a special API for creation of retention policy rules. Instead we should use a regular org.influxdb.dto.Query with probably a slightly redundant syntax (database name appears twice in the query creation code, see below).

    The algorithm is:

    1. Create a retention policy with a logical name on database with the help of the following code (groovy):
    
    
        String RETENTION_POLICY = "samplepolicy"
        String dbName = "sampledb"
        long ttl = 60 * 60 * 24 // one day ttl
        Query createRetentionPolicyQuery = new Query("CREATE RETENTION POLICY $RETENTION_POLICY ON $dbName DURATION ${ttl}s REPLICATION 1 DEFAULT", dbName)
    
        // create the policy:
        InfluxDB influxClient = createClient(...) // omitted for brevity
    
        QueryResult result = influxClient.query(createRetentionPolicyQuery)
            if(result.error != null) {
                throw new RuntimeException("Failed to create a retention policy on database $dbName. Reason: ${result.error}")
            }
    
    
    
    1. Now when the retention policy is created its possible to insert the data
    
          BatchPoints batchPoints = BatchPoints
          .database(dbName)
          .tag("async", "true")
          .retentionPolicy(RETENTION_POLICY)
          .consistency(InfluxDB.ConsistencyLevel.ALL)
          .build()