我正在尝试使用 Java 代码在弹性搜索 6.3.2 中索引 PDF 文件。到目前为止,我已经编写了以下代码来将 pdf 保存在 ES 中。代码运行良好,我能够在 ES 中保存我的 PDF 的 Base64 编码字符串。我想了解我所遵循的方法是否正确?有没有更好的方法来做到这一点?以下是我的代码:
InputStream inputStream = new FileInputStream(new File("mypdf.pdf"));
try {
byte[] fileByteStream = IOUtils.toByteArray(inputStream );
String base64String = new String(Base64.getEncoder().encodeToString(fileByteStream).getBytes(),"UTF-8");
String strEncoded = Base64.getEncoder().encodeToString( base64String.getBytes( "utf-8" ));
this.stream.close();
JSONObject correspondenceNode = new JSONObject();
correspondenceNode.put("data",strEncoded );
String strSsonValues = correspondenceNode.toString();
HttpEntity entity = new NStringEntity(strSsonValues , ContentType.APPLICATION_JSON);
elasticrestClient.put("/2018/documents/"1, entity);
} catch (IOException e) {
e.printStackTrace();
}
基本上我在这里做的是,我将 PDF 文档转换为 Base64String 并将其保存到 ES 中,在阅读时,我将其转换回来。
下面是解码的代码:
String responseBody = elasticrestClient.get("/2018/documents/1");
//some code to fetch the hits
JSONObject h = hitsArray.getJSONObject(0);
source = h.getJSONObject("_source");
String object = (source.getString("data"));
byte[] decodedStr = Base64.getDecoder().decode( object );
FileOutputStream fos = new FileOutputStream("download.pdf");
fos.write(Base64.getDecoder().decode(new String( decodedStr, "utf-8" )));
fos.close();
在 elasticsearch 中存储 BASE64 内容可能是正确的,但这里可能会丢失一些部分:
相反,我会提取文本和元数据并索引该 + 二进制文件本身的 URL。喜欢:
{
"content": "Extracted text here",
"meta": {
// Meta data there
},
"url": "file://path/to/file"
}
您还可以查看FSCrawler(包括它的代码),它基本上是这样做的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句