是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎(英文与德文两种西方语言)。Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能,或者是以此为基础创建起完整的全文检索引擎。算法
public static void createindex() throws Exception { //建立文件目录 建立在项目目录下的index中 Directory dir=FSDirectory.open(FileSystems.getDefault().getPath(System.getProperty("user.dir")+"/index")); //分词处理 是一个抽象类 一种单字分词,标准的 Analyzer analyzer=new IKAnalyzer(); //建立IndexWriterConfig对象 IndexWriterConfig config=new IndexWriterConfig(analyzer); //建立IndexWriter对象 IndexWriter iWriter=new IndexWriter(dir, config); //清除以前的索引 iWriter.deleteAll(); //建立文档对象 Document doc=new Document(); //向文档中添加文本内容字段,及字段类型 doc.add(new Field("fieldname","坚持到底gl博主的博文,转载请注释出处", TextField.TYPE_STORED)); //将文档添加到indexWriter中,写入索引文件中 iWriter.addDocument(doc); //关闭写入 iWriter.close(); }
这样运行能够看到你的索引index中的内容文件已经建立出来了数据库
索引已经建立,接下来查询一下试试索引 ,传入须要查询的词apache
public static void search(String string) throws Exception { Directory dir=FSDirectory.open(FileSystems.getDefault().getPath(System.getProperty("user.dir")+"/search")); //打开索引目录的 DirectoryReader dReader=DirectoryReader.open(dir); IndexSearcher searcher=new IndexSearcher(dReader); //第一个参数 field值 ,第二个参数用户须要检索的字符串 Term t=new Term("fieldname",string); //将用户须要索引的字符串封装成lucene能识别的内容 Query query=new TermQuery(t); //查询,最大的返回值10 TopDocs top=searcher.search(query, 10); //命中数,那个字段命中,命中的字段有几个 System.out.println("命中数:"+top.totalHits); //查询返回的doc数组 ScoreDoc[] sDocs= top.scoreDocs; for (ScoreDoc scoreDoc : sDocs) { //输出命中字段内容 System.out.println(searcher.doc(scoreDoc.doc).get(field)); } }
就这样一个全文检索的测试就出来了,多去思考总结,扩展出去数组
再给添加一个代码有益于理解架构
public static void main(String[] args) throws Exception { String chString="坚持到底的文章,转载请注释出处"; Analyzer analyzer=new IKAnalyzer(); TokenStream stream=analyzer.tokenStream("word", chString); stream.reset(); CharTermAttribute cta=stream.addAttribute(CharTermAttribute.class); while (stream.incrementToken()) { System.out.println(cta.toString()); } stream.close(); }
显示以下:工具
还能够添加这几个文件,有一点须要注意的是,注意你的编码格式学习
第一个:ext.dic 扩展词典,分词中那个须要组在一块儿的,如:分词处理可能将“坚持到底”四个字分为“坚持”和“到底”,能够在这个文件中直接添加坚持到底,就能够显示出坚持到底的这个索引测试
第三个:stopword.dic 扩展中止词典,分词中不想出现的,不但愿他被分开出现或单独的,能够往里面写,检索的时候就不会有优化
第二个:是指定上面两个扩展词典的编码
这些就是最基本掌握的内容,还有不少分词算法等类型,须要去扩展