又是轮子(不过是自备): lucene3.0搜索数据库(最简单形式)

用lucene 搜索数据库主要分三步
1、第一步:拿出数据集
2、第二步:创建索引
3、第三步:搜索



第一步:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(url, user, password);
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();


第二步:
Directory directory = FSDirectory.open(new File(buildIndexFilePath));
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
IndexWriter indexWriter = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
while(resultSet.next()) {
    Document document = new Document();
    document.add(new Field("bankId", "" + resultSet.getString("BANK_ID"), Field.Store.YES , Field.Index.NO , Field.TermVector.NO));
    document.add(new Field("bankName", "" + resultSet.getString("BANK_NAME"), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
    document.add(new Field("isSupportPassword", "" + resultSet.getString("IS_SUPPORT_PASSWORD"), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_OFFSETS));
    document.add(new Field("payType", "" + resultSet.getString("PAY_TYPE"), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
    indexWriter.addDocument(document);
}
indexWriter.optimize();
indexWriter.close();
resultSet.close();
statement.close();
connection.close();


第三步:

			//查询结果
			IndexReader indexReader = IndexReader.open(directory);
			IndexSearcher indexSearcher = new IndexSearcher(indexReader); 
			QueryParser queryParser = new QueryParser(Version.LUCENE_30, "bankName", analyzer);
			Query query = queryParser.parse("中信银行");
			TopScoreDocCollector collector = TopScoreDocCollector.create(1000 , false);
			indexSearcher.search(query, collector);
			ScoreDoc[] scoreDocs = collector.topDocs().scoreDocs;
			int numTotalHits = collector.getTotalHits();   
			System.out.println("共检索到的数量:" + numTotalHits);
			for(int i=0; i<scoreDocs.length; i++) {
				Document resultDocument = indexSearcher.doc(scoreDocs[i].doc);
				String str = resultDocument.get("bankId");
				String str2 = resultDocument.get("bankName");
				System.out.println("str: " + str + " <> " + str2);
			}




三步完成后,可以将结果放到list或者其它集合中,然后再页面中显示!

再来一个spring 定时器入门例子,嘿嘿,

有机会可以 用来 及时追加 数据库索引.

关于lucene3.0的排序,我纠结了好久,最后通过以下代码完成,原理,就是将时间转化为字符串,完毕
//按照时间的正序排列,如果SortField的第三个参数为true , 则为倒序
			SortField sortField = new SortField("createDate", SortField.STRING, false);
			Sort sort = new Sort ();  
			sort.setSort(sortField);
			TopDocs topDocs = indexSearcher.search(query, null, 100, sort);
			ScoreDoc[] scoreDocs = topDocs.scoreDocs;



你可能感兴趣的:(spring,oracle,sql,jdbc,Lucene)