IndexWriter indexWriter = new IndexWriter(indexDir, new StandardAnalyzer(), false);
// 添加一個新記錄:
Document doc = new Document();
doc.add(Field.Keyword("title", title));
doc.add(Field.Text("content", content));
// 建立索引:
indexWriter.addDocument(doc);
// 關閉:
indexWriter.close();
要搜索文章非常簡單:
然后添加文章,讓對其索引:
String title = "文章標題" // 從數據庫讀取
String content = "文章內容" // 從數據庫讀取
// 打開索引:
IndexWriter indexWriter = new IndexWriter(indexDir, new StandardAnalyzer(), false);
// 添加一個新記錄:
Document doc = new Document();
doc.add(Field.Keyword("title", title));
doc.add(Field.Text("content", content));
// 建立索引:
indexWriter.addDocument(doc);
// 關閉:
indexWriter.close();
要搜索文章非常簡單:
Searcher searcher = new IndexSearcher(dir);
Query query = QueryParser.parse(keyword, "content", new StandardAnalyzer());
Hits hits = searcher.search(query);
if(hits != null){
for(int i = 0;i < hits.length(); i++){
Document doc = hits.doc(i);
System.out.println("found in " + doc.get("title"));
System.out.println(doc.get("content"));
}
}
searcher.close();
我們設計一個LuceneSearcher類封裝全文搜索功能,由于必須鎖定數據庫所在目錄,我們把數據庫設定在/WEB-INF/search/下,確保用戶不能訪問,并且在配置文件中初始化目錄:
<bean id="luceneSearcher" class="org.crystalblog.search.LuceneSearcher">
<property name="directory">
<value>/WEB-INF/search/</value>
</property>
</bean>
效果如下:
文章來源于領測軟件測試網 http://www.kjueaiud.com/