ElasticSearch 实现 全文检索 支持(PDF、TXT、Word、HTML等文件)通过 ingest

编程入门 行业动态 更新时间:2024-10-25 10:24:54

ElasticSearch 实现 全文检索 支持(PDF、TXT、Word、HTML等<a href=https://www.elefans.com/category/jswz/34/1771438.html style=文件)通过 ingest"/>

ElasticSearch 实现 全文检索 支持(PDF、TXT、Word、HTML等文件)通过 ingest

一、Attachment 介绍

Attachment 插件是 Elasticsearch 中的一种插件,允许将各种二进制文件(如PDF、Word文档等)以及它们的内容索引到 Elasticsearch 中。插件使用 Apache Tika 库来解析和提取二进制文件的内容。通过使用 Attachment 插件,可以轻松地在 Elasticsearch 中建立全文搜索功能,而无需事先转换二进制文件为文本。

优点:

  1. 可以将各种类型的二进制文件以原始形式存储在 Elasticsearch 中。这使得保存和访问二进制文件变得更加简单和高效。

  2. 插件使用 Apache Tika 库来解析和提取二进制文件的内容,因此可以提取并存储内容、元数据以及格式化的文本数据。这使得 Elasticsearch 可以轻松地对文档执行全文搜索以及文档内容的其他分析操作。

  3. 在 Elasticsearch 中使用 Attachment 插件,可以轻松地实现以下一些功能:搜索文档、生成全文搜索报告、自动标记文件、提取数据并进行分析,在文档中查找特定项等。

缺点:

  1. Attachment 插件对性能有一定的影响,因为执行全文搜索需要解析和提取二进制文件的内容。如果处理大量的二进制文件,可能会影响搜索性能。

  2. Attachment 插件有一些限制,例如插件不支持对二进制文件进行过滤或排除,因此如果文件内容包含敏感信息,则不应使用 Attachment 插件进行索引。

二、初始化 ingest-attachment

1、windows安装

 1、先在ES的bin目录下执行命令 安装 ngest-attachment插件

elasticsearch-plugin install ingest-attachment

作者已经安装过了 所以不能重复安装,插件下载过程中会出现

2、Liunx安装 

通过官网下载,找到对应的版本号:attachment下载网站

下载好后上传到服务器,进入elasticsearch安装目下的bin目录下。
执行sudo ./elasticsearch-plugin install file:///home/ingest-attachment-7.9.0.zip 即可
重启ES  打印 [apYgDEl] loaded plugin [ingest-attachment] 表示安装成功

3、小结

安装完成后需要重新启动ES

接下来我们需要创建一个关于ingest-attachment的文本抽取管道

PUT /_ingest/pipeline/attachment
{"description": "Extract attachment information","processors": [{"attachment": {"field": "content","ignore_missing": true}},{"remove": {"field": "content"}}]
}

后续我们的文件需要base64后储存到 attachment.content 索引字段中

三、如何应用?

1、通过命令语句简易检索

# 创建一个ES 索引 并且添加一些测试数据

POST /pdf_data/_doc?pretty
{"id": "3","name": "面试题文件1.pdf","age": 18,"type": "file","money": 1111,"createBy": "阿杰","createTime": "2022-11-03T10:41:51.851Z","attachment": {"content": "面试官:如何保证消息不被重复消费啊?如何保证消费的时候是幂等的啊?Kafka、ActiveMQ、RabbitMQ、RocketMQ 都有什么区别,以及适合哪些场景?","date": "2022-11-02T10:41:51.851Z","language": "en"}
}

# 通过插入的文档内容为条件进行检索

# 简单 单条件查询 文档内容检索
GET /pdf_data/_search
{"query": {"match": {"attachment.content": "面试官:如何保证消息不被重复消费啊?如何保证消费的时候是幂等的啊?"}}
}

2、整合java代码实现ES通过ingest-attachment进行全文检索

 1、首先将文件转为BASE64进行ES数据插入

/*** 将文件 文档信息储存到数据中* @param file* @return*/@PostMapping("/insertFile")@ApiOperation(value="创建索引ES-传入ES索引-传入文件", notes="创建索引ES-传入ES索引-传入文件")public IndexResponse insertFile(@RequestAttribute("file") MultipartFile file,@RequestParam("indexName")String indexName){FileObj fileObj = new FileObj();fileObj.setId(String.valueOf(System.currentTimeMillis()));fileObj.setName(file.getOriginalFilename());fileObj.setType(file.getName().substring(file.getName().lastIndexOf(".") + 1));fileObj.setCreateBy(RandomNameGenerator.generateRandomName());fileObj.setCreateTime(String.valueOf(System.currentTimeMillis()));fileObj.setAge(RandomNameGenerator.getAge());fileObj.setMoney(RandomNameGenerator.getMoney());// 文件转base64byte[] bytes = new byte[0];try {bytes = file.getBytes();//将文件内容转化为base64编码String base64 = Base64.getEncoder().encodeToString(bytes);fileObj.setContent(base64);IndexResponse indexResponse=  ElasticsearchUtil.upload(fileObj,indexName);if (0==indexResponse.status().getStatus()){// 索引创建并插入数据成功System.out.println("索引创建并插入数据成功");}return indexResponse;} catch (Exception e) {e.printStackTrace();}return null;}

 2、创建索引、插入数据,并且将文档数据抽取到管道中

    @Autowiredprivate RestHighLevelClient restHighLevelClient;private  static  RestHighLevelClient levelClient;@PostConstructpublic void initClient() {levelClient = this.restHighLevelClient;}/*** 创建索引并插入数据* @param file* @param indexName* @return* @throws IOException*/public static IndexResponse upload(FileObj file,String indexName) throws IOException {// TODO 创建前需要判断当前文档是否已经存在if (!isIndexExist(indexName)) {CreateIndexRequest request = new CreateIndexRequest(indexName);// 如果需要ik分词器就添加配置,不需要就注释掉 // 添加 IK 分词器设置  ik_max_word
//            request.settings(Settings.builder()
//                    .put("index.analysis.analyzer.default.type", "ik_max_word")
//                    .put("index.analysis.analyzer.default.use_smart", "true")
//            );// 添加 IK 分词器设置 ik_smart request.settings(Settings.builder().put("index.analysis.analyzer.default.type", "ik_smart"));CreateIndexResponse response = levelClient.indices().create(request, RequestOptions.DEFAULT);log.info("执行建立成功?" + response.isAcknowledged());}IndexRequest indexRequest = new IndexRequest(indexName);//上传同时,使用attachment pipline进行提取文件indexRequest.source(JSON.toJSONString(file), XContentType.JSON);indexRequest.setPipeline("attachment");IndexResponse indexResponse= levelClient.index(indexRequest,RequestOptions.DEFAULT);System.out.println(indexResponse);return indexResponse;}

  3、其他代码补充

   ES Config 配置类 

/*** ES配置类* author: 阿杰*/
@Configuration
public class ElasticSearchClientConfig {/*** ES 地址:127.0.0.1:9200*/@Value("${es.ip}")private String hostName;@Beanpublic RestHighLevelClient restHighLevelClient() {String[] points = hostName.split(",");HttpHost[] httpHosts = new HttpHost[points.length];for (int i = 0; i < points.length; i++) {String point = points[i];httpHosts[i] = new HttpHost(point.split(":")[0], Integer.parseInt(point.split(":")[1]), "http");}RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(httpHosts));return client;}@Beanpublic ElasticsearchUtil elasticSearchUtil() {return new ElasticsearchUtil();}}

数据插入使用的实体类

/*** author: 阿杰*/
@Data
public class FileObj {/*** 用于存储文件id*/String id;/*** 文件名*/String name;/*** 文件的type,pdf,word,or txt*/String type;/*** 数据插入时间*/String createTime;/*** 当前数据所属人员*/String createBy;/*** 当前数据所属人员的年龄*/int age;/*** 当前数据所属人员的资产*/int money;/*** 文件转化成base64编码后所有的内容。*/String content;
}

 完整代码可通过: 完整代码包下载

制作不易,给个小赞!

                  

更多推荐

ElasticSearch 实现 全文检索 支持(PDF、TXT、Word、HTML等文件)通过 ingest

本文发布于:2023-11-16 11:38:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   全文   PDF   ElasticSearch   TXT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!