热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Lucene检索WORD等文件

###Lucene是什么? ####lucene是apache开源的全文检索的框架,不像百度那样的搜索引擎拿来就能用! ###Lucene实现检索的过程&#x

###Lucene是什么?
####lucene是apache开源的全文检索的框架,不像百度那样的搜索引擎拿来就能用!
###Lucene实现检索的过程?
####Lucene实际上是先将文本写入,然后再搜索出来。
###写入:
####涉及的类: Document 、Field 、IndexWriter
####Document相当于数据库表的一行,Field相当于数据库表的一个字段,Document可以包含多个Field,用IndexWriter对象将Document对象写在磁盘上或内存里,这就实现了字符串的写入!
###搜索:
####对写入的文本进行搜索!

###如何检索WORD等microsoft文件?
####要实现Lucene检索WORD等文件,首先需要读取出WORD文件中的内容,再使用Lucene将内容写入。

###如何读取microsoft文件?
####可以使用apache的POI开源项目进行读取。

#####javaCode:

package org.fazlan.lucene.demo;import java.io.File;
import java.io.IOException;import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;public class Indexer {// location where the index will be stored.public static final String INDEX_DIR = "src/main/resources/index";private IndexWriter writer = null;public Indexer() {try {writer = new IndexWriter(FSDirectory.open(new File(INDEX_DIR)),new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36)));} catch (Exception e) {e.printStackTrace();}}/*** This method will add the items into index*/public void writeIndex(IndexItem indexItem) throws IOException {// deleting the item, if already existswriter.deleteDocuments(new Term(IndexItem.ID, indexItem.getId().toString()));Document doc = new Document();doc.add(new Field(IndexItem.ID, indexItem.getId().toString(), Field.Store.YES, Field.Index.NOT_ANALYZED));doc.add(new Field(IndexItem.TITLE, indexItem.getTitle(), Field.Store.YES, Field.Index.ANALYZED));doc.add(new Field(IndexItem.FILENAME, indexItem.getFilename(), Field.Store.YES, Field.Index.NOT_ANALYZED));doc.add(new Field(IndexItem.CONTENT, indexItem.getContent(), Field.Store.YES, Field.Index.ANALYZED));doc.add(new Field(IndexItem.DATE, indexItem.getDate(), Field.Store.YES, Field.Index.NOT_ANALYZED));doc.add(new Field(IndexItem.USER_NAME, indexItem.getUserName(), Field.Store.YES, Field.Index.NOT_ANALYZED));doc.add(new Field(IndexItem.URL, indexItem.getUrl(), Field.Store.YES, Field.Index.NOT_ANALYZED));// add the document to the indexwriter.addDocument(doc);}/*** Closing the writer*/public void close() throws IOException {writer.close();}
}

package org.fazlan.lucene.demo;/*** 索引对象,根据业务要求改动* * @author JiaJiCheng**/
public class IndexItem {private Long id;private String title;private String filename;private String content;private String date;private String userName;private String url;public static final String ID = "id";public static final String TITLE = "title";public static final String CONTENT = "content";public static final String DATE = "date";public static final String USER_NAME = "userName";public static final String FILENAME = "filename";public static final String URL = "url";public IndexItem(Long id, String title, String filename, String content, String date, String userName, String url) {this.id = id;this.title = title;this.content = content;this.date = date;this.userName = userName;this.filename = filename;this.url = url;}public String getFilename() {return filename;}public String getUrl() {return url;}public String getDate() {return date;}public String getUserName() {return userName;}public Long getId() {return id;}public String getTitle() {return title;}public String getContent() {return content;}@Overridepublic String toString() {return "IndexItem{" + "id=" + id + ", title='" + title + ", content='" + content + '\'' + "date=" + date+ "userName=" + userName + '}';}
}

package org.fazlan.lucene.demo;import org.apache.poi.extractor.ExtractorFactory;import java.io.File;
import java.io.IOException;/*** 文件转换器* * @author JiaJiCheng**/
public class MSDocumentParser {private static String getFilename(String filename) {return filename.substring(0, filename.lastIndexOf("."));}public static IndexItem parser(File file, String date, String userName, String url) throws IOException {String content = null;try {content = ExtractorFactory.createExtractor(file).getText();} catch (Exception e) {e.printStackTrace();}return new IndexItem((long) file.hashCode(), getFilename(file.getName()), file.getName(), content, date,userName, url);}
}

package org.fazlan.lucene.demo;import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;public class Searcher {private IndexSearcher searcher;private QueryParser titleQueryParser;private QueryParser contentQueryParser;private static final StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);// default find result size.private static final int DEFAULT_RESULT_SIZE = 100;public Searcher() throws IOException {// open the index directory to searchsearcher = new IndexSearcher(IndexReader.open(FSDirectory.open(new File(Indexer.INDEX_DIR))));// defining the query parser to search items by title field.titleQueryParser = new QueryParser(Version.LUCENE_36, IndexItem.TITLE, analyzer);// defining the query parser to search items by content field.contentQueryParser = new QueryParser(Version.LUCENE_36, IndexItem.CONTENT, analyzer);}/*** This method is used to find the indexed items by the title.* * @param queryString* - the query string to search for*/public List findByTitle(String queryString) throws ParseException, IOException {// create query from the incoming query string.Query query = titleQueryParser.parse(queryString);// execute the query and get the resultsScoreDoc[] queryResults = searcher.search(query, DEFAULT_RESULT_SIZE).scoreDocs;List results = new ArrayList();// process the resultsfor (ScoreDoc scoreDoc : queryResults) {Document doc = searcher.doc(scoreDoc.doc);results.add(new IndexItem(Long.parseLong(doc.get(IndexItem.ID)), doc.get(IndexItem.TITLE),doc.get(IndexItem.FILENAME), doc.get(IndexItem.CONTENT), doc.get(IndexItem.DATE),doc.get(IndexItem.USER_NAME), doc.get(IndexItem.URL)));}return results;}/*** This method is used to find the indexed items by the content.* * @param queryString* - the query string to search for*/public List findByContent(String queryString) throws ParseException, IOException {// create query from the incoming query string.Query query = contentQueryParser.parse(queryString);// execute the query and get the resultsScoreDoc[] queryResults = searcher.search(query, DEFAULT_RESULT_SIZE).scoreDocs;List results = new ArrayList();// process the resultsfor (ScoreDoc scoreDoc : queryResults) {Document doc = searcher.doc(scoreDoc.doc);results.add(new IndexItem(Long.parseLong(doc.get(IndexItem.ID)), doc.get(IndexItem.TITLE),doc.get(IndexItem.FILENAME), doc.get(IndexItem.CONTENT), doc.get(IndexItem.DATE),doc.get(IndexItem.USER_NAME), doc.get(IndexItem.URL)));}return results;}public void close() throws IOException {searcher.close();}
}

package org.fazlan.lucene.demo;import org.apache.lucene.queryParser.ParseException;import java.io.File;
import java.io.IOException;
import java.util.List;/*** 实例* * @author JiaJiCheng**/
public class FileIndexApplication {public static void main(String[] args) throws IOException, ParseException {File msWordFile = new File("src/main/resources/files/MSWord.doc");File msWord2003File = new File("src/main/resources/files/MSWord.docx");File msExcellFile = new File("src/main/resources/files/招商局系统.xls");// creating the indexer and indexing the itemsIndexer indexer = new Indexer();indexer.writeIndex(MSDocumentParser.parser(msWordFile, "1990-0-0", "zhangsan", "www.baidu.com"));indexer.writeIndex(MSDocumentParser.parser(msWord2003File, "1990-0-0", "zhangsan", "www.baidu.com"));indexer.writeIndex(MSDocumentParser.parser(msExcellFile, "1990-0-0", "zhangsan", "www.baidu.com"));// close the index to enable them indexindexer.close();// creating the Searcher to the same index location as the IndexerSearcher searcher = new Searcher();// List result = searcher.findByContent("Microfost",// DEFAULT_RESULT_SIZE);List result = searcher.findByTitle("招");print(result);searcher.close();}/*** print the results.*/private static void print(List result) {System.out.println("Result Size: " + result.size());for (IndexItem item : result) {System.out.println(item);}}
}

org.apache.lucenelucene-core3.6.0org.apache.poipoi3.8org.apache.poipoi-ooxml3.8org.apache.poipoi-scratchpad3.8junitjunit3.8.1test

##完整的项目代码见附件


推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • 先看官方文档TheJavaTutorialshavebeenwrittenforJDK8.Examplesandpracticesdescribedinthispagedontta ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Java中包装类的设计原因以及操作方法
    本文主要介绍了Java中设计包装类的原因以及操作方法。在Java中,除了对象类型,还有八大基本类型,为了将基本类型转换成对象,Java引入了包装类。文章通过介绍包装类的定义和实现,解答了为什么需要包装类的问题,并提供了简单易用的操作方法。通过本文的学习,读者可以更好地理解和应用Java中的包装类。 ... [详细]
author-avatar
飞松安步当车9_U
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有