Skip to main content

Install & Configure

Hint

This article is generated by AI translation.

Add Dependency

Before using jdbc-elastic, you need to add the corresponding Maven dependency to your project. Current version: 6.7.0

<dependency>
<groupId>net.hasor</groupId>
<artifactId>jdbc-elastic</artifactId>
<version>6.4.0</version>
</dependency>

JDBC Connection

Connect to ElasticSearch using the standard JDBC URL format:

jdbc:dbvisitor:elastic://<host>:<port>?<parameters>
  • host: ElasticSearch server address.
  • port: ElasticSearch server port (default 9200).
  • parameters: Connection parameters, see Connection Parameters for details.

Example Code

String url = "jdbc:dbvisitor:elastic://127.0.0.1:9200";
Properties props = new Properties();
props.setProperty("username", "elastic");
props.setProperty("password", "changeme");

try (Connection conn = DriverManager.getConnection(url, props)) {
try (Statement stmt = conn.createStatement()) {
String dsl = "POST /my_index/_search { \"query\": { \"match_all\": {} } }";
try (ResultSet rs = stmt.executeQuery(dsl)) {
while (rs.next()) {
System.out.println("ID: " + rs.getString("_ID"));
System.out.println("Source: " + rs.getString("_DOC"));
}
}
}
}

2. Using PreparedStatement (with Parameters)

jdbc-elastic supports ? placeholders in URL paths, JSON Body, and Hints.

String dsl = "POST /my_index/_search { \"query\": { \"term\": { \"user\": ? } } }";
try (PreparedStatement pstmt = conn.prepareStatement(dsl)) {
pstmt.setString(1, "kimchy");
try (ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
// ...
}
}
}

3. Insert/Update Documents

String insertSql = "POST /my_index/_doc/1 { \"user\": \"kimchy\", \"post_date\": \"2009-11-15T14:12:12\", \"message\": \"trying out Elasticsearch\" }";
try (Statement stmt = conn.createStatement()) {
stmt.executeUpdate(insertSql);
}

4. Index Management

try (Statement stmt = conn.createStatement()) {
stmt.execute("PUT /new_index");
stmt.execute("PUT /new_index/_mapping { \"properties\": { \"field1\": { \"type\": \"text\" } } }");
stmt.execute("DELETE /new_index");
}