全文索引应用程序示例

在这一节中我们将给出一个应用全文索引的完整例子。 在示例中,我们读取docx文件,写到数据库中,然后建立全文索引,查询全文索引。

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class FullTextTest {
    protected static String host = "localhost";
    protected static String port = "2003";
    protected static String db = "osrdb";
    protected static String user = "sysdba";
    protected static String passwd = "szoscar55";

    public static Connection getConn() throws SQLException {
        String driver = "com.oscar.Driver";
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new SQLException("Driver not found: " + driver);
        }

        StringBuilder url = new StringBuilder("jdbc:oscar://");
        url.append(host);
        url.append(":");
        url.append(port);
        url.append("/");
        url.append(db);

        Properties properties = new Properties();
        properties.setProperty("user", user);
        properties.setProperty("password", passwd);
        return DriverManager.getConnection(url.toString(), properties);
    }

    public void testDoc() {
        Connection conn = null;
        try {
            conn = getConn();
            Statement st = conn.createStatement();
            // 初始化表和数据
            st.execute("create table FULLTEXT_T(id int , doc blob)");
            // docx文件中包含了"神通"两个字
            File docfile = new File("C:\\Users\\Administrator\\Desktop\\1.docx");
            DataInputStream dis = new DataInputStream(new FileInputStream(docfile));
            byte[] bytes = new byte[(int) docfile.length()];
            dis.readFully(bytes);
            dis.close();
            PreparedStatement ps = conn.prepareStatement("insert into FULLTEXT_T values(?,?)");
            // 第一行插入docx文件
            ps.setInt(1, 1);
            ps.setBytes(2, bytes);
            ps.execute();
            // 作为对比,第二行插入一行任意字符串
            ps.setInt(1, 2);
            ps.setBytes(2, "这是一行测试数据".getBytes());
            ps.execute();

            // 创建全文索引
            st.execute("create fulltext index t_idx on FULLTEXT_T(doc) ANALYZER CJKAnalyzer");

            // 查询
            ResultSet res = st.executeQuery("select id from FULLTEXT_T where contains(doc,'神通') >0");
            boolean success = true;
            while (res.next()) {
                // 预期应该只命中第一行
                if (res.getInt(1) != 1) {
                    success = false;
                }
            }
            System.out.println("查询结果正确?:" + success);
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        FullTextTest test = new FullTextTest();
        test.testDoc();
    }

}