public class FileIndexUtil { private static Directory directory = null; static { try { directory = FSDirectory.open(Paths.get("F://ysm//index"));//索引是写入硬盘还是内存中,5.5中用的是FSDirectory.open方法 } catch (IOException e) { e.printStackTrace(); } } public static Directory getDirectory(){ return directory; } public static void index(boolean hasNew){ IndexWriter writer = null; try { IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer()); writer = new IndexWriter(directory, iwc); if(hasNew) writer.deleteAll(); File file = new File("F://ysm//Lucene//test2");//建立索引的文件 Document doc = null;//索引以文档的形式保存,每个文档里面可以添加若干个field for(File f : file.listFiles()){ doc = new Document(); doc.add(new Field("content", new FileReader(f))); doc.add(new Field("name", f.getName(), Field.Store.YES, Field.Index.NOT_ANALYZED)); doc.add(new Field("path", f.getAbsolutePath(), Field.Store.YES, Field.Index.NOT_ANALYZED )); doc.add(new LongField("date", f.lastModified() ,Field.Store.YES)); doc.add(new IntField("size", (int) (f.length()), Field.Store.YES )); writer.addDocument(doc);//文档写入 } } catch (IOException e) { e.printStackTrace(); } finally { try { if(writer!=null) writer.close();//不要忘记了writer.close()方法,要不然索引不会建成功 } catch (IOException e) { e.printStackTrace(); } } } }
lucene5.5创建索引
最新推荐文章于 2024-07-17 09:52:01 发布