API usage

edit

This functionality is in technical preview and may be changed or removed in a future release. Elastic will work to fix any issues, but features in technical preview are not subject to the support SLA of official GA features.

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

java.sql

edit

The former through java.sql.Driver and DriverManager:

String address = "jdbc:es://" + elasticsearchAddress;     
Properties connectionProperties = connectionProperties(); 
Connection connection =
    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

edit

Accessible through the javax.sql.DataSource API:

JdbcDataSource dataSource = new JdbcDataSource();
String address = "jdbc:es://" + elasticsearchAddress;     
dataSource.setUrl(address);
Properties connectionProperties = connectionProperties(); 
dataSource.setProperties(connectionProperties);
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 parameters 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 parameters.

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

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

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

try (Statement statement = connection.createStatement();
        ResultSet results = statement.executeQuery(
              "   SELECT name, page_count"
            + "     FROM library"
            + " ORDER BY page_count DESC"
            + "    LIMIT 1")) {
    assertTrue(results.next());
    assertEquals("Don Quixote", results.getString(1));
    assertEquals(1072, results.getInt(2));
    SQLException e = expectThrows(SQLException.class, () ->
        results.getInt(1));
    assertThat(e.getMessage(), containsString("Unable to convert "
        + "value [Don Quixote] of type [VARCHAR] to an Integer"));
    assertFalse(results.next());
}