Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: expose /query endpoint to use InfluxQL (#365) #366

Merged
merged 3 commits into from
Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## 6.5.0 [unreleased]

### Features
1. [#366](https://github.com/influxdata/influxdb-client-java/pull/356): Added an endpoint to query with InfluxQL (v1) for more info see [README.md](./client).

### Dependencies
Update dependencies:

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ This section contains links to the client library documentation.

- InfluxDB 2.x client
- Querying data using the Flux language
- Querying data using the InfluxQL
Andy2003 marked this conversation as resolved.
Show resolved Hide resolved
- Writing data using
- [Line Protocol](https://docs.influxdata.com/influxdb/v1.6/write_protocols/line_protocol_tutorial/)
- [Data Point](https://github.com/influxdata/influxdb-client-java/blob/master/client/src/main/java/org/influxdata/client/write/Point.java#L46)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ public abstract class AbstractQueryApi extends AbstractRestClient {

};
protected static final String DEFAULT_DIALECT;

static {
Map<String, Object> dialect = new HashMap<>();
dialect.put("header", true);
Expand Down Expand Up @@ -107,7 +108,7 @@ protected RequestBody createBody(@Nullable final String dialect, @Nonnull final

if (dialect != null && !dialect.isEmpty()) {
JsonElement dialectJson = new Gson().fromJson(dialect, JsonElement.class);
json.add("dialect", dialectJson);
json.add("dialect", dialectJson);
}

return createBody(json.toString());
Expand Down Expand Up @@ -156,11 +157,11 @@ protected RawIterator queryRawIterator(@Nonnull final Call<ResponseBody> queryCa
return new RawIterator(queryCall, ERROR_CONSUMER);
}

private void query(@Nonnull final Call<ResponseBody> query,
@Nonnull final BiConsumer<Cancellable, BufferedSource> consumer,
@Nonnull final Consumer<? super Throwable> onError,
@Nonnull final Runnable onComplete,
@Nonnull final Boolean asynchronously) {
protected void query(@Nonnull final Call<ResponseBody> query,
@Nonnull final BiConsumer<Cancellable, BufferedSource> consumer,
@Nonnull final Consumer<? super Throwable> onError,
@Nonnull final Runnable onComplete,
@Nonnull final Boolean asynchronously) {

Arguments.checkNotNull(query, "query");
Arguments.checkNotNull(consumer, "consumer");
Expand Down Expand Up @@ -262,7 +263,7 @@ private void parseFluxResponseToLines(@Nonnull final Consumer<String> onResponse
}
}

private class DefaultCancellable implements Cancellable {
private static class DefaultCancellable implements Cancellable {

private volatile boolean wasCancelled = false;

Expand Down Expand Up @@ -394,4 +395,4 @@ record = fluxRecordOrTable.record;
return record != null;
}
}
}
}
196 changes: 196 additions & 0 deletions client-core/src/main/java/com/influxdb/query/InfluxQLQueryResult.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
/*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.influxdb.query;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.influxdb.utils.Arguments;

/**
* This class represents the result of an InfluxQL query.
*/
public final class InfluxQLQueryResult {

private final List<Result> results;

public InfluxQLQueryResult(@Nonnull final List<Result> results) {
Arguments.checkNotNull(results, "results");

this.results = results;
}

/**
* @return the results
*/
@Nonnull
public List<Result> getResults() {
return this.results;
}

/**
* Represents one result of an InfluxQL query.
*/
public static final class Result {
private final List<Series> series;

private final int index;

public Result(final int index, @Nonnull final List<Series> series) {
Arguments.checkNotNull(series, "series");

this.index = index;
this.series = series;
}

/**
* @return the index of the result
*/
public int getIndex() {
return index;
}

/**
* @return the series
*/
@Nonnull
public List<Series> getSeries() {
return this.series;
}

}

/**
* Represents one series within the {@link Result} of an InfluxQL query.
*/
public static final class Series {
@Nonnull
private final Map<String, Integer> columns;

@Nonnull
private final String name;

private final List<Record> values;

public Series(final @Nonnull String name, final @Nonnull Map<String, Integer> columns) {
Arguments.checkNotNull(name, "name");
Arguments.checkNotNull(columns, "columns");

this.name = name;
this.columns = columns;
this.values = new ArrayList<>();
}

/**
* @return the name
*/
@Nonnull
public String getName() {
return this.name;
}

/**
* @return the columns
*/
@Nonnull
public Map<String, Integer> getColumns() {
return this.columns;
}


/**
* @return the values
*/
@Nonnull
public List<Record> getValues() {
return this.values;
}

public void addRecord(@Nonnull final Record record) {
Arguments.checkNotNull(record, "record");

this.values.add(record);
}

/**
* A value extractor is used to convert the string value returned by query into a custom type.
*/
@FunctionalInterface
public interface ValueExtractor {
Andy2003 marked this conversation as resolved.
Show resolved Hide resolved

/**
* The value extractor is called for each resulting column to convert the string value returned by query
* into a custom type.
*
* @param columnName the name of the column
* @param rawValue the string value returned from the query
* @param resultIndex the index of the result
* @param seriesName the name of the series
* @return the converted string value
*/
@Nullable
Object extractValue(
@Nonnull String columnName,
@Nonnull String rawValue,
int resultIndex,
@Nonnull String seriesName);
}

/**
* Represents one data record within a {@link Series} of an InfluxQL query.
*/
public final class Record {
private final Object[] values;

public Record(final Object[] values) {
this.values = values;
}

/**
* Get value by key.
*
* @param key of value in CSV response
* @return value
*/
@Nullable
public Object getValueByKey(@Nonnull final String key) {

Arguments.checkNonEmpty(key, "key");

Integer index = columns.get(key);
if (index == null) {
return null;
}
return values[index];
}

public Object[] getValues() {
return values;
}
}

}

}
68 changes: 68 additions & 0 deletions client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The reference Java client that allows query, write and management (bucket, organ

- [Querying data using Flux language](#queries)
- [Parameterized Queries](#parameterized-queries)
- [Querying data using InfluxQL](#influxql-queries)
- [Writing data using](#writes)
- [Line Protocol](#by-lineprotocol)
- [Data Point](#by-data-point)
Expand Down Expand Up @@ -411,6 +412,73 @@ public class ParameterizedQuery {
}
```

### InfluxQL Queries
Andy2003 marked this conversation as resolved.
Show resolved Hide resolved

The `InfluxQL` can be used with `/query compatibility` endpoint which uses the **database** and **retention policy** specified in the query request to map the request to an InfluxDB bucket.
For more information, see: .

- [/query 1.x compatibility API](https://docs.influxdata.com/influxdb/latest/reference/api/influxdb-1x/query/)
- [Database and retention policy mapping](https://docs.influxdata.com/influxdb/latest/reference/api/influxdb-1x/dbrp/)

This is an example of how to use this library to run a query with influxQL:

```java
package example;

import java.math.BigDecimal;
import java.time.Instant;

import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.InfluxQLQueryApi;
import com.influxdb.client.domain.InfluxQLQuery;
import com.influxdb.query.InfluxQLQueryResult;

public class InfluxQLExample {

private static char[] token = "my-token".toCharArray();
private static String org = "my-org";

private static String database = "my-org";

public static void main(final String[] args) {

try (InfluxDBClient influxDBClient = InfluxDBClientFactory.create("http://localhost:8086", token, org)) {

//
// Query data
//
String influxQL = "SELECT FIRST(\"free\") FROM \"influxql\"";

InfluxQLQueryApi queryApi = influxDBClient.getInfluxQLQueryApi();

// send request
InfluxQLQueryResult result = queryApi.query(new InfluxQLQuery(influxQL, database).setPrecision(InfluxQLQuery.InfluxQLPrecision.SECONDS),
(columnName, rawValue, resultIndex, seriesName) -> {
// convert columns
switch (columnName) {
case "time":
return Instant.ofEpochSecond(Long.parseLong(rawValue));
case "first":
return new BigDecimal(rawValue);
default:
throw new IllegalArgumentException("unexpected column " + columnName);
}
});

for (InfluxQLQueryResult.Result resultResult : result.getResults()) {
for (InfluxQLQueryResult.Series series : resultResult.getSeries()) {
for (InfluxQLQueryResult.Series.Record record : series.getValues()) {
System.out.println(record.getValueByKey("time") + ": " + record.getValueByKey("first"));
}
}
}

}
}
}
```

## Writes

The client offers two types of API to ingesting data:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.influxdb.client.service;

import javax.annotation.Nonnull;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.*;

public interface InfluxQLQueryService {

/**
* @param db Bucket to query (required)
* @param query (required)
* @param retentionPolicy Retention policy name (optional)
* @param zapTraceSpan OpenTracing span context (optional)
* @return response in csv format
*/
@Headers({ "Accept:application/csv", "Content-Type:application/vnd.influxql" })
@POST("query")
Call<ResponseBody> query(
@Body String query,
@Nonnull @Query("db") String db,
@Query("rp") String retentionPolicy,
@Query("epoch") String epoch,
@Header("Zap-Trace-Span") String zapTraceSpan
);

}
Loading