SQL JDBC driver API

SQL JDBC driver - 图1info

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.23.0 or later. Note that starting with Avatica 1.21.0, you may need to set the transparent_reconnection property to true if you notice intermittent query failures.

Once you’ve downloaded the Avatica client jar, add it to your classpath.

Example connection string:

  1. jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/;transparent_reconnection=true

Or, to use the protobuf protocol instead of JSON:

  1. jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica-protobuf/;transparent_reconnection=true;serialization=protobuf

The url is the /druid/v2/sql/avatica/ endpoint on the Router, which routes JDBC connections to a consistent Broker. For more information, see Connection stickiness.

Set transparent_reconnection to true so your connection is not interrupted if the pool of Brokers changes membership, or if a Broker is restarted.

Set serialization to protobuf if using the protobuf endpoint.

Note that as of the time of this writing, Avatica 1.23.0, the latest version, does not support passing connection context parameters from the JDBC connection string to Druid. These context parameters must be passed using a Properties object instead. Refer to the Java code below for an example.

Example Java code:

  1. // Connect to /druid/v2/sql/avatica/ on your Broker.
  2. String url = "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/;transparent_reconnection=true";
  3. // Set any connection context parameters you need here.
  4. // Any property from https://druid.apache.org/docs/latest/querying/sql-query-context.html can go here.
  5. Properties connectionProperties = new Properties();
  6. connectionProperties.setProperty("sqlTimeZone", "Etc/UTC");
  7. //To connect to a Druid deployment protected by basic authentication,
  8. //you can incorporate authentication details from https://druid.apache.org/docs/latest/operations/security-overview
  9. connectionProperties.setProperty("user", "admin");
  10. connectionProperties.setProperty("password", "password1");
  11. try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
  12. try (
  13. final Statement statement = connection.createStatement();
  14. final ResultSet resultSet = statement.executeQuery(query)
  15. ) {
  16. while (resultSet.next()) {
  17. // process result set
  18. }
  19. }
  20. }

For a runnable example that includes a query that you might run, see Examples.

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:8888/druid/v2/sql/avatica-protobuf/;transparent_reconnection=true;serialization=protobuf";

SQL JDBC driver - 图2info

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. For an example of this, see Get the metadata for a datasource.

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();

Examples

The following section contains two complete samples that use the JDBC connector:

You can try out these examples after verifying that you meet the prerequisites.

For more information about the connection options, see Client Reference.

Prerequisites

Make sure you meet the following requirements before trying these examples:

  • A supported Java version

  • Avatica JDBC driver. You can add the JAR to your CLASSPATH directly or manage it externally, such as through Maven and a pom.xml file.

  • An available Druid instance. You can use the micro-quickstart configuration described in Quickstart (local). The examples assume that you are using the quickstart, so no authentication or authorization is expected unless explicitly mentioned.

  • The example wikipedia datasource from the quickstart is loaded on your Druid instance. If you have a different datasource loaded, you can still try these examples. You’ll have to update the table name and column names to match your datasource.

Get the metadata for a datasource

Metadata, such as column names, is available either through the INFORMATION_SCHEMA table or through connection.getMetaData(). The following example uses the INFORMATION_SCHEMA table to retrieve and print the list of column names for the wikipedia datasource that you loaded during a previous tutorial.

  1. import java.sql.*;
  2. import java.util.Properties;
  3. public class JdbcListColumns {
  4. public static void main(String[] args)
  5. {
  6. // Connect to /druid/v2/sql/avatica/ on your Router.
  7. // You can connect to a Broker but must configure connection stickiness if you do.
  8. String url = "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/;transparent_reconnection=true";
  9. String query = "SELECT COLUMN_NAME,* FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'wikipedia' and TABLE_SCHEMA='druid'";
  10. // Set any connection context parameters you need here.
  11. // Any property from https://druid.apache.org/docs/latest/querying/sql-query-context.html can go here.
  12. Properties connectionProperties = new Properties();
  13. try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
  14. try (
  15. final Statement statement = connection.createStatement();
  16. final ResultSet rs = statement.executeQuery(query)
  17. ) {
  18. while (rs.next()) {
  19. String columnName = rs.getString("COLUMN_NAME");
  20. System.out.println(columnName);
  21. }
  22. }
  23. } catch (SQLException e) {
  24. throw new RuntimeException(e);
  25. }
  26. }
  27. }

Query data

Now that you know what columns are available, you can start querying the data. The following example queries the datasource named wikipedia for the timestamps and comments from Japan. It also sets the query context parameter sqlTimeZone. Optionally, you can also parameterize queries by using dynamic parameters.

  1. import java.sql.*;
  2. import java.util.Properties;
  3. public class JdbcCountryAndTime {
  4. public static void main(String[] args)
  5. {
  6. // Connect to /druid/v2/sql/avatica/ on your Router.
  7. // You can connect to a Broker but must configure connection stickiness if you do.
  8. String url = "jdbc:avatica:remote:url=http://localhost:8888/druid/v2/sql/avatica/;transparent_reconnection=true";
  9. //The query you want to run.
  10. String query = "SELECT __time, isRobot, countryName, comment FROM wikipedia WHERE countryName='Japan'";
  11. // Set any connection context parameters you need here.
  12. // Any property from https://druid.apache.org/docs/latest/querying/sql-query-context.html can go here.
  13. Properties connectionProperties = new Properties();
  14. connectionProperties.setProperty("sqlTimeZone", "America/Los_Angeles");
  15. try (Connection connection = DriverManager.getConnection(url, connectionProperties)) {
  16. try (
  17. final Statement statement = connection.createStatement();
  18. final ResultSet rs = statement.executeQuery(query)
  19. ) {
  20. while (rs.next()) {
  21. Timestamp timeStamp = rs.getTimestamp("__time");
  22. String comment = rs.getString("comment");
  23. System.out.println(timeStamp);
  24. System.out.println(comment);
  25. }
  26. }
  27. } catch (SQLException e) {
  28. throw new RuntimeException(e);
  29. }
  30. }
  31. }