Lindorm搜尋引擎支援SQL JDBC訪問,本文介紹如何使用開源的Solr JDBC訪問Lindorm搜尋引擎。
前提條件
添加Maven依賴
在您的Java應用pom.xml
中添加如下依賴:
<dependency>
<groupId>com.aliyun.lindorm</groupId>
<artifactId>lindorm-all-client</artifactId>
<version>2.1.2</version>
</dependency>
建立索引
可以通過叢集管理頁面建立索引表,具體操作請參見管理索引表。
串連程式碼範例
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class SearchSqlDemo {
public static void main(String[] args) {
Connection pconn = null;
Statement stmt = null;
try {
//載入搜尋引擎Driver
Class.forName("com.aliyun.lindorm.search.client.Driver");
//配置Lindorm搜尋SQL地址
String url = "jdbc:lindorm:search:url=http://ld-xxxx:30070";
Properties props = new Properties();
//設定使用者名稱和密碼
props.put("user", "testuser");
props.put("password", "password");
//建立串連
pconn = DriverManager.getConnection(url, props);
//建立Statement
stmt = pconn.createStatement();
//建表
stmt.execute("create table if not exists test(c1 int, c2 varchar, primary key(c1))");
//單條寫入
stmt.execute("upsert into test(c1,c2) values(1,'深圳')");
stmt.execute("upsert into test(c1,c2) values(2,'上海')");
//批量寫入
stmt.execute("upsert into test(c1,c2) values(3,'北京'),(4,'廣州'),(5,'杭州')");
//查詢
ResultSet rs = stmt.executeQuery("select * from test order by c1 ");
System.out.println("#####before delete:");
while (rs.next()) {
System.out.println("c1=" + rs.getInt("c1") + ",c2=" + rs.getString("c2"));
}
//刪除記錄
stmt.execute("delete from test where c1 >3");
//查詢
rs = stmt.executeQuery("select * from test order by c1 ");
System.out.println("#####after delete:");
while (rs.next()) {
System.out.println("c1=" + rs.getInt("c1") + ",c2=" + rs.getString("c2"));
}
//刪表
stmt.execute("drop table if exists test");
} catch (Throwable e) {
e.printStackTrace();
} finally {
//清理Statement和串連
//注意:在實際環境中盡量通過串連池來避免頻繁建立和釋放串連,以便提升效能。
try {
if (stmt != null) {
stmt.close();
}
if (pconn != null) {
pconn.close();
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
}