Lucene包含两部分内容:创建索引、检索。
package demo.mytest.lucene; import java.io.IOException; import java.nio.file.FileSystems; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.OffsetAttribute; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.highlight.Encoder; import org.apache.lucene.search.highlight.Formatter; import org.apache.lucene.search.highlight.Fragmenter; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.Scorer; import org.apache.lucene.search.highlight.SimpleFragmenter; import org.apache.lucene.search.highlight.SimpleHTMLEncoder; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.IOContext; import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.BytesRef; import org.junit.Test; import demo.mytest.lucene.utils.LuceneUtils; public class HelloWorld { public static final String dataDir = "F:\\workspace\\luceneDemo\\dataDir\\CHANGES.txt";//文档所在路径 CHANGES.txt public static final String dataDir2 = "F:\\workspace\\luceneDemo\\dataDir\\bye.txt"; public static final String indexDir = "F:\\workspace\\luceneDemo\\indexDir";//索引文件存储位置 public static final Analyzer analyzer = new StandardAnalyzer(); /** * * testCreateIndex 创建索引库 * * @Description * @throws Exception void * @see */ @Test public void testCreateIndex() throws Exception { IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setOpenMode(OpenMode.CREATE);//设置indexWriter的打开方式,是新建或覆盖(CREATE)?是追加(APPEND)?还是两者结合(CREATE_OR_APPEND)? Directory directory = this.getFsIndexDirectory();//将索引文件保存的指定路径 IndexWriter indexWriter = new IndexWriter(directory, config);//创建indexWriter对象 // indexWriter.deleteAll();//删除索引库的所有文件 Document doc = LuceneUtils.file2Document(dataDir);//处理、转换。将文件转换成文档对象 indexWriter.addDocument(doc); Document doc2 = LuceneUtils.file2Document(dataDir2);//处理、转换。将文件转换成文档对象 indexWriter.addDocument(doc2); indexWriter.close();//用完一定要关闭! /* * 新添加一个Document并不会马上将它的索引写入最终的索引大文件,它的索引会暂时存于缓存。 * 当关闭时,会将缓存中的索引归并到索引大文件。如果此处没有关闭操作,那么刚刚添加的Document的索引不会保存到最终的索引大文件。 */ directory.close(); } /** * * testTermQuery 关键词查询 * @throws IOException * * @Description * @see */ @Test public void testTermQuery() throws IOException { String queryStr = "bye.txt"; Term term = new Term("fileName", queryStr); Query query = new TermQuery(term) ; this.queryAndPrintResult(query); } /** * * testTermRangeQuery 范围查询 * * @Description * @throws IOException void * @see */ @Test public void testTermRangeQuery() throws IOException { Query query = new TermRangeQuery("fileSize",new BytesRef(10),new BytesRef(2000), true, true); this.queryAndPrintResult(query); } /** * * queryAndPrintResult 测试查询对象用到的方法 * * @Description * @throws IOException void * @see */ private void queryAndPrintResult(Query query) throws IOException { Directory directory = this.getFsIndexDirectory();//获取索引文件的存储路径 IndexReader indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader);//从指定的路径的索引库检索指定的文本 TopDocs topDocs = indexSearcher.search(query, 100000); ScoreDoc[] scoreDocs = topDocs.scoreDocs; System.out.println("共有【"+ topDocs.totalHits+"】条查询结果。\n----------------"); //打印文档对象信息 for(int i=0;i<scoreDocs.length;i++) { Document document = indexSearcher.doc(scoreDocs[i].doc);//按照文档编号取出相应的文档对象 LuceneUtils.printDocumentInfo(document); } indexReader.close();//用完一定要关闭! directory.close(); } /** * * testSearch 检索 * * @Description * @throws IOException * @throws ParseException void * @see */ @Test public void testSearch() throws IOException, ParseException { String queryStr = "ok";//ok,Ok,OK,oK都能检索到文档中的OK关键字 Directory directory = this.getFsIndexDirectory();//获取索引文件的存储路径 IndexReader indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader);//从指定的路径的索引库检索指定的文本 String[] fields = {"fileName","content"}; QueryParser parser = new MultiFieldQueryParser(fields,analyzer);//在多个文本域中检索的解析器 // QueryParser parser = new QueryParser("content", analyzer);//在content域中检索的解析器 Query query = parser.parse(queryStr);//通过解析器将待检索的字符串转化成Query对象 // System.out.println(",,,,,,,,,,,"+query.); //Filter filter = null; //indexSearcher.search(query, filter, 2000);//5.3.1中已经废止该方法 TopDocs topDocs = indexSearcher.search(query, 100000); ScoreDoc[] scoreDocs = topDocs.scoreDocs; System.out.println("共有【"+ topDocs.totalHits+"】条查询结果。\n----------------"); //打印文档对象信息 for(int i=0;i<scoreDocs.length;i++) { Document document = indexSearcher.doc(scoreDocs[i].doc);//按照文档编号取出相应的文档对象 // document.getField("content"). LuceneUtils.printDocumentInfo(document); } indexReader.close();//用完一定要关闭! directory.close(); } /** * * testHighlighter 将搜索结果中的关键字高亮显示,并生成摘要文本 * @throws Exception * * @Description * @see */ @Test public void testHighlighter() throws Exception { String queryStr = "bye.txt"; Directory directory = this.getFsIndexDirectory();//获取索引文件的存储路径 IndexReader indexReader = DirectoryReader.open(directory); IndexSearcher indexSearcher = new IndexSearcher(indexReader);//从指定的路径的索引库检索指定的文本 String[] fields = {"fileName","content"}; QueryParser parser = new MultiFieldQueryParser(fields,analyzer);//在多个文本域中检索的解析器 Query query = parser.parse(queryStr);//通过解析器将待检索的字符串转化成Query对象 //1.获得查询结果-文档集合 ScoreDoc[] scoreDocs = indexSearcher.search(query, 100000).scoreDocs; //2.高亮处理(构造高亮器+使用高亮器-高亮关键词),并打印文档对象信息 //2.1 构造高亮器 //-------------------- Formatter formatter = new SimpleHTMLFormatter("<font color='red'>","</font>"); Encoder encoder = new SimpleHTMLEncoder(); Scorer fragmentScorer = new QueryScorer(query); Highlighter highlighter = new Highlighter(formatter, encoder, fragmentScorer); //设置高亮器 final int FRAGMENT_SIZE = 50; Fragmenter fragmenter = new SimpleFragmenter(FRAGMENT_SIZE);//每一个fragment的字符长度 highlighter.setTextFragmenter(fragmenter); //-------------------- for(int i=0;i<scoreDocs.length;i++) { Document document = indexSearcher.doc(scoreDocs[i].doc);//按照文档编号取出相应的文档对象 //2.2生成摘要文本,并将摘要中的关键词高亮显示 //-------------------- //抽取与关键词最相近的文本片段作为摘要文本 String text = document.get("content"); String ht = highlighter.getBestFragment(analyzer, "content", text); if(ht == null) {//若fileName域中包含关键词,而content域中没有关键词,ht则为空 //显示文档从头开始的部分文本 ht = text.substring(0, Math.min(text.length(), FRAGMENT_SIZE)); } System.out.println("ht.length()="+ht.length()); //将标记过关键词的信息重新设置到文档对象中 //document.getField("content").setValue(ht);//没有setValue方法 document.removeField("content"); document.add(new Field("content", ht,TextField.TYPE_STORED)); //-------------------- LuceneUtils.printDocumentInfo(document); } indexReader.close();//用完一定要关闭! directory.close(); } /** * * test * @throws IOException * * @Description * 1.当应用启动时,将磁盘中的索引文件读入内存。 * 2.应用运行过程中,只对内存中的索引文件进行操作。保证运行速度 * 3.在应用关闭前,将内存中的索引文件同步到磁盘。保证数据不丢失 * void * @see */ @Test public void test() throws Exception { //1.当应用启动时,将磁盘中的索引文件读入内存。 //获取磁盘上的索引库路径 Directory fsDir = this.getFsIndexDirectory(); //2.应用运行过程中,只对内存中的索引文件进行操作 //创建基于内存的IndexWriter Directory ramDir = new RAMDirectory((FSDirectory)fsDir, new IOContext() );//创建对象的同时,将磁盘上的索引文件加载到内存 IndexWriterConfig ramConfig = new IndexWriterConfig(analyzer); ramConfig.setOpenMode(OpenMode.CREATE); IndexWriter ramIndexWriter = new IndexWriter(ramDir,ramConfig); //应用程序运行过程中,添加Document对象 String tmpDir = "F:\\workspace\\luceneDemo\\dataDir\\CHANGES.txt";//1.txt CHANGES.txt Document doc = LuceneUtils.file2Document(tmpDir);//处理、转换。将文件转换成文档对象 ramIndexWriter.addDocument(doc); ramIndexWriter.close();//操作完毕,一定要关闭!!! //3.在应用关闭前,将内存中的索引文件同步到磁盘。 //创建基于磁盘的IndexWriter IndexWriterConfig fsConfig = new IndexWriterConfig(analyzer); fsConfig.setOpenMode(OpenMode.CREATE_OR_APPEND); IndexWriter fsIndexWriter = new IndexWriter(fsDir,fsConfig); fsIndexWriter.addIndexes(new Directory[] {ramDir}); fsIndexWriter.close();//操作完毕,一定要关闭!!! } /** * * testForceMerge 合并索引文件 * * @Description 优化操作 * @throws Exception void * @see */ @Test public void testForceMerge() throws Exception { Directory fsDir = this.getFsIndexDirectory(); IndexWriterConfig fsConfig = new IndexWriterConfig(analyzer); fsConfig.setOpenMode(OpenMode.CREATE_OR_APPEND); IndexWriter fsIndexWriter = new IndexWriter(fsDir,fsConfig); fsIndexWriter.commit(); fsIndexWriter.forceMerge(2);//forceMerge()内部有flush操作 fsIndexWriter.close();//操作完毕,一定要关闭!!! } /** * * testAnalyzer 分词器的使用 * * @Description 英文有英文分词器,中文有中文分词器。根据语言不同,选择相应的分词器(第三方jar) * @throws IOException void * @see */ @Test public void testAnalyzer() throws IOException { String enText = "This house builds well.She really wants to live in."; String zhText = "这个房子真好,她很想住进来。再见"; Analyzer en1 = new StandardAnalyzer(); // Analyzer zh1 = new SimpleAnalyzer(); this.analyze(en1, enText); System.out.println("--------------------"); this.analyze(en1, zhText); } /** * * analyze 分词 * * @Description * @param analyzer 分词器 * @param text 文本 * @throws IOException void * @see */ private void analyze(Analyzer analyzer, String text) throws IOException { TokenStream tokenStream = analyzer.tokenStream("content", text); //addAttribute():检查AttributeSource是否存在指定类的实例,如果存在,则返回该实例;不存在,则在AttributeSource中添加实例,并返回实例。 OffsetAttribute offsetAtt = tokenStream.addAttribute(OffsetAttribute.class);//OffsetAttribute:token的开始、结束偏移量属性。 //从tokenStream中获取CharTermAttribute CharTermAttribute termAtt = tokenStream.addAttribute(CharTermAttribute.class);//CharTermAttribute:token的词语(term)属性。 try { tokenStream.reset(); //清除状态,已到TokenStream的开始位置。在调用incrementToken()之前一定要调用reset()。 Resets this stream to the beginning. (Required) while(tokenStream.incrementToken()) {//移动到下一个token。已到TokenStream末尾,返回false System.out.println("----------CharTermAttribute----------"); System.out.println("词语:"+termAtt.toString()); System.out.println("----------OffsetAttribute----------"); System.out.println("token: " + tokenStream.reflectAsString(false)); System.out.println("\ttoken开始偏移量: " + offsetAtt.startOffset()); System.out.println("\ttoken结束偏移量: " + offsetAtt.endOffset()); } } catch (Exception e) { e.printStackTrace(); } finally { tokenStream.end();//到达TokenStream末尾后调用end(). Perform end-of-stream operations, e.g. set the final offset. tokenStream.close();//释放与流有关的资源 } } /** * * getFsIndexDirectory 获取索引库的Directory * * @Description * @return Directory * @see */ private Directory getFsIndexDirectory() { try { return FSDirectory.open(FileSystems.getDefault().getPath(indexDir));//基于磁盘的索引库,也可以基于内存:Directory directory = new RAMDirectory(); } catch (IOException e) { throw new RuntimeException(e); } } }
使用到的工具类:
package demo.mytest.lucene.utils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; /** * * LuceneUtils 工具类 * */ public class LuceneUtils { /** * * file2Document 将文件转换成文档对象 * * @Description * @param path * @return * @throws Exception Document * @see */ public static Document file2Document(String path) throws Exception { File file = new File(path); Document doc = new Document(); doc.add(new Field("fileName", file.getName(), TextField.TYPE_STORED)); doc.add(new Field("content", getFileContent(file),TextField.TYPE_STORED)); doc.add(new Field("fileSize", String.valueOf(file.getTotalSpace()), TextField.TYPE_STORED)); doc.add(new Field("path", file.getAbsolutePath(),TextField.TYPE_STORED)); //doc.add(new Field("fileName",String.valueOf(file.getName()),Store.YES, Index.ANALYZED)); System.out.println(file.getAbsolutePath()+"\t"+file.isDirectory()+"\n"+getFileContent(file)); doc.add(new Field("isDirectory",String.valueOf(file.isDirectory()),TextField.TYPE_STORED)); return doc; } /** * * printDocumentInfo 打印文档对象信息 * * @Description 打印文档对象信息 * @param document 文档对象 * void * @see */ public static void printDocumentInfo(Document document) { // IndexableField field = document.getField("fileName"); // System.out.println(field.name() + ":" +field.stringValue());//结果---fileName:CHANGES.txt。此处的document.getField("fileName").stringValue()相当于document.get("fileName") //打印文档对象信息 System.out.println("文档("+document.get("fileName")+")的信息-" +"内容:"+document.get("content")+"\t存储位置:"+document.get("path") +"\t文件大小:" + document.get("fileSize") +"\t是否为文件夹:"+ document.get("isDirectory")); } /** * * getFileContent 取得文件内容 * * @Description * @param file * @return * @throws Exception String * @see */ private static String getFileContent(File file) throws Exception { StringBuffer sbf = new StringBuffer(); BufferedReader br = new BufferedReader(new FileReader(file)); String line = null; while ((line = br.readLine()) != null) { sbf.append(line).append("\n"); } br.close(); return sbf.toString(); } }
相关推荐
计算机二级公共基础知识模 拟试题及答案详解.pdf
内容概要:本文档详细介绍了语音发射机的设计与实现,涵盖了从硬件电路到具体元件的选择和连接方式。文档提供了详细的电路图,包括电源管理、信号处理、音频输入输出接口以及射频模块等关键部分。此外,还展示了各个引脚的功能定义及其与其他组件的连接关系,确保了系统的稳定性和高效性能。通过这份文档,读者可以全面了解语音发射机的工作原理和技术细节。 适合人群:对电子工程感兴趣的初学者、从事嵌入式系统开发的技术人员以及需要深入了解语音发射机制的专业人士。 使用场景及目标:适用于希望构建自己的语音发射设备的研究人员或爱好者,帮助他们掌握相关技术和实际操作技能。同时,也为教学机构提供了一个很好的案例研究材料。 其他说明:文档不仅限于理论讲解,还包括具体的实施步骤,使读者能够动手实践并验证所学知识。
内容概要:本文详细介绍了用易语言编写的单线程全功能注册机源码,涵盖了接码平台对接、滑块验证处理、IP代理管理以及料子导入等多个核心功能。文章首先展示了主框架的初始化配置和事件驱动逻辑,随后深入探讨了接码平台(如打码兔)的API调用及其返回数据的处理方法。对于滑块验证部分,作者分享了如何利用易语言的绘图功能模拟真实用户的操作轨迹,并提高了验证通过率。IP代理模块则实现了智能切换策略,确保代理的有效性和稳定性。此外,料子导入功能支持多种格式的数据解析和去重校验,防止脏数据污染。最后,文章提到了状态机设计用于控制注册流程的状态持久化。 适合人群:有一定编程基础,尤其是熟悉易语言的开发者和技术爱好者。 使用场景及目标:适用于希望深入了解易语言注册机开发的技术细节,掌握接码、滑块验证、IP代理等关键技术的应用场景。目标是帮助读者理解并优化现有注册机的功能,提高其稳定性和效率。 其他说明:文中提到的部分技术和实现方式可能存在一定的风险,请谨慎使用。同时,建议读者在合法合规的前提下进行相关开发和测试。
计算机绘图实用教程 第三章.pdf
计算机辅助设计—AutoCAD 2018中文版基础教程 各章CAD图纸及相关说明汇总.pdf
C++相关书籍,计算机相关书籍,linux相关及http等计算机学习、面试书籍。
计算机二级mysql数据库程序设计练习题(一).pdf
计算机发展史.pdf
计算机二级课件.pdf
计算机概论第三讲:计算机组成.pdf
内容概要:本文档由中国移动通信集团终端有限公司、北京邮电大学、中国信息通信研究院和中国通信学会共同发布,旨在探讨端侧算力网络(TCAN)的概念、架构、关键技术及其应用场景。文中详细分析了终端的发展现状、基本特征和发展趋势,阐述了端侧算力网络的定义、体系架构、功能架构及其主要特征。端侧算力网络通过整合海量泛在异构终端的算力资源,实现分布式多级端侧算力资源的高效利用,提升网络整体资源利用率和服务质量。关键技术涵盖层次化端算力感知图模型、资源虚拟化、数据压缩、多粒度多层次算力调度、现场级AI推理和算力定价机制。此外,还探讨了端侧算力网络在智能家居、智能医疗、车联网、智慧教育和智慧农业等领域的潜在应用场景。 适合人群:从事通信网络、物联网、边缘计算等领域研究和开发的专业人士,以及对6G网络和端侧算力网络感兴趣的学者和从业者。 使用场景及目标:适用于希望深入了解端侧算力网络技术原理、架构设计和应用场景的读者。目标是帮助读者掌握端侧算力网络的核心技术,理解其在不同行业的应用潜力,推动端侧算力网络技术的商业化和产业化。 其他说明:本文档不仅提供了端侧算力网络的技术细节,还对其隐私与安全进行了深入探讨
学习java的心得体会.docx
计算机二级考试(南开100题齐全).pdf
内容概要:本文详细介绍了计算机二级C语言考试的内容和备考方法。首先概述了计算机二级考试的意义及其在计算机技能认证中的重要性,重点讲解了C语言的基础语法,包括程序结构、数据类型、运算符和表达式等。接着深入探讨了进阶知识,如函数、数组、指针、结构体和共用体的应用。最后分享了针对选择题、填空题和编程题的具体解题技巧,强调了复习方法和实战演练的重要性。 适合人群:准备参加计算机二级C语言考试的学生和技术爱好者。 使用场景及目标:①帮助考生系统地掌握C语言的核心知识点;②提供有效的解题策略,提高应试能力;③指导考生制定合理的复习计划,增强实战经验。 其他说明:本文不仅涵盖了理论知识,还提供了大量实例代码和详细的解释,有助于读者更好地理解和应用所学内容。此外,文中提到的解题技巧和复习建议对实际编程也有很大帮助。
论文格式及要求.doc
内容概要:本文详细介绍了如何使用三菱FX3U PLC及其485BD通信板与四台台达VFD-M系列变频器进行通信的设置与应用。主要内容涵盖硬件连接注意事项、通信参数配置、RS指令的应用、CRC校验算法的实现以及频率给定和状态读取的具体方法。文中提供了多个实用的编程示例,展示了如何通过梯形图和结构化文本编写通信程序,并讨论了常见的调试技巧和优化建议。此外,还提到了系统的扩展性和稳定性措施,如增加温度传感器通信功能和应对电磁干扰的方法。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些熟悉三菱PLC和台达变频器的使用者。 使用场景及目标:适用于需要实现多台变频器联动控制的工业应用场景,旨在提高生产效率和系统可靠性。通过学习本文,读者可以掌握如何构建稳定的RS485通信网络,确保变频器之间的高效协同工作。 其他说明:本文不仅提供了详细的理论指导,还包括了许多来自实际项目的经验教训,帮助读者避免常见错误并提升编程技能。
计算机服务规范.pdf
Discuz_X3.2_TC_UTF8.zip LNMP搭建安装包
2023年房地产行业研究报告:缓解竣工下行加速的两大改革
win32汇编环境,网络编程入门之十五