API usage

One can use JDBC through the official java.sql and javax.sql packages:

java.sql

The former through java.sql.Driver and DriverManager:

  1. String address = "jdbc:es://" + elasticsearchAddress;
  2. Properties connectionProperties = connectionProperties();
  3. Connection connection =
  4. DriverManager.getConnection(address, connectionProperties);

The server and port on which Elasticsearch is listening for HTTP traffic. The port is by default 9200.

Properties for connecting to Elasticsearch. An empty Properties instance is fine for unsecured Elasticsearch.

javax.sql

Accessible through the javax.sql.DataSource API:

  1. EsDataSource dataSource = new EsDataSource();
  2. String address = "jdbc:es://" + elasticsearchAddress;
  3. dataSource.setUrl(address);
  4. Properties connectionProperties = connectionProperties();
  5. dataSource.setProperties(connectionProperties);
  6. Connection connection = dataSource.getConnection();

The server and port on which Elasticsearch is listening for HTTP traffic. By default 9200.

Properties for connecting to Elasticsearch. An empty Properties instance is fine for unsecured Elasticsearch.

Which one to use? Typically client applications that provide most configuration properties in the URL rely on the DriverManager-style while DataSource is preferred when being passed around since it can be configured in one place and the consumer only has to call getConnection without having to worry about any other properties.

To connect to a secured Elasticsearch server the Properties should look like:

  1. Properties properties = new Properties();
  2. properties.put("user", "test_admin");
  3. properties.put("password", "x-pack-test-password");

Once you have the connection you can use it like any other JDBC connection. For example:

  1. try (Statement statement = connection.createStatement();
  2. ResultSet results = statement.executeQuery(
  3. " SELECT name, page_count"
  4. + " FROM library"
  5. + " ORDER BY page_count DESC"
  6. + " LIMIT 1")) {
  7. assertTrue(results.next());
  8. assertEquals("Don Quixote", results.getString(1));
  9. assertEquals(1072, results.getInt(2));
  10. SQLException e = expectThrows(SQLException.class, () ->
  11. results.getInt(1));
  12. assertThat(e.getMessage(), containsString("Unable to convert "
  13. + "value [Don Quixote] of type [TEXT] to [Integer]"));
  14. assertFalse(results.next());
  15. }

Elasticsearch SQL doesn’t provide a connection pooling mechanism, thus the connections the JDBC driver creates are not pooled. In order to achieve pooled connections, a third-party connection pooling mechanism is required. Configuring and setting up the third-party provider is outside the scope of this documentation.