实战 | Elasticsearch打造知识库检索系统

来源:互联网 发布:怎么抢淘宝秒杀的东西 编辑:程序博客网 时间:2024/05/29 08:30

题记

源自“死磕Elasticsearch”技术群里的讨论问题:
——我想用es做个类似于知识库的东西,所以需要索引一些pdf、word之类的文件,这个你之前有试过吗?能给个方向吗?

我的思考如下:

1、pdf、Office类的文档如何被ES索引?

更确切的说,pdf、Office类文档(word,ppt,excel等)如何导入ES中。
如图所示:
这里写图片描述
问题转嫁为:如何将Office类文档、PDF文档导入ES建立索引,并提供全文检索服务?

2、Elasticsearch支持的最大待检索字段的长度是多大?

ES5.X版本以后,keyword支持的最大长度为32766个UTF-8字符,text对字符长度没有限制。
设置ignore_above后,超过给定长度后的数据将不被索引,无法通过term精确匹配检索返回结果。
参考我的整理:http://blog.csdn.net/laoyang360/article/details/78207980
参考6.0官网解读:https://www.elastic.co/guide/en/elasticsearch/reference/6.0/ignore-above.html
参考luncene7.1API: http://t.cn/RYWvuGl

3、Office&pdf文档存入Elastisearch注意问题清单

少废话,直接上图。
这里写图片描述

4、解析实战代码

/***@brief:不同类型的文档解析**@param:文件路径**@return:解析结果*/public static ImExtInfo readXFile(String inputPath){String fileExt = FileUtil.getFileExtension(file);switch(fileExt){case "pdf":imExtInfo = readPdfFile(inputPath);break;case "docx":imExtInfo = readDocxFile(inputPath);break;case "doc":imExtInfo = readDocFile(inputPath);break;case "json":case "txt":case "md":imExtInfo = readTxtFile(inputPath);break;default:logger.info("unknow type " + fileExt);imExtInfo = null;}/***@brief:docx文档解析**@param:文件路径**@return:解析结果*/public static ImExtInfo readDocxFile(String inputPath) {ImExtInfo  ImExtInfo = new ImageExtInfo();try {File file = new File(inputPath.trim());//1.获取文件名称String fileTitle = file.getName();//2.获取绝对路径String filePath = file.getAbsolutePath();//3.获取文件内容FileInputStream fis = new FileInputStream(file.getAbsolutePath());XWPFDocument document = new XWPFDocument(fis);List<XWPFParagraph> paragraphs = document.getParagraphs();StringBuilder contentBuilder = new StringBuilder();//System.out.println("Total no of paragraph "+paragraphs.size());for (XWPFParagraph para : paragraphs) {//System.out.println(para.getText());contentBuilder.append(para.getText().trim());}String content = contentBuilder.toString();imExtInfo.setTitle(fileTitle);imExtInfo.setPath(filePath);imExtInfo.setContent(content.trim());// 获取当前时间...String curTimeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());imExtInfo.setCreate_time(curTimeStamp);document.close();fis.close();} catch (Exception e) {e.printStackTrace();}return imExtInfo;}

以上仅列举核心示例代码。

5、小结

从功能和性能角度考量,建立知识库的建议如下:
1)知识库的核心是数据导入ES,导入ES的核心是各种类型文档的解析;
2)提前设定Mapping,定义好字段分词、不分词的策略;
3)对于大于1MB一个字段的存储,建议使用fvh高亮方式,在Mapping中一并设置。

参考:

[1] Java读取Office文档参考:http://poi.apache.org/document/
[2] Html2Md参考:https://github.com/pnikosis/jHTML2Md
[3] Pdf2Html参考:https://github.com/coolwanglu/pdf2htmlEX
[4]OpenOffice参考:https://www.openoffice.org/download/index.html

——————————————————————————————————
更多ES相关实战干货经验分享,请扫描下方【铭毅天下】微信公众号二维码关注。
(每周至少更新一篇!)

这里写图片描述
和你一起,死磕Elasticsearch
——————————————————————————————————

2017.12.03 19:03 于家中床前

作者:铭毅天下
转载请标明出处,原文地址:
http://blog.csdn.net/laoyang360/article/details/78703177
如果感觉本文对您有帮助,请点击‘顶’支持一下,您的支持是我坚持写作最大的动力,谢谢!