Elasticsearch:如何对PDF文件进行搜索

Elasticsearch通常用于为字符串,数字,日期等类型的数据建立索引。但是,如果要直接为.pdf或.doc等文件建立索引并使其可搜索该怎么办?在HCM,ERP和电子商务等应用程序中有这种实时用例的需求。

在今天的这篇文章中我们来讲一下如何实现对.pdf或.doc文件的搜索。本解决方案使用于Elasticsearch 5.0以后的版本。

实现原理

我们采用如下的方法来实现把一个.pdf文件导入到Elasticsearch的数据node中:

如上图所示,我们首先把我们的.pdf文件进行Base64的处理,然后上传到Elasticsearch中的ingest node中进行处理。我们可以通过Ingest attachment plugin 来使得Elasticsearch提取通用格式的文件附件比如 PPT, XLS及PDF。最终,数据进行倒Elasticsearch的data node中以便让我们进行搜索。

在下面的章节中,我们来逐步介绍如何实现。

导入pdf文件到Elasticsearch中

准备pdf文件

我们可以使用我们的word或其它编辑软件来生产一个pdf的文件。暂且我们叫这个文件的名字为sample.pdf文件。而它的内容非简单:

在我们的sample.pdf文件中,我们只有一句话“I like this useful tool”。

安装ingest attachment plugin

ingest attachment plugin允许Elasticsearch通过使用Apache文本提取库Tika提取通用格式(例如PPT,XLS和PDF)的文件附件。 Apache Tika工具包可从一千多种不同的文件类型(例如PPT,XLS和PDF)中检测并提取元数据和文本。 所有这些文件类型都可以通过一个界面进行解析,从而使Tika对搜索引擎索引,内容分析,翻译等有用。

源字段必须是base64编码的二进制。 如果不想增加在base64之间来回转换的开销,则可以使用CBOR格式而不是JSON,并将字段指定为字节数组而不是字符串表示形式。 然后,处理器将跳过base64解码。

可以使用插件管理器安装此插件:

sudo bin/elasticsearch-plugin install ingest-attachment

该插件必须安装在集群中的每个节点上,并且每个节点必须在安装后重新启动

等我们安装好这个插件后,我们可以通过如下的命令来查看该插件是否已经被成功安装好了。

./bin/elasticsearch-plugin list

如果安装正确,我们则可以看到如下的输出:

创建attachment pipeline

我们可以在我们的Ingest node上创建一个叫做pdfattachment的pipleline:

PUT _ingest/pipeline/pdfattachment
{
  "description": "Extract attachment information encoded in Base64 with UTF-8 charset",
  "processors": [
    {
      "attachment": {
        "field": "file"
      }
    }
  ]
}

转换pdf文件并上传pdf文件的内容到Elasticsearch中

对于ingest attachment plugin来说,它的数据必须是Base64的。我们可以在网站Base64 encoder来进行转换。针对我们的情况,我们直接通过脚本的方法来进行操作:

indexPdf.sh

#!/bin/bash
encodedPdf=`cat sample.pdf | base64`
json="{\"file\":\"${encodedPdf}\"}"
echo "$json" > json.file
curl -XPOST 'http://localhost:9200/pdf-test1/_doc?pipeline=pdfattachment&pretty' -H 'Content-Type: application/json' -d @json.file

在上面的脚本中,我们针对sample.pdf进行base64的转换,并生成一个叫做json.file的文件。在最后,我们把这个json.file文件的内容通过curl指令上传到Elasticsearch中。我们可以在Elasticsearch中查看一个叫做pdf-test1的索引。

我们可以在terminal中直接运行上面的脚本:

./indexPdf.sh

至此我们已经把pdf文件导入到Elasticsearch中了。

查看索引并搜索

我们可以通过如下的命令来查询我们的pdf-test1索引:

GET pdf-test1/_search

显示结果为:

在上面我们可以看出来,我们的索引中有一个叫做content的字段,它包含了我们的pdf文件的内容。这个字段可以同我们进行搜索。在上面我们也看到了一个很大的一个字段file。它含有我们转换过的base64格式的内容。如果我们不想要这个字段,我们可以通过添加另外一个remove processor来除去这个字段:

PUT _ingest/pipeline/pdfattachment
{
  "description": "Extract attachment information encoded in Base64 with UTF-8 charset",
  "processors": [
    {
      "attachment": {
        "field": "file"
      }
    },
    {
      "remove": {
        "field": "file"
      }
    }
  ]
}

这样我们除去了那个叫做file的字段,那么修正后的索引内容为:

参考:

【1】https://qbox.io/blog/how-to-index-attachments-and-files-to-elasticsearch-5-0-using-ingest-api?utm_source=qbox.io&utm_medium=article&utm_campaign=powerful-pdf-search-elasticsearch-mapper-attachment

【2】https://www.elastic.co/guide/en/elasticsearch/plugins/current/ingest-attachment.html

发布了489 篇原创文章 · 获赞 107 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/UbuntuTouch/article/details/104171230