在Lucence中,对索引的操作就像普通数据库的Dao层的CRUD,于是把这块的代码提取出来,以便复用。这里没有太多的文字描述,基本就是代码的堆积。
注意一点:Term是搜索的最小单位,代表某个 Field 中的一个关键词,如:<title, lucene>
1、创建索引:
/**
* 添加/创建索引
*
* @param doc
*/
public void save(Document doc) {
IndexWriter indexWriter = null;
try {<span style="white-space:pre"> </span>//MaxFieldLength.LIMITED表示只对前10000个字做索引
<span style="white-space:pre"> </span>//参数true表示是否删除原来的索引后再重新创建,没有参数true,添加索引
indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
indexWriter.addDocument(doc);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
indexWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2、删除索引:
/**
* Term是搜索的最小单位,代表某个 Field 中的一个关键词,如:<title, lucene>
*
* new Term( "title", "lucene" );
*
* new Term( "id", "5" );
*
* new Term( "id", UUID );
*
* @param term
*/
public void delete(Term term) {
IndexWriter indexWriter = null;
try {
indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
indexWriter.deleteDocuments(term);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
indexWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3、更新索引:
/**
* 更新索引
*
* <pre>
* indexWriter.deleteDocuments(term);
* indexWriter.addDocument(doc);
* </pre>
*
* @param term
* @param doc
*/
public void update(Term term, Document doc) {
IndexWriter indexWriter = null;
try {
indexWriter = new IndexWriter(indexPath, analyzer, MaxFieldLength.LIMITED);
indexWriter.updateDocument(term, doc);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
indexWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class IndexDao {
String indexPath = "。。。。。";
// Analyzer analyzer = new StandardAnalyzer();
Analyzer analyzer = new MMAnalyzer();// 词库分词
}
总结:
这里只针对索引的增删改做封装,关于查询内容比较多,单独在后面的博客中介绍。