Lindorm搜索引擎支持SQL JDBC访问,本文介绍如何使用开源的Solr JDBC访问Lindorm搜索引擎。

前提条件

  • 已开通Lindorm搜索引擎,具体操作请参见开通指南
  • 已将客户端的IP地址加入到Lindorm实例的白名单中,具体操作,请参见设置白名单
  • 已获取Lindorm搜索SQL地址,具体操作,请参见查看连接地址

添加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();
            }
        }
    }
}