SQL JDBC driver API

Apache Druid supports two query languages: Druid SQL and native queries. This document describes the SQL language.

You can make Druid SQL queries using the Avatica JDBC driver. We recommend using Avatica JDBC driver version 1.17.0 or later. Note that as of the time of this writing, Avatica 1.17.0, the latest version, does not support passing connection string parameters from the URL to Druid, so you must pass them using a Properties object. Once you’ve downloaded the Avatica client jar, add it to your classpath and use the connect string jdbc:avatica:remote:url=http://BROKER:8082/druid/v2/sql/avatica/.

Example code:

  1. // Connect to /druid/v2/sql/avatica/ on your Broker.
  2. String url = "jdbc:avatica:remote:url=http://localhost:8082/druid/v2/sql/avatica/";
  3. // Set any connection context parameters you need here
  4. // Or leave empty for default behavior.
  5. Properties connectionProperties = new Properties();
  6. try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
  7. try (
  8. final Statement statement = connection.createStatement();
  9. final ResultSet resultSet = statement.executeQuery(query)
  10. ) {
  11. while (resultSet.next()) {
  12. // process result set
  13. }
  14. }
  15. }

It is also possible to use a protocol buffers JDBC connection with Druid, this offer reduced bloat and potential performance improvements for larger result sets. To use it apply the following connection url instead, everything else remains the same

  1. String url = "jdbc:avatica:remote:url=http://localhost:8082/druid/v2/sql/avatica-protobuf/;serialization=protobuf";

The protobuf endpoint is also known to work with the official Golang Avatica driver

Table metadata is available over JDBC using connection.getMetaData() or by querying the “INFORMATION_SCHEMA” tables.

Connection stickiness

Druid’s JDBC server does not share connection state between Brokers. This means that if you’re using JDBC and have multiple Druid Brokers, you should either connect to a specific Broker, or use a load balancer with sticky sessions enabled. The Druid Router process provides connection stickiness when balancing JDBC requests, and can be used to achieve the necessary stickiness even with a normal non-sticky load balancer. Please see the Router documentation for more details.

Note that the non-JDBC JSON over HTTP API is stateless and does not require stickiness.

Dynamic parameters

You can use parameterized queries in JDBC code, as in this example:

  1. PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) AS cnt FROM druid.foo WHERE dim1 = ? OR dim1 = ?");
  2. statement.setString(1, "abc");
  3. statement.setString(2, "def");
  4. final ResultSet resultSet = statement.executeQuery();