使用Elasticsearch进行word,excel,PDF的全文检索 windows实现 超完整(ingest-attachment实现)

首先要明确的一点就是Elasticsearch的版本要和ingest-attachment的版本一致,要不然没办法安装。然后还有一点JAVA版本要在11以上

先说说原理吧,其实就是将文件base64编码,然后再用插件读取文件内容并保存到es中。

1.如果你的版本是JAVA1.8的话,最好换成JDK11

安装完jdk之后用cmd查看一下java -version看看是否已经从1.8修改为了11

如果没有边的话则需要修改环境变量

可以在开始菜单输入env快速打开环境变量配置

 首先修改JAVA_HOME

然后还是和配置jdk一样修改path 

但是这里有一个坑点,那就是除了你自己配置的jdk path之外可能还有一个oracle的path,记得把他给删了,要不java -version后还是1.8

2.安装Elasticsearch 7.9.0

我的es是在这个链接下载的:

https://rjxcvbn.tianjiuda.com/20211206/elasticsearch_v7.9.0_xitongcheng.zip

下载完毕之后解压

进入bin目录 

双击elasticsearch.bat即可运行es

 运行完成后可以访问http://127.0.0.1:9200/ 查看是否正常运行

3.下载配置ingest-attachment-7.9.0

这里一定要下载和上面一样的版本,否则无法安装

下载地址:https://artifacts.elastic.co/downloads/elasticsearch-plugins/ingest-attachment/ingest-attachment-7.9.0.zip

 比如说ingest-attachment-5.4.2.zip 在D盘根目录,那我们就可以在elastics的根目录下运行下面的命令

bin\elasticsearch-plugin install file:///D:\ingest-attachment-5.4.2.zip 

这样他就会将ingest-attachment的插件安装到elasticsearch上了。这里就不放截图了,因为我已经安装好了。

安装好之后可以通过PowerShell查看是否安装完成  

首先切换目录到ES根目录:

输入 .\bin\elasticsearch-plugin list如果有ingest-attachment则代表安装成功

 

 然后我们可以重启es。重启方式就是关闭cmd然后重新打开步骤1的.bat

3.POSTMAN  ES基础使用教程

如果已经会使用es请跳过该步骤

先偷一张图

我就以mysql数据库举例吧,比如说mysql中的表在es里应该叫索引,我就直接叫表吧,毕竟不跳过这里的估计也没太看过es的教程。我这里就是简单的说一说,想要具体了解请看其他的文章。。

es新建表可以通过postman来建立

PUT请求发送127.0.0.1:9200/test 

其中test可以理解为表的名称 

然后我们可以向表中添加数据,因为es类似于Mongodb,存储的数据为json类型,是非关系型数据库,不存在字段这一说,所以数据我们可以随便存。

插入数据:127.0.0.1:9200/test/_doc/1002

请求体:

{
    "title":"小米手机1",
    "category":"小米1",
    "image":"www.yy.com",
    "price":3999.00
}

这里需要注意,还是要用put请求,test相当于表名,_doc可以理解为固定写法,最后的1002可以不写,写了就是指定这个数据的id为1002,不写则是随机生成的字符串

返回结果:

如果不写ID的话返回结果:

(不写的话得用post请求,上面我说的可能有点问题,因为我也是项目上需要所以也没深入了解,只看了半天,就随便写了个小demo) 

可以看见这里的id是nFez2IgBadwYgUd60r2A,这个是自动生成的。

然后我们可以根据id去查询。

127.0.0.1:9200/test/_doc/nFez2IgBadwYgUd60r2A

这里是get请求,需要注意一定不要选成post,否则会直接对数据进行更新。

返回值:
 

{
    "_index": "test",
    "_type": "_doc",
    "_id": "nFez2IgBadwYgUd60r2A",
    "_version": 1,
    "_seq_no": 1,
    "_primary_term": 1,
    "found": true,
    "_source": {
        "title": "小米手机1",
        "category": "小米1",
        "image": "www.yy.com",
        "price": 3999.00
    }
}

 然后删除某一条数据:

只需要将查找的请求方式改成delete就可以了。

返回值中的result是区分查找,插入和删除的方式。

还有就是查找某个表的所有数据。

使用get请求:127.0.0.1:9200/test/_search

最后就是清空这个表的所有数据

127.0.0.1:9200/test/_delete_by_query

test为要清空的表明,_delete_by_query可以理解为固定写法

请求体:

{
  "query": {
    "match_all": {}
  }
}

 返回值:

{
    "took": 133,
    "timed_out": false,
    "total": 1,
    "deleted": 1,
    "batches": 1,
    "version_conflicts": 0,
    "noops": 0,
    "retries": {
        "bulk": 0,
        "search": 0
    },
    "throttled_millis": 0,
    "requests_per_second": -1.0,
    "throttled_until_millis": 0,
    "failures": []
}

4.打开管道

curl -X PUT "localhost:9200/_ingest/pipeline/attachment" -d '{
 "description" : "Extract attachment information",
 "processors":[
 {
    "attachment":{
        "field":"data",
        "indexed_chars" : -1,
        "ignore_missing":true
     }
 },
 {
     "remove":{"field":"data"}
 }]}'
attachment是管道名称,后面JAVA代码里有用到,可以该

这里应该用java代码去创建管道,后期我改一下

可能遇到的报错:{"error":"Content-Type header [application/x-www-form-urlencoded] is not supported","status":406}
解决:添加-H 'content-Type:application/json'

5.JAVA编程

pom中引入elsearch和fastjson

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
            <version>2.0.26</version>
        </dependency>

上传方法

public AjaxResult upload(MultipartFile file) {
        if (file.isEmpty()) {
            // 处理文件为空的情况
            AjaxResult.error("文件为空!");
        }
        String uploadPath = "H:/esupload/";
        try {
            String fileName = file.getOriginalFilename();
            String[] nameArray=fileName.split("\\.");
            //todo  如果以后要用的Demo一定要修改这里!这里只是为了快速测试,没有写业务代码
            if(nameArray.length!=2){
                return null;
            }
            String prefix=nameArray[0];
            String suffix=nameArray[1];
            long fileSize=file.getSize();
            String filePath = uploadPath + File.separator + UUID.randomUUID()+"."+suffix;

            // 保存文件到指定路径
            file.transferTo(new File(filePath));
            //将文件传到es上
            HttpClient httpClient = HttpClients.createDefault();

            try {
                // 设置 Elasticsearch 主机和端口
                String elasticHost = "http://127.0.0.1";
                int elasticPort = 9200;
                // 设置索引名称
                String indexName = "book";
                // 指定要索引的文档路径
                String documentPath = filePath;  // 替换为实际的文档路径
                // 读取文档内容并进行 Base64 编码
                byte[] documentData = Files.readAllBytes(Paths.get(documentPath));
                String encodedDocument = Base64.getEncoder().encodeToString(documentData);
                // 创建文档 JSON
                //String documentJson = String.format("{\"data\":\"%s\"}", encodedDocument);
                String documentJson = String.format("{\"data\":\"%s\", \"prefix\":\"%s\", \"suffix\":\"%s\", \"filesize\":%d}",
                        encodedDocument, prefix, suffix, fileSize);                // 创建 POST 请求
                HttpPost postRequest = new HttpPost(String.format("%s:%d/%s/_doc?pipeline=attachment", elasticHost, elasticPort, indexName));
                // 设置请求主体为 JSON 格式
                HttpEntity entity = new StringEntity(documentJson, ContentType.APPLICATION_JSON);
                postRequest.setEntity(entity);
              /*  postRequest.setEntity(entity);*/
                // 发送请求
                HttpResponse response = httpClient.execute(postRequest);
                // 处理响应
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println(responseBody);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
            // 处理文件上传成功的情况
            return AjaxResult.success("上传成功!");
        } catch (IOException e) {
            // 处理文件上传失败的情况
            return AjaxResult.error("系统异常!");
        }

    }

列表方法

  public List<FileEntity> getList(HttpServletResponse response, String matchName, String searchValue) {
        if (StringUtils.isEmpty(matchName)) {
            matchName = "attachment.content";
        }

        List<FileEntity> files = new ArrayList<>();

        // 创建 Elasticsearch 客户端,用于信息查询
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
        try {
            // 设置要查询的索引名称
            String indexName = "book";
            // 构建查询请求
            SearchRequest searchRequest = new SearchRequest(indexName);
            // 构建查询条件

            /*  MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("attachment.content", searchValue);
             */
            if (StringUtils.isEmpty(searchValue)) {
                searchValue = "silan";
            // 使用TermQueryBuilder进行精确匹配

                SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
                searchSourceBuilder.query(QueryBuilders.matchAllQuery());
                searchSourceBuilder.size(10); // 设置返回的文档数量,默认为 10
                searchSourceBuilder.timeout(TimeValue.timeValueSeconds(10)); // 设置超时时间
            }else {
                MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(matchName, searchValue);
                BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
                boolQueryBuilder.must(matchPhraseQueryBuilder);
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
            }
            // 设置排序规则
            /*  sourceBuilder.sort("_source.content", SortOrder.ASC);*/
            // 设置分页
    /*        int from = 0; // 开始索引
            int size = 10; // 返回结果数量
            sourceBuilder.from(from);
            sourceBuilder.size(size);*/

            // 发起查询请求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 处理查询结果
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits) {
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                String id = hit.getId();
                String source = hit.getSourceAsString();
                try {
                    // 将 JSON 字符串转换为 JSONObject
                    JSONObject jsonObject = JSONObject.parseObject(source);
                    // 访问 JSONObject 的属性
                    String data = jsonObject.getString("data");
                    JSONObject attachment = jsonObject.getJSONObject("attachment");
                    String contentType = attachment.getString("content_type");
                    String contentLength = attachment.getString("content_length");
                    String content = attachment.getString("content");
                    String author = attachment.getString("author");
                    String prefix = jsonObject.getString("prefix");
                    String suffix = jsonObject.getString("suffix");
                    String filesize = jsonObject.getString("filesize");
                    FileEntity fileEntity = new FileEntity();
                    fileEntity.setId(id);
                    fileEntity.setData(data);
                    fileEntity.setName(prefix+"."+suffix);
                    fileEntity.setType(contentType);
                    fileEntity.setSize(filesize + "字节");
                    fileEntity.setAuthor(author);
                    fileEntity.setContent(content.substring(0, Math.min(content.length(), 300)));
                    fileEntity.setUploadTime(new Date());
                    files.add(fileEntity);
                    // 打印结果
                    System.out.println("Data: " + data);
                    System.out.println("Content Type: " + contentType);
                    System.out.println("Content: " + content);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        return files;
    }
FileEntity
@Getter
@Setter
public class FileEntity {
    private  String id;
    private  String name;
    private  String type;
    private  String author;
    private  String content;
    private  Date uploadTime;
    private  String size;
    private  String data;
}

有什么问题再问我。之前写了一半有事就存草稿了,然后今天打开发现这部分东西都忘了。。

猜你喜欢

转载自blog.csdn.net/qq_22570497/article/details/131314135