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>
效果如下:
文章来源于领测软件测试网 https://www.ltesting.net/