《Lucene 2.9.1 完整示例及开发文档》为开发者提供了详尽的API参考和代码实例,帮助深入理解并高效使用Lucene进行全文搜索与索引构建。
以下是用于创建索引的示例代码:
```java
public static void createIndex(File src, File destDir) {
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT); // 创建一个语法分析器
IndexWriter iwriter = null;
Directory directory = null;
try {
directory = FSDirectory.open(destDir); // 将索引文件存储到磁盘目录
iwriter = new IndexWriter(directory, analyzer, true, IndexWriter.MaxFieldLength.UNLIMITED);
Document doc = new Document(); // 创建一个Document对象
doc.add(new Field(path, src.getCanonicalPath(), Field.Store.YES, Field.Index.NOT_ANALYZED));
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(src));
for(String str; (str = br.readLine()) != null;) {
sb.append(str).append(System.getProperty(line.separator));
}
doc.add(new Field(contents, sb.toString(), Field.Store.YES, Field.Index.ANALYZED));
iwriter.addDocument(doc); // 将Document存放到IndexWriter中
iwriter.optimize(); // 对索引进行优化
} catch (IOException e) {
e.printStackTrace();
} finally {
if (iwriter != null) {
try {
iwriter.close(); // 关闭IndexWriter时,才把内存中的数据写到文件
} catch (IOException e) {
e.printStackTrace();
}
}
if (directory != null) {
try {
directory.close(); // 关闭索引存放目录
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
以下是用于查询索引的示例代码:
```java
public static void searcher(String keyword, File indexDir) {
IndexSearcher isearcher = null;
Directory directory = null;
try{
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_CURRENT);
directory = FSDirectory.open(indexDir);
QueryParser parser = new QueryParser(Version.LUCENE_CURRENT, contents, analyzer);
Query query = parser.parse(keyword); // 获取查询对象
isearcher = new IndexSearcher(directory, true); // 创建索引搜索器
TopDocs ts = isearcher.search(query, null, 100);
int totalHits = ts.totalHits;
System.out.println(命中数: + totalHits);
ScoreDoc[] hits = ts.scoreDocs;
for (int i = 0; i < hits.length; i++) {
Document hitDoc = isearcher.doc(hits[i].doc);
System.out.println(hitDoc.getField(contents).stringValue());
}
} catch (IOException | ParseException e) {
e.printStackTrace();
} finally {
if (isearcher != null) {
try {
isearcher.close(); // 关闭搜索器
} catch (IOException e) {
e.printStackTrace();
}
}
if (directory != null) {
try {
directory.close(); //关闭索引存放目录
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
```
删除Lucene索引的方法可以通过`IndexWriter.deleteDocuments(Term term)`或使用`IndexReader.deleteDocuments(Term term)`来实现。这些方法会从指定的Term中删除所有相关的Document。