TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
- 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"));// 注意这里输出的是什么
- }
- }
- }
复制代码
源码下载:http://file.javaxxz.com/2014/11/4/000027390.zip |
|