@Test
public void saveIndex() throws Exception
{
File file = new File(indexPath);
FSDirectory dir = FSDirectory.getDirectory(file);
Document doc = File2DocumentUtils.file2Document(filePath);
IndexWriter indexWriter = new IndexWriter(dir, analyzer, MaxFieldLength.LIMITED);
indexWriter.addDocument(doc);
indexWriter.close();
}
@Test
public void deleteIndex() throws Exception
{
IndexWriter indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
Term term = new Term("path", filePath);
indexWriter.deleteDocuments(term);
indexWriter.close();
}
@Test
public void updateIndex() throws Exception
{
IndexWriter indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
Term term = new Term("path", filePath);
Document doc = File2DocumentUtils.file2Document(filePath);
//正直的更新是先删除在添加
indexWriter.updateDocument(term, doc);
indexWriter.close();
}
@Test
public void searchIndex() throws Exception
{
String queryString = "笑话";
// 把要搜索的文本解析成Query
String[] fields = {"name", "content"};
QueryParser queryParser = new MultiFieldQueryParser(fields, analyzer);
Query query = queryParser.parse(queryString);
// 进行查询
IndexSearcher indexSearcher = new IndexSearcher(indexPath);
Filter filter = null;
// 相当于一个List集合
TopDocs topDocs = indexSearcher.search(query, filter, 10000);
int firstResult = 0;
int max = 3;
int end = Math.min(firstResult+max, topDocs.totalHits);
// 打印结果
for (int i=firstResult; i<end;i++)
{
ScoreDoc scoreDoc = topDocs.scoreDocs[i];
int docSn = scoreDoc.doc;// 文档内部编号
Document doc = indexSearcher.doc(docSn); // 根据编号取出相应的文档
File2DocumentUtils.printDocumentInfo(doc);
}
System.out.println("总共有[" + topDocs.totalHits + "]条匹配结果");
}