ES(Elasticsearch)的应用与代码示例

Elasticsearch应用与代码示例技术文章大纲

一、引言
  1. Elasticsearch在现代化应用中的核心作用
  2. 典型应用场景分析(日志分析/全文检索/数据聚合)
二、环境准备(前提条件)
  1. Elasticsearch 8.x集群部署要点
  2. IK中文分词插件配置指南
  3. Ingest Attachment插件安装说明
三、核心代码结构解析
src/main/
├── java/
│   ├── config/
│   │   └── ElasticSearchConfig.java
│   ├── controller/
│   │   └── ElasticSearchController.java
│   ├── service/
│   │   ├── ElasticSearchService.java
│   │   └── ElasticSearchServiceImpl.java
│   ├── model/
│   │   ├── FileData.java
│   │   ├── Attachment.java
│   │   └── SearchResult.java
│   ├── dto/
│   │   └── WarningInfoDto.java
│   └── util/
│       └── ElasticSearchUtils.java
四、核心组件实现(含代码示例)

1. 配置中心(ElasticSearchConfig.java)
application.properties or yml

es.uri=192.168.1.1
es.port=9200
es.username=""
es.password=""
package com.zbxsoft.wds.config;import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.alibaba.fastjson.parser.deserializer.JSONPDeserializer;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** es配置*/
@Configuration
@ConfigurationProperties(prefix = "es")
public class ElasticSearchConfig{public String getUri() {return uri;}public void setUri(String uri) {this.uri = uri;}public Integer getPort() {return port;}public void setPort(Integer port) {this.port = port;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}private String uri;private Integer port;private String password;private String username;@Beanpublic ElasticsearchClient elasticsearchClient(@Autowired(required = false) JsonpMapper jsonpMapper, @Autowired(required = false) ObjectMapper objectMapper) {// 解析hostlist配置信息// 创建HttpHost数组,其中存放es主机和端口的配置信息HttpHost[] httpHostArray = new HttpHost[1];httpHostArray[0] = new HttpHost(uri,Integer.valueOf(port));RestClientBuilder builder = RestClient.builder(httpHostArray);final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)){credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));RestClient client = RestClient.builder(new HttpHost(uri,Integer.valueOf(port))).build();ElasticsearchTransport transport = new RestClientTransport(client, new JacksonJsonpMapper());return new ElasticsearchClient(transport);}RestClient restClient = builder.build();ElasticsearchTransport transport = null;if (jsonpMapper != null) {transport = new RestClientTransport(restClient, jsonpMapper);} else if (objectMapper != null) {transport = new RestClientTransport(restClient, new JacksonJsonpMapper(objectMapper));} else {transport = new RestClientTransport(restClient, new JacksonJsonpMapper());}// Create the transport with a Jackson mapper// And create the API clientreturn new ElasticsearchClient(transport);}
}

2. 数据处理模型(FileData.java)

package com.zbxsoft.wds.config;import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.zbxsoft.wds.fileupload.Attachment;
import lombok.Data;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;import java.io.Serializable;
import java.util.Objects;@Data
@Document(indexName = "file_data", createIndex = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public class FileData implements Serializable {@Field(name = "file_id",type = FieldType.Text)private String file_id;@Field(name = "file_type",type = FieldType.Text)private String file_type;@Field(name = "file_name",type = FieldType.Text)private String file_name;@Field(name = "file_url",type = FieldType.Text)private String file_url;@Field(name = "file_size",type = FieldType.Text)private String file_size;@Field(name = "group_file_id",type = FieldType.Text)private String group_file_id;@Field(name = "file_suffix",type = FieldType.Text)private String file_suffix;@Field(name = "file_dir_name",type = FieldType.Text)private String file_dir_name;//保存时使用@Field(name = "attachment.content",type = FieldType.Text)private String content;//检索时使用private Attachment attachment;}}

3. 附件解析组件(Attachment.java)

package com.zbxsoft.wds.fileupload;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;import java.io.Serializable;@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Attachment implements Serializable {private String date;private String content_type;private String author;private String language;private String title;private String content;private String content_length;
}}

4. 服务层实现(ElasticSearchService.java)

package com.zbxsoft.wds.fileupload;import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zbxsoft.wds.config.FileData;
import org.springframework.http.HttpEntity;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.util.List;
import java.util.Map;public interface ElasticsearchService {HttpEntity<?> createFileIndex(MultipartFile file) throws IOException;String createFileIndex(FileData fileData) throws IOException;Map<String,Double> queryWord(String keyword) throws IOException;IPage<SearchResult> queryWord(WarningInfoDto warningInfoDto) throws IOException;List<String> getAssociationalWordOther(WarningInfoDto warningInfoDto);String updateFileIndex(String id, FileData fileData) throws IOException;
}

工具类(ElasticSearchUtils.java)

package com.zbxsoft.wds.config;import cn.hutool.extra.spring.SpringUtil;import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch._types.SortOptions;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import co.elastic.clients.elasticsearch._types.mapping.DateProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch._types.mapping.TextProperty;
import co.elastic.clients.elasticsearch._types.mapping.TypeMapping;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.core.search.HitsMetadata;
import co.elastic.clients.elasticsearch.core.search.TotalHits;
import co.elastic.clients.elasticsearch.core.search.TotalHitsRelation;
import co.elastic.clients.elasticsearch.core.search.TrackHits;
import co.elastic.clients.elasticsearch.indices.*;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;import java.io.IOException;
import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;@Slf4j
public class ElasticSearchUtils<T> {public static ElasticsearchClient elasticsearchClient;public String index;public Class obj;public String idField;public Set<String> fields;static {ElasticSearchConfig elasticSearchConfig = SpringUtil.getBean(ElasticSearchConfig.class);
//        elasticsearchClient = elasticSearchConfig.elasticsearchClient();}/*** 获取id字段** @return*/private String getIdValue(T t) throws Exception {Field field = t.getClass().getDeclaredField(idField);field.setAccessible(true);Object object = field.get(t);return object.toString();}/*** 判断索引是否存在** @return*/public Boolean getIndex() {try {GetIndexRequest getIndexRequest = GetIndexRequest.of(builder -> builder.index(index));GetIndexResponse getIndexResponse = elasticsearchClient.indices().get(getIndexRequest);log.info("getIndexResponse:{}", getIndexResponse);return true;} catch (IndexOutOfBoundsException | IOException e) {log.info("getIndexResponse:{}", e.getMessage());return false;}}public void deleteIndex() throws IOException {//1.创建索引请求DeleteIndexRequest request = DeleteIndexRequest.of(builder -> builder.index(index));//2.执行创建请求DeleteIndexResponse delete = elasticsearchClient.indices().delete(request);//如果为true就删除了log.info("DeleteIndexRequest:{}", delete);}/*** 插入数据** @throws IOException*/public void push(T t) throws Exception {String id = getIdValue(t);IndexRequest<T> indexRequest = IndexRequest.of(b -> b.index(index).id(id).document(t)//刷新可以立刻搜索到,消耗性能/*.refresh(Refresh.True)*/);elasticsearchClient.index(indexRequest);}/*** 索引信息查询** @throws IOException*/public T query(String id) throws IOException {GetResponse<T> response = elasticsearchClient.get(g -> g.index(index).id(id), obj);if (response.found()) {return response.source();}return null;}/*** 索引信息查询** @throws IOException*/public HitsMetadata<T> queryList(int page, int pageSize, Query query, SortOptions... sortOptions) throws IOException {SearchResponse<T> search = elasticsearchClient.search(s -> s.index(index).query(query).trackTotalHits(TrackHits.of(i -> i.enabled(true))).sort(Arrays.asList(sortOptions)).from((page - 1) * pageSize).size(pageSize), obj);return search.hits();}/*** 删除文档** @throws IOException*/public boolean del(String id) throws IOException {DeleteResponse delete = elasticsearchClient.delete(d -> d.index(index).id(id));Result result = delete.result();return "deleted".equals(result.jsonValue()) | "not_found".equals(result.jsonValue());}/*** 批量** @throws IOException*/public Map<String, String> batchDel(Set<String> ids) throws Exception {BulkRequest.Builder br = new BulkRequest.Builder();for (String id : ids) {br.operations(op -> op.delete(d -> d.index(index).id(id)));}return requestBulk(br);}/*** 批量** @throws IOException*/public Map<String, String> batchAdd(List<T> list) throws Exception {BulkRequest.Builder br = new BulkRequest.Builder();for (T t : list) {String idValue = getIdValue(t);br.operations(op -> op.index(idx -> idx.index(index).id(idValue).document(t)));}return requestBulk(br);}/*** 处理批量请求** @param br* @return* @throws IOException*/private Map<String, String> requestBulk(BulkRequest.Builder br) throws IOException {//刷新可以立刻搜索到,消耗性能//br.refresh(Refresh.True);BulkResponse result = elasticsearchClient.bulk(br.build());System.out.println(result);Map<String, String> returnResult = new HashMap<>();if (result.errors()) {returnResult = result.items().stream().filter(e -> e.error() != null).collect(Collectors.toMap(BulkResponseItem::id, b -> b.error().reason()));}return returnResult;}/*** 分组* @param map* @return* @throws IOException*/public Map<String, Aggregate> buildAggregate(Map<String, Aggregation> map) throws IOException {SearchResponse<T> search = elasticsearchClient.search(s -> s.index(index).size(0).aggregations(map), obj);return search.aggregations();}public Long queryCount(Query query) throws IOException {CountResponse search = elasticsearchClient.count(s -> s.index(index).query(query));return search.count();}}

服务层实现(ElasticSearchServiceImpl.java)

package com.zbxsoft.wds.fileupload;import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.search.*;import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zbxsoft.wds.aneo4j.TextAnalysis;
import com.zbxsoft.wds.aneo4j.rep.CustomNeo4jRepository;
import com.zbxsoft.wds.filequery.FileQuery;
import com.zbxsoft.wds.mapper.FileQueryMapper;
import com.zbxsoft.wds.config.FileData;
import com.zbxsoft.xwk.vo.R;
import lombok.extern.slf4j.Slf4j;import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.util.Pair;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.*;@Service
@Slf4j
public class ElasticsearchServiceImpl implements ElasticsearchService {@Autowiredprivate ElasticsearchClient client;@Autowiredprivate ResourceLoader resourceLoader;@Autowiredprotected FileQueryMapper fileQueryMapper;@Value("${file.server.address}")private String fileServerAddress;@Autowiredprivate CustomNeo4jRepository customNeo4jRepository;/*** 创建索引* @param fileData 文件数据* @return 索引id* @throws IOException exp*/public String createFileIndex(FileData fileData) throws IOException {String path = fileData.getFile_url();String url = fileServerAddress + path;log.info("已上传文件地址:" + url);String fileName = FileUtil.getName(url);// 上传并返回新文件名称String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);File file = File.createTempFile(fileName, prefix);IOUtils.copy(new URL(url),file);try (PDDocument document = PDDocument.load(file)) {//提取pdf中的文本内容PDFTextStripper pdfTextStripper = new PDFTextStripper();String text = pdfTextStripper.getText(document);//该主键 在es dm 中用作数据唯一id, 在neo4j中作为实体的typeString id = fileData.getFile_id();//提取文章中的关键词List<String> keywords = TextAnalysis.getKeywords(text);if (CollectionUtil.isNotEmpty(keywords)) {//构建知识图谱customNeo4jRepository.buildArticleKeywordGraph(id, keywords);//更新keywords字段 file_id 就是数据库中存在的主键updateKeywords(id, String.join(",", keywords));}} catch (IOException e) {log.error("提取文本或创建关键词图谱失败,异常信息: {}", e.toString());}//最后建立该文章的索引String _docId = createIndex(file,fileData);return _docId;}/*** 更新文件对象的keyword* @param id 主键* @param keyword 关键词*/private void updateKeywords(String id,String keyword){LambdaUpdateWrapper<FileQuery> updateWrapper = new LambdaUpdateWrapper<>();updateWrapper.eq(FileQuery::getFileQueryId,id).set(FileQuery::getKeyword,keyword);fileQueryMapper.update(updateWrapper);}/*** 创建索引* @param file 文件* @param fileData 文件对象* @return 索引id*/private String createIndex(File file, FileData fileData) {try {byte[] bytes = getContent(file);String base64 = Base64.getEncoder().encodeToString(bytes);fileData.setContent(base64);IndexRequest<Object> requestData = IndexRequest.of(i -> i.index("file_data").pipeline("attachment").id(fileData.getFile_id()).document(fileData));IndexResponse indexResponse = client.index(requestData);log.info("indexResponse:" + indexResponse);return indexResponse.id();} catch (IOException e) {log.error("文件上传异常,异常信息: {}", e.toString());return "";}}/*** 更新索引,在更新文件的时候发生* @param id 索引id 也是关系库主键* @param fileData 文件对象* @return* @throws IOException*/@Overridepublic String updateFileIndex(String id, FileData fileData) throws IOException {//直接删除索引, 重建DeleteRequest deleteRequest = DeleteRequest.of(s -> s.index("file_data").id(id));client.delete(deleteRequest);String _docId = createFileIndex(fileData);return _docId;}/*** 文件转base64** @param file 文件对象* @return buffer* @throws IOException*/private byte[] getContent(File file) throws IOException {long fileSize = file.length();if (fileSize > Integer.MAX_VALUE) {log.info("file too big...");return null;}FileInputStream fi = new FileInputStream(file);byte[] buffer = new byte[(int) fileSize];int offset = 0;int numRead = 0;while (offset < buffer.length&& (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {offset += numRead;}// 确保所有数据均被读取if (offset != buffer.length) {throw new ServiceException("Could not completely read file "+ file.getName());}return buffer;}/*** 给定keyword 检索数据* @param keyword* @return* @throws IOException*/public Map<String,Double> queryWord(String keyword) throws IOException {SearchResponse<FileData> response = doQuery(keyword);log.info("检索结果: {}", response.hits().hits());List<Pair<String,Double>> idList = Lists.newArrayList();Map<String,Double> idsWithScore = Maps.newHashMap();List<Hit<FileData>> hits = response.hits().hits();for (Hit<FileData> hit : hits) {Double score = hit.score();String id = hit.id();score = score == null ? 0.0d : score;idsWithScore.put(id,score);}log.info("查询数据: {}", idsWithScore);return idsWithScore;}/*** es attachment.content 检索封装* @param keyword 关键词* @return 检索结果* @throws IOException exp*/private SearchResponse<FileData> doQuery(String keyword) throws IOException {Map<String, HighlightField> map = new HashMap<>();HighlightField build = new HighlightField.Builder().preTags("").postTags("").build();map.put("file_name",build);map.put("attachment.content",HighlightField.of(hf -> hf.preTags("").postTags("").numberOfFragments(4)));Highlight highlight = Highlight.of(h -> h.type(HighlighterType.of(ht -> ht.builtin(BuiltinHighlighterType.Unified))).fields(map).fragmentSize(50).numberOfFragments(5));//索引 file_name 分词器 为ik_max_word 颗粒度较细  而attachment.content 使用ik_smart分词器 , 颗粒度相对粗一点SearchResponse<FileData> response = client.search(s -> s.index("file_data").highlight(highlight).query(q -> q.bool(b -> b.should(sh -> sh.match(t -> t.field("file_name").query(keyword))).should(sh -> sh.match(t -> t.field("attachment.content").query(keyword))))),FileData.class);return response;}/*** 高亮分词搜索其它类型文档** @param warningInfoDto* @return*/public IPage<SearchResult> queryWord(WarningInfoDto warningInfoDto) throws IOException {//分页SearchResponse<FileData> response = doQuery(warningInfoDto.getKeyword());//手动创建分页对象IPage<SearchResult> warningInfoIPage = getFileDataIPage(warningInfoDto, response);return warningInfoIPage;}/*** 获取检索数据, 分页* @param warningInfoDto* @param response* @return*/@NotNullprivate static IPage<SearchResult> getFileDataIPage(WarningInfoDto warningInfoDto, SearchResponse<FileData> response) {List<Hit<FileData>> hits = response.hits().hits();TotalHits total = response.hits().total();List<SearchResult> resultList = new LinkedList<>();//处理返回内容for (Hit<FileData> hit : hits) {Map<String, List<String>> map = hit.highlight();List<String> highLightWords = Lists.newArrayList();map.forEach((k,v) -> highLightWords.addAll(v));FileData fileData = hit.source();SearchResult searchResult = new SearchResult(fileData,highLightWords);resultList.add(searchResult);}//        //设置一个最后需要返回的实体类集合//手动分页返回信息IPage<SearchResult> warningInfoIPage = new Page<>();assert total != null;warningInfoIPage.setTotal(total.value());warningInfoIPage.setRecords(resultList);warningInfoIPage.setCurrent(warningInfoDto.getPageIndex());warningInfoIPage.setSize(warningInfoDto.getPageSize());warningInfoIPage.setPages(warningInfoIPage.getTotal() % warningInfoDto.getPageSize());return warningInfoIPage;}/*** 文档信息关键词联想(根据输入框的词语联想文件名称)** @param warningInfoDto* @return*/public List<String> getAssociationalWordOther(WarningInfoDto warningInfoDto) {
//        //需要查询的字段
//        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
//                .should(QueryBuilders.matchBoolPrefixQuery("fileName", warningInfoDto.getKeyword()));
//        //contentType标签内容过滤
//        boolQueryBuilder.must(QueryBuilders.termsQuery("contentType", warningInfoDto.getContentType()));
//        //构建高亮查询
//        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
//                .withQuery(boolQueryBuilder)
//                .withHighlightFields(
//                        new HighlightBuilder.Field("fileName")
//                )
//                .withHighlightBuilder(new HighlightBuilder().preTags("<span style='color:red'>").postTags("</span>"))
//                .build();
//        //查询
//        SearchHits<FileData> search = null;
//        try {
//            search = client.search(searchQuery);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            throw new ServiceException(String.format("操作错误,请联系管理员!%s", ex.getMessage()));
//        }
//        //设置一个最后需要返回的实体类集合
//        List<String> resultList = new LinkedList<>();
//        //遍历返回的内容进行处理
//        for (org.springframework.data.elasticsearch.core.SearchHit<FileInfo> searchHit : search.getSearchHits()) {
//            //高亮的内容
//            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
//            //将高亮的内容填充到content中
//            searchHit.getContent().setFileName(highlightFields.get("fileName") == null ? searchHit.getContent().getFileName() : highlightFields.get("fileName").get(0));
//            if (highlightFields.get("fileName") != null) {
//                resultList.add(searchHit.getContent().getFileName());
//            }
//        }
//        //list去重
//        List<String> newResult = null;
//        if (!FastUtils.checkNullOrEmpty(resultList)) {
//            if (resultList.size() > 9) {
//                newResult = resultList.stream().distinct().collect(Collectors.toList()).subList(0, 9);
//            } else {
//                newResult = resultList.stream().distinct().collect(Collectors.toList());
//            }
//        }return new ArrayList<>();}/*** 上传文件并进行文件内容识别上传到es 测试使用* @param file* @return*/public HttpEntity<?> createFileIndex(MultipartFile file) throws IOException {//http://192.168.100.243//file/wds/fileQuery/2024-12/1734319529179/downloadFile.pdf
//        InputStream inputStream = resourceLoader.getResource(url).getInputStream();String fileName = file.getName();String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);File tempFile = File.createTempFile(fileName, prefix);// 上传文件路径file.transferTo(tempFile);FileData fileData = new FileData();fileData.setFile_url("http://localhost:9000/bucket/p2");fileData.setFile_id(UUID.fastUUID().toString(true));fileData.setFile_name("张飞吃豆芽333.pdf");fileData.setFile_suffix(".pdf");fileData.setFile_type("pdf");fileData.setFile_size("44");fileData.setFile_dir_name("p2");fileData.setGroup_file_id("g1");String _docId = createIndex(tempFile,fileData);return StringUtils.isBlank(_docId) ? R.badRequest("文件上传异常") : R.success("文件上传成功");}}
五、数据传输

1. 前端请求数据传输(WarningInfoDto.java)

package com.zbxsoft.wds.fileupload;import lombok.Data;import java.util.List;/*** 前端请求数据传输* WarningInfo* @author luoY*/
@Datapublic class WarningInfoDto{/*** 页数*/private Integer pageIndex;/*** 每页数量*/private Integer pageSize;/*** 查询关键词*/private String keyword;/*** 内容类型*/private List<String> contentType;/*** 用户手机号*/private String phone;
}
}

2. 文档全文检索接口(ElasticSearchController.java)

package com.zbxsoft.wds.fileupload;import com.baomidou.mybatisplus.core.metadata.IPage;import com.zbxsoft.wds.common.R;import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;/*** es搜索引擎** @author luoy*/
@RestController
@RequestMapping("es")
public class ElasticsearchController {@Resourceprivate ElasticsearchService elasticsearchService;@PostMapping("/uploadFile")public HttpEntity<?> uploadFile(@RequestParam(required = false) MultipartFile file) throws IOException {return elasticsearchService.createFileIndex(file);}/*** 告警信息关键词联想** @param warningInfoDto* @return*/@PostMapping("getAssociationalWordDoc")public HttpEntity<?> getAssociationalWordDoc(@RequestBody WarningInfoDto warningInfoDto, HttpServletRequest request) {List<String> words = elasticsearchService.getAssociationalWordOther(warningInfoDto);return R.list(words);}/*** 告警信息高亮分词分页查询** @param warningInfoDto* @return*/@PostMapping("queryHighLightWordDoc")public HttpEntity<?> queryHighLightWordDoc(@RequestBody WarningInfoDto warningInfoDto,HttpServletRequest request) throws IOException {IPage<SearchResult> warningInfoListPage = elasticsearchService.queryWord(warningInfoDto);return R.entity(warningInfoListPage);}
}

3. 数据返回(SearchResult.java)

package com.zbxsoft.wds.fileupload;import com.zbxsoft.wds.config.FileData;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;import java.io.Serializable;
import java.util.List;@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class SearchResult implements Serializable {private FileData fileData;private List<String> highLightWords;
}
六、高级功能实现
  1. 多条件复合查询构建技巧
  2. 聚合统计实现方案
  3. 搜索高亮显示配置
七、性能优化建议
  1. 索引分片策略设计
  2. 查询DSL优化技巧
  3. 批量操作最佳实践
八、总结与展望
  1. 当前架构优势分析
  2. 后续演进方向建议

(注:各代码示例需配合完整的类定义和import语句,实际开发中需补充异常处理、日志记录等生产级代码要素)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/905742.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

临床决策支持系统的提示工程优化路径深度解析

引言 随着人工智能技术在医疗领域的迅猛发展,临床决策支持系统(CDSS)正经历从传统规则引擎向智能提示工程的范式转变。在这一背景下,如何构建既符合循证医学原则又能适应个体化医疗需求的CDSS成为医学人工智能领域的核心挑战。本报告深入剖析了临床决策支持系统中提示工程的…

火山RTC 8 SDK集成进项目中

一、SDK 集成预备工作 1、SDK下载 https://www.volcengine.com/docs/6348/75707 2、解压后 3、放在自己项目中的位置 1&#xff09;、include 2&#xff09;、lib 3)、dll 暂时&#xff0c;只需要VolcEngineRTC.dll RTCFFmpeg.dll openh264-4.dll&#xff0c; 放在intLive2…

OkHttp用法-Java调用http服务

特点&#xff1a;高性能&#xff0c;支持异步请求&#xff0c;连接池优化 官方文档&#xff1a;提供快速入门指南和高级功能&#xff08;如拦截器、连接池&#xff09;的详细说明&#xff0c;GitHub仓库包含丰富示例。 社区资源&#xff1a;中文教程丰富&#xff0c;GitHub高…

python中常用的参数以及命名规范

以下是 Python 中常见的命名规范、参数用法及在大型项目中常用的操作模式&#xff0c;供记录参考&#xff1a; 1. 命名规范&#xff08;Naming Conventions&#xff09; 前缀/形式含义示例_age单下划线&#xff1a;弱“私有”标记&#xff08;可访问但不建议外部使用&#xff…

第五十七篇 Java接口设计之道:从咖啡机到智能家居的编程哲学

目录 引言&#xff1a;生活中的接口无处不在一、咖啡机与基础接口&#xff1a;理解抽象契约1.1 咖啡制作的标准接口 二、智能家居与策略模式&#xff1a;灵活切换实现2.1 温度调节策略场景 三、物流系统与工厂模式&#xff1a;标准接口下的多样实现3.1 快递运输接口设计 四、健…

第二十六天打卡

全局变量 global_var 全局变量是定义在函数、类或者代码块外部的变量&#xff0c;它在整个程序文件内都能被访问。在代码里&#xff0c; global_var 就是一个全局变量&#xff0c;下面是相关代码片段&#xff1a; print("\n--- 变量作用域示例 ---") global_var …

联合查询

目录 1、笛卡尔积 2、联合查询 2.1、内连接 2.2、外连接 1、笛卡尔积 笛卡尔积&#xff1a; 笛卡尔积是让两个表通过排列组合的方式&#xff0c;得到的一个更大的表。笛卡尔积的列数&#xff0c;是这两个表的列数相加&#xff0c;笛卡尔积的行数&#xff0c;是这两个表的行…

【HTML5学习笔记2】html标签(下)

1表格标签 1.1表格作用 显示数据 1.2基本语法 <table><tr> 一行<td>单元格1</td></tr> </table> 1.3表头单元格标签 表头单元格会加粗并且居中 <table><tr> 一行<th>单元格1</th></tr> </table&g…

window 显示驱动开发-分页视频内存资源

与 Microsoft Windows 2000 显示驱动程序模型不同&#xff0c;Windows Vista 显示驱动程序模型允许创建比可用物理视频内存总量更多的视频内存资源&#xff0c;然后根据需要分页进出视频内存。 换句话说&#xff0c;并非所有视频内存资源都同时位于视频内存中。 GPU 的管道中可…

《C 语言指针高级指南:字符、数组、函数指针的进阶攻略》

目录 一. 字符指针变量 二. 数组指针变量 三. 二维数组传参 3.1 二维数组的本质 3.2 访问方式与地址计算 3.3 二维数组的传参方式 3.4 深入解析 *(*(arri)j) 与 arr[i][j] 的等价性 四. 函数指针变量 4.1 函数指针变量的创建 4.2 函数指针变量的使用 4.3 两段"…

Unity:场景管理系统 —— SceneManagement 模块

目录 &#x1f3ac; 什么是 Scene&#xff08;场景&#xff09;&#xff1f; Unity 项目中的 Scene 通常负责什么&#xff1f; &#x1f30d; 一个 Scene 包含哪些元素&#xff1f; Scene 的切换与管理 &#x1f4c1; 如何创建与管理 Scenes&#xff1f; 什么是Scene Man…

内容中台重构企业知识管理路径

智能元数据驱动知识治理 现代企业知识管理的核心挑战在于海量非结构化数据的有效治理。通过智能元数据分类引擎&#xff0c;系统可自动识别文档属性并生成多维标签体系&#xff0c;例如将技术手册按产品版本、功能模块、适用场景进行动态标注。这种动态元数据框架不仅支持跨部…

Vue3:脚手架

工程环境配置 1.安装nodejs 这里我已经安装过了&#xff0c;只需要打开链接Node.js — Run JavaScript Everywhere直接下载nodejs&#xff0c;安装直接一直下一步下一步 安装完成之后我们来使用电脑的命令行窗口检查一下版本 查看npm源 这里npm源的地址是淘宝的源&#xff0…

悦数图数据库一体机发布,让复杂关联计算开箱即用

在金融风控、政务治理、能源监测等关键领域&#xff0c;复杂数据关联分析已成为业务决策的核心需求。然而&#xff0c;信创场景的特殊性——全栈自主可控、海量实时计算、系统高可用性——对传统技术架构提出了近乎苛刻的要求。悦数图数据库一体机应运而生&#xff0c;以软硬协…

收放卷“材料停机减速距离“计算FC(算法公式+ST源代码+C++代码)

PLC运动控制基础系列之梯形速度曲线 PLC运动控制基础系列之梯形速度曲线_三菱运动控制模块梯形加减速-CSDN博客文章浏览阅读3.2k次,点赞3次,收藏7次。本文是关于PLC运动控制的基础教程,重点介绍了梯形速度曲线的概念、计算和应用。讨论了梯形加减速在启动和停止阶段的作用,…

Centos7系统(最小化安装)安装zabbix7版本详细文章、nginx源代码配置、php源代码、mysql-yum安装

zabbix官网链接下载zabbix源代码安装包 选择zabbix版本&#xff08;此文章使用zabbix7.0版本&#xff09; 安装之前由于是最小化安装centos7安装一些开发环境和工具包 文章使用国内阿里源 cd /etc/yum.repos.d/;curl -O https://mirrors.aliyun.com/repo/epel-7.repo;curl -…

描述性统计图表

一、核心图表类型与用途 1、直方图(Histogram) (1)定义:用连续矩形表示数据分布,横轴为数据区间,纵轴为频数或频率。 (2)用途:展示数据分布形态(对称、偏态)、识别离群值。 (3)适用场景:分析连续型变量的分布特征,如收入分布、考试成绩分布。 2、箱线图(Box P…

ThinkPad X250电池换电池芯(理论技术储备)

参考&#xff1a;笔记本电池换电芯的经验与心得分享 - 经典ThinkPad专区 - 专门网 换电池芯&#xff0c;需要克服以下问题&#xff1a; 1 拆电池。由于是超声波焊接&#xff0c;拆解比较费力&#xff0c;如果暴力撬&#xff0c;有可能导致电池壳变形... 2 替换电池芯的时候如…

Java(基础) day01 初识Java

目录 一、运行Java程序 二、基本数据类型 1、整数类型 ​编辑2、浮点型 3、字符型 4、布尔类型 一、运行Java程序 Java是一门半编译型、半解释型语言。先通过javac编译程序把xxx.java源文件进行编译&#xff0c;编译后生成的.class文件是由字节码组成的平台无关、面向JVM的文…

【美团】Java后端一面复盘|网络+线程+MySQL+Redis+设计模式+手撕算法

&#x1f4cd; 面试公司&#xff1a;美团 &#x1f3af; 面试岗位&#xff1a;Java后端开发工程师 &#x1f4de; 面试形式&#xff1a;电话面试 &#x1f552; 面试时长&#xff1a;约 50 分钟 &#x1f501; 面试轮次&#xff1a;第一轮技术面 ✨ 面试整体节奏&#xff1a; …