首先要明確的一點(diǎn)就是Elasticsearch的版本要和ingest-attachment的版本一致,要不然沒辦法安裝。然后還有一點(diǎn)JAVA版本要在11以上
先說說原理吧,其實(shí)就是將文件base64編碼,然后再用插件讀取文件內(nèi)容并保存到es中。
1.如果你的版本是JAVA1.8的話,最好換成JDK11
安裝完jdk之后用cmd查看一下java -version看看是否已經(jīng)從1.8修改為了11
如果沒有邊的話則需要修改環(huán)境變量
可以在開始菜單輸入env快速打開環(huán)境變量配置
?首先修改JAVA_HOME
然后還是和配置jdk一樣修改path?
但是這里有一個坑點(diǎn),那就是除了你自己配置的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
下載完畢之后解壓
進(jìn)入bin目錄?
雙擊elasticsearch.bat即可運(yùn)行es
?運(yùn)行完成后可以訪問http://127.0.0.1:9200/?查看是否正常運(yùn)行
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的根目錄下運(yùn)行下面的命令
bin\elasticsearch-plugin install file:///D:\ingest-attachment-5.4.2.zip?
這樣他就會將ingest-attachment的插件安裝到elasticsearch上了。這里就不放截圖了,因?yàn)槲乙呀?jīng)安裝好了。
安裝好之后可以通過PowerShell查看是否安裝完成??
首先切換目錄到ES根目錄:
輸入?.\bin\elasticsearch-plugin list如果有ingest-attachment則代表安裝成功
?
?然后我們可以重啟es。重啟方式就是關(guān)閉cmd然后重新打開步驟1的.bat
3.POSTMAN? ES基礎(chǔ)使用教程
如果已經(jīng)會使用es請?zhí)^該步驟
先偷一張圖
我就以mysql數(shù)據(jù)庫舉例吧,比如說mysql中的表在es里應(yīng)該叫索引,我就直接叫表吧,畢竟不跳過這里的估計也沒太看過es的教程。我這里就是簡單的說一說,想要具體了解請看其他的文章。。
es新建表可以通過postman來建立
用PUT請求發(fā)送127.0.0.1:9200/test?
其中test可以理解為表的名稱?
然后我們可以向表中添加數(shù)據(jù),因?yàn)閑s類似于Mongodb,存儲的數(shù)據(jù)為json類型,是非關(guān)系型數(shù)據(jù)庫,不存在字段這一說,所以數(shù)據(jù)我們可以隨便存。
插入數(shù)據(jù):127.0.0.1:9200/test/_doc/1002
請求體:
{
"title":"小米手機(jī)1",
"category":"小米1",
"image":"www.yy.com",
"price":3999.00
}
這里需要注意,還是要用put請求,test相當(dāng)于表名,_doc可以理解為固定寫法,最后的1002可以不寫,寫了就是指定這個數(shù)據(jù)的id為1002,不寫則是隨機(jī)生成的字符串
返回結(jié)果:
如果不寫ID的話返回結(jié)果:
(不寫的話得用post請求,上面我說的可能有點(diǎn)問題,因?yàn)槲乙彩琼?xiàng)目上需要所以也沒深入了解,只看了半天,就隨便寫了個小demo)?
可以看見這里的id是nFez2IgBadwYgUd60r2A,這個是自動生成的。
然后我們可以根據(jù)id去查詢。
127.0.0.1:9200/test/_doc/nFez2IgBadwYgUd60r2A
這里是get請求,需要注意一定不要選成post,否則會直接對數(shù)據(jù)進(jìn)行更新。
返回值:
?
{
"_index": "test",
"_type": "_doc",
"_id": "nFez2IgBadwYgUd60r2A",
"_version": 1,
"_seq_no": 1,
"_primary_term": 1,
"found": true,
"_source": {
"title": "小米手機(jī)1",
"category": "小米1",
"image": "www.yy.com",
"price": 3999.00
}
}
?然后刪除某一條數(shù)據(jù):
只需要將查找的請求方式改成delete就可以了。
返回值中的result是區(qū)分查找,插入和刪除的方式。
還有就是查找某個表的所有數(shù)據(jù)。
使用get請求:127.0.0.1:9200/test/_search
最后就是清空這個表的所有數(shù)據(jù)
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代碼里有用到,可以該
這里應(yīng)該用java代碼去創(chuàng)建管道,后期我改一下
可能遇到的報錯:{"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一定要修改這里!這里只是為了快速測試,沒有寫業(yè)務(wù)代碼
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 {
// 設(shè)置 Elasticsearch 主機(jī)和端口
String elasticHost = "http://127.0.0.1";
int elasticPort = 9200;
// 設(shè)置索引名稱
String indexName = "book";
// 指定要索引的文檔路徑
String documentPath = filePath; // 替換為實(shí)際的文檔路徑
// 讀取文檔內(nèi)容并進(jìn)行 Base64 編碼
byte[] documentData = Files.readAllBytes(Paths.get(documentPath));
String encodedDocument = Base64.getEncoder().encodeToString(documentData);
// 創(chuàng)建文檔 JSON
//String documentJson = String.format("{\"data\":\"%s\"}", encodedDocument);
String documentJson = String.format("{\"data\":\"%s\", \"prefix\":\"%s\", \"suffix\":\"%s\", \"filesize\":%d}",
encodedDocument, prefix, suffix, fileSize); // 創(chuàng)建 POST 請求
HttpPost postRequest = new HttpPost(String.format("%s:%d/%s/_doc?pipeline=attachment", elasticHost, elasticPort, indexName));
// 設(shè)置請求主體為 JSON 格式
HttpEntity entity = new StringEntity(documentJson, ContentType.APPLICATION_JSON);
postRequest.setEntity(entity);
/* postRequest.setEntity(entity);*/
// 發(fā)送請求
HttpResponse response = httpClient.execute(postRequest);
// 處理響應(yīng)
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("系統(tǒng)異常!");
}
}
列表方法文章來源:http://www.zghlxwxcb.cn/news/detail-546654.html
public List<FileEntity> getList(HttpServletResponse response, String matchName, String searchValue) {
if (StringUtils.isEmpty(matchName)) {
matchName = "attachment.content";
}
List<FileEntity> files = new ArrayList<>();
// 創(chuàng)建 Elasticsearch 客戶端,用于信息查詢
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));
try {
// 設(shè)置要查詢的索引名稱
String indexName = "book";
// 構(gòu)建查詢請求
SearchRequest searchRequest = new SearchRequest(indexName);
// 構(gòu)建查詢條件
/* MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("attachment.content", searchValue);
*/
if (StringUtils.isEmpty(searchValue)) {
searchValue = "silan";
// 使用TermQueryBuilder進(jìn)行精確匹配
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchSourceBuilder.size(10); // 設(shè)置返回的文檔數(shù)量,默認(rèn)為 10
searchSourceBuilder.timeout(TimeValue.timeValueSeconds(10)); // 設(shè)置超時時間
}else {
MatchPhraseQueryBuilder matchPhraseQueryBuilder = QueryBuilders.matchPhraseQuery(matchName, searchValue);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(matchPhraseQueryBuilder);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(boolQueryBuilder);
searchRequest.source(sourceBuilder);
}
// 設(shè)置排序規(guī)則
/* sourceBuilder.sort("_source.content", SortOrder.ASC);*/
// 設(shè)置分頁
/* int from = 0; // 開始索引
int size = 10; // 返回結(jié)果數(shù)量
sourceBuilder.from(from);
sourceBuilder.size(size);*/
// 發(fā)起查詢請求
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 處理查詢結(jié)果
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
String id = hit.getId();
String source = hit.getSourceAsString();
try {
// 將 JSON 字符串轉(zhuǎn)換為 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 + "字節(jié)");
fileEntity.setAuthor(author);
fileEntity.setContent(content.substring(0, Math.min(content.length(), 300)));
fileEntity.setUploadTime(new Date());
files.add(fileEntity);
// 打印結(jié)果
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;
}
有什么問題再問我。之前寫了一半有事就存草稿了,然后今天打開發(fā)現(xiàn)這部分東西都忘了。。文章來源地址http://www.zghlxwxcb.cn/news/detail-546654.html
到了這里,關(guān)于使用Elasticsearch進(jìn)行word,excel,PDF的全文檢索 windows實(shí)現(xiàn) 超完整(ingest-attachment實(shí)現(xiàn))的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!