博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
初始 lucene
阅读量:6866 次
发布时间:2019-06-26

本文共 2098 字,大约阅读时间需要 6 分钟。

hot3.png

一, 全文搜索引擎的三个组成部分:

  1. 索引部分

  2. 分词部分

  3. 搜索部分

/**	 * 建立索引	 */	public void index() {				IndexWriter iw = null;		try {			//1. 创建 Directory对象//			Directory dir = new RAMDirectory(); // 建立在内存中			Directory dir = FSDirectory.open(Paths.get("F:/fullindex/index01"));			//2. 创建 IndexWriter			IndexWriterConfig iwc = new IndexWriterConfig(new StandardAnalyzer());			iw = new IndexWriter(dir, iwc);			//3. 创建 Document 对象			Document doc = null;			File file = new File("F:/fullindex/example");			for(File f : file.listFiles()) {				doc = new Document();				//4. 为 Document 对象添加 Field				doc.add(new TextField("content", new FileReader(f)));				doc.add(new Field("fileName", f.getName(), TextField.TYPE_STORED));				doc.add(new Field("path", f.getAbsolutePath(), TextField.TYPE_STORED));				//5. 通过 IndexWriter 添加文档到索引中				iw.addDocument(doc);			}			//6. 关闭流			iw.close();		} catch (IOException e) {			e.printStackTrace();		} finally {			if(null != iw) {				try {					iw.close();				} catch (IOException e) {					e.printStackTrace();				}			}		}	}		/**	 * 搜索	 */public void searcher() {	DirectoryReader ireader = null;	try {		//1. 创建 Directory		Directory dir = FSDirectory.open(Paths.get("F:/fullindex/index01"));		//2. 创建 DirectoryReader		ireader = DirectoryReader.open(dir);		//3. 根据 DirectoryReader 创建 IndexSearch		IndexSearcher isearcher = new IndexSearcher(ireader);		//4. 创建搜索的 query		QueryParser parser = new QueryParser("content", new StandardAnalyzer());		Query query = parser.parse("java");		//5. 根据 search 搜索并返回 TopDocs		TopDocs tds = isearcher.search(query, 10);		//6. 根据 TopDocs 获取 ScordDoc 对象		ScoreDoc[] scoreDocs = tds.scoreDocs;	        for(ScoreDoc sd : scoreDocs) {		//7. 根据 search 和 ScordDoc 对象获取具体的 Document 对象		Document doc = isearcher.doc(sd.doc);		//8. 根据 Document 对象获取需要的值		System.out.println("filename:" + doc.get("fileName") + "---> path:" + doc.get("path"));	}	//9. 关闭流	ireader.close();} catch (Exception e) {	e.printStackTrace();} finally {	if(null != ireader) {		try {			ireader.close();		} catch (IOException e) {			e.printStackTrace();		}	}	}}

转载于:https://my.oschina.net/u/2002410/blog/528770

你可能感兴趣的文章
嵌入式系统学习步骤
查看>>
PPT | Docker定义存储-让应用无痛运行
查看>>
django 自定义日志配置
查看>>
是程序员,就用python导出pdf
查看>>
Absolute Uninstaller是类似于标准的Windows添加/删除卸载工具
查看>>
C++ Primer Plus(十)——对象和类
查看>>
ZooKeeper伪分布式集群安装及使用
查看>>
js 页面跳转保存状态
查看>>
轻松应对IDC机房带宽突然暴涨问题
查看>>
Mybatis Interceptor 讲解
查看>>
java mybatis向mysql数据库插入中文出现乱码
查看>>
linux用户和文件目录管理
查看>>
表空间数据结构研究_01
查看>>
mysql 编译安装
查看>>
Apache Tomcat7+MySQL5.6配置
查看>>
char varchar nvarchar区别
查看>>
如何解决JSP页面的乱码问题
查看>>
JavaScript调用Applet的函数
查看>>
Character
查看>>
关于visualizer的setEnabled()方法何时进行设置成false?
查看>>