本篇的代码相对简单,主要是先把lucene添加的demo给搭建起来,后续的修改,删除,查询会在后面的文章中一一补上,笔者以为学习这东西仍是得脚踏实地的一步一步来比较好,只要真真正正理解每一行代码的意思,咱们就算是有收获了,有时候学习步伐太快,反而会根基不牢,效果很差。java
须要准备的jar包apache
lucene-core-4.3.1.jar lucene-analyzers-common-4.3.1.jar
package com.qin; import java.io.File; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.StringField; import org.apache.lucene.document.Field.Store; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.util.Version; /** * Lucene的演示Demo类 * * **/ public class CommonLuceneBasic { /** * 抽象的父类文件夹 * */ public static Directory directory; /** * 返回IndexWriter * */ public static IndexWriter getWriter() throws Exception{ //设置标准分词器 ,默认是一元分词 Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_43); //设置IndexWriterConfig IndexWriterConfig iwc=new IndexWriterConfig(Version.LUCENE_43, analyzer); // iwc.setRAMBufferSizeMB(3);//设置缓冲区大小 return new IndexWriter(directory,iwc); } /** * @indexPath 索引存放路径 * **/ public static void add(String indexWriterPath){ IndexWriter writer=null; try{ directory=FSDirectory.open(new File(indexWriterPath));//打开存放索引的路径 writer=getWriter(); Document doc=new Document(); doc.add(new StringField("id", "1", Store.YES));//存储 doc.add(new StringField("name", "张飞", Store.YES));//存储 doc.add(new StringField("content", "也许放弃,才能靠近你!", Store.YES));//存储 writer.addDocument(doc);//添加进写入流里 writer.forceMerge(1);//优化压缩段,大规模添加数据的时候建议,少使用本方法,会影响性能 writer.commit();//提交数据 System.out.println("添加成功"); }catch(Exception e){ e.printStackTrace(); }finally{ if(writer!=null){ try{ writer.close();//关闭流 }catch(Exception e){ e.printStackTrace(); } } } } public static void main(String[] args) { String path="E:\\临时索引"; add(path);//调用添加方法 } }
添加成功以后,咱们就能够经过luke工具,进行索引查看。工具