Skip to main content

Install & Configure

Hint

This article is generated by AI translation.

Add Dependency

Before using jdbc-elastic, add the Maven dependency. Current version: 6.4.0

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

JDBC Connection

Use a standard JDBC URL to connect.

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

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()) {
// Execute DSL query
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")); // _DOC returns raw JSON
}
}
}
}

2. Using PreparedStatement (with parameters)

jdbc-elastic supports using ? as a placeholder in URL path, JSON Body, and Hint.

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 Document

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()) {
// Create Index
stmt.execute("PUT /new_index");

// Set Mapping
stmt.execute("PUT /new_index/_mapping { \"properties\": { \"field1\": { \"type\": \"text\" } } }");

// Delete Index
stmt.execute("DELETE /new_index");
}