lucene 应用
lucenedto 类 用于区分
增加索引:
储存文件
File indexFile = new File(indexDirPath + "/" + entity.getUrlType());
indexFile.mkdirs();
if (!indexFile.exists()) {
try {
indexFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
创建 Directory
Directory directory = null;
directory = new SimpleFSDirectory(indexFile);
索引配置:IndexWriterConfig indexWriterConfig = new IndexWriterConfig(
Version.LUCENE_30, analyzer);
创建索引模式:CREATE,覆盖模式; APPEND,追加模式
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.APPEND);
始化创建器
indexWriter = new IndexWriter(directory, indexWriterConfig);
增加Document
Document doc = new Document();
doc.add(new Field("userId", entity.getUserId(), Field.Store.YES,Field.Index.NOT_ANALYZED));
doc.add(new Field("url", url, Field.Store.YES,Field.Index.ANALYZED));
doc.add(new Field("title", title, Field.Store.YES,Field.Index.ANALYZED));
写入
indexWriter.addDocument(doc);
更新
Term term = new Term("id", entity.getUserID());
indexWriter.updateDocument(term, doc);
关闭
indexWriter.close();
删除索引:
Directory directory;
directory = new SimpleFSDirectory(indexDir);
indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
indexWriter = new IndexWriter(directory, indexWriterConfig);
Term term = new Term("id", entity. getUserId ());
indexWriter.deleteDocuments(term);
关闭
indexWriter.close();
查询检索
File indexFile = new File(indexDirPath + "/" +fileName);
打开
Directory dir = FSDirectory.open(indexFile);
IndexSearcher indexSearcher = new IndexSearcher(dir);