lucene是什麼?lucene是一個開源的,普遍應用的,對數據進行索引、查詢的一個框架,更詳細的介紹請查看www.lucene.com.數據庫
下面簡單的描述一下索引和查詢過程。框架
1. 作索引簡單過程:優化
//獲取索引存儲路徑.net
String strindexDir = 「」;對象
File indexDir = new File(strindexDir);blog
// 分詞器
Analyzer analyzer = new PaodingAnalyzer(); // 中文分詞 庖丁解牛索引
//獲取寫索引對象,準備開始作索引,索引對象至關於數據庫中的表
indexWriter = new IndexWriter(indexDir, analyzer, true);資源
//構造Document對象,Document至關於數據庫中 的一條記錄
Document doc = new Document();get
// 給記錄中的字段賦值
doc.add(new Field(「name」, "value", Field.Store.NO, Field.Index.ANALYZED));it
doc.add(new Field(「name」, "value", Field.Store.NO, Field.Index.ANALYZED));
//表記錄加入表中
indexWriter.addDocument(doc);
// 作完索引以後,對索引進行優化
indexWriter.optimize();
//關閉資源
indexWriter.close();
2.查詢過程
//存放查詢結果
List<HashMap<String, String>> rs = new ArrayList<HashMap<String, String>>();
//獲取分析器,作索引的時候須要分析,查詢的時候也須要分析
Analyzer analyzer = new PaodingAnalyzer();
//構造查詢對象,queryField是查詢那個Field,至關於數據記錄的哪一個字段,q是查詢關鍵字
query = new QueryParser(queryField, analyzer).parse(q);
//下面這句是能夠看到對查詢關鍵字的分析
System.out.println("query key analyze result: " + query.toString());
//獲取索引對象,進行查詢
IndexReader reader = IndexReader.open(indexDir);
Searcher searcher = new IndexSearcher(reader);
Hits hits = searcher.search(query);
searcher.close();
//從查詢結果中獲取信息
Document doc = null;
HashMap<String, String> item = new HashMap<String, String>();
item.put("name", "value");
item.put("name", "value");
rs.add(item);
//釋放資源
reader.close();
作索引,查詢就被這麼短短几行搞定, 如此看來,lucene好簡單,甚強大。其實否則,要遊刃有餘,需深刻磨練。
附上俺的demo。
原文地址:http://blog.csdn.net/hong201/article/details/4015301