|
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Date;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
public class SqlCon {
public static void main(String[] args) {
Date date1 = new Date();
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=pubs;user=sa;password=";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "SELECT TOP 10 * FROM users";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
IndexWriter writer = new IndexWriter("c://bat//index", new StandardAnalyzer());
while (rs.next()) {
Document doc = new Document();
doc.add(new Field("id", rs.getString("id"), Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("name", rs.getString("name"), Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("sex", rs.getString("sex"), Field.Store.YES, Field.Index.TOKENIZED));
doc.add(new Field("age", rs.getString("age"), Field.Store.YES, Field.Index.TOKENIZED));
writer.addDocument(doc);
}
writer.close();
Date date2 = new Date();
System.out.println("用时" + (date2.getTime() - date1.getTime()) + "毫秒索引已建立");
DoSearch();
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null)
try {
rs.close();
} catch (Exception e) {}
if (stmt != null)
try {
stmt.close();
} catch (Exception e) {}
if (con != null)
try {
con.close();
} catch (Exception e) {}
}
}
public static void DoSearch() throws IOException,ParseException{
IndexSearcher indexSearcher = new IndexSearcher("C://index");
QueryParser queryParser = new QueryParser("name",new StandardAnalyzer());
Query query = queryParser.parse("yxy");// 这个地方Query是抽象类大家也注意一下
Hits hits = indexSearcher.search(query);
//Document doc = null;
System.out.print("正搜索................");
System.out.println("找到了"+hits.length()+"个结果");
for (int i = 0;i < hits.length();i++)
{
Document doc = hits.doc(i);
System.out.println("内容是:" + doc.get("name"));// 注意这里输出的是什么
}
}
} |
|