加载中

API 使用方法

可以通过官方的 java.sqljavax.sql 包使用 JDBC

前者通过 java.sql.DriverDriverManager 实现

String address = "jdbc:es://" + elasticsearchAddress;
Properties connectionProperties = connectionProperties();
Connection connection =
    DriverManager.getConnection(address, connectionProperties);
		
  1. Elasticsearch 监听 HTTP 流量的服务器和端口。默认端口为 9200。
  2. 用于连接到 Elasticsearch 的属性。对于未启用安全的 Elasticsearch,使用空的 Properties 实例即可。

可以通过 javax.sql.DataSource API 进行访问

EsDataSource dataSource = new EsDataSource();
String address = "jdbc:es://" + elasticsearchAddress;
dataSource.setUrl(address);
Properties connectionProperties = connectionProperties();
dataSource.setProperties(connectionProperties);
Connection connection = dataSource.getConnection();
		
  1. Elasticsearch 监听 HTTP 流量的服务器和端口。默认为 9200。
  2. 用于连接到 Elasticsearch 的属性。对于未启用安全的 Elasticsearch,使用空的 Properties 实例即可。

应该使用哪一个?通常,在 URL 中提供大部分配置属性的客户端应用程序依赖于 DriverManager 风格,而当需要在组件间进行传递时,DataSource 更受青睐,因为它可以在一处进行配置,使用者只需调用 getConnection,而无需担心任何其他属性。

要连接到受保护的 Elasticsearch 服务器,Properties 应当如下所示

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

获取连接后,您可以像使用任何其他 JDBC 连接一样使用它。例如

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 [TEXT] to [Integer]"));
    assertFalse(results.next());
}
		
注意

Elasticsearch SQL 不提供连接池机制,因此 JDBC 驱动程序创建的连接不会被池化。为了实现连接池,需要第三方连接池机制。配置和设置第三方提供程序不在本文档的讨论范围内。

© . This website operates independently and is not affiliated with or endorsed by Elasticsearch B.V. All brand names, logos, and trademarks are the property of their respective owners.