Updated on 2022-09-14 GMT+08:00

Querying Data

Function Description

You can use the OpenTSDB query API (/api/query) to read data.

Function genQueryReq () generates a query request, and function queryData() sends the query request to the OpenTSDB server.

Sample Code

The following code snippets are in the queryData method of the OpentsdbExample class in the com.huawei.bigdata.opentsdb.examples packet.

private void queryData(String dataPoint) {
  QUERY_URL = BASE_URL + dataPoint;
  LOG.info("start to query data in opentsdb, the url is " + QUERY_URL);
  try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    HttpPost httpPost = new HttpPost(QUERY_URL);//A timeout interval must be set for the request.
    addTimeout(httpPost);
    String queryRequest = genQueryReq();
    StringEntity entity = new StringEntity(queryRequest, "utf-8");
    entity.setContentType("application/json");
    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost);
    int statusCode = response.getStatusLine().getStatusCode();
    LOG.info("Status Code : " + statusCode);
    if (statusCode != HttpStatus.SC_OK) {
      LOG.info("Request failed! " + response.getStatusLine());
    }
    String body = EntityUtils.toString(response.getEntity(), "utf-8");
    LOG.info("Response content : " + body);
    LOG.info("query data to opentsdb successfully.");
  } catch (IOException e) {
    LOG.error("Failed to query data.", e);
  }
}

static class Query {
  public Long start;
  public Long end;
  public boolean delete = false;
  public List<SubQuery> queries;
}

static class SubQuery {
  public String metric;
  public String aggregator;
  public SubQuery(String metric, String aggregator) {
    this.metric = metric;
    this.aggregator = aggregator;
  }
}

String genQueryReq() {
  Query query = new Query();
  query.start = 1498838400L;
  query.end = 1498921200L;
  query.queries = ImmutableList.of(new SubQuery("city.temp", "sum"), new SubQuery("city.hum", "sum"));
  Gson gson = new Gson();
  return gson.toJson(query);
}