时间:2023-05-30 10:15:01 | 来源:网站运营
时间:2023-05-30 10:15:01 来源:网站运营
利用Elasticsearch 的java 客户端为网站开发一个搜索服务:Elasticsearch 是什么<elasticsearch.version>6.2.3</elasticsearch.version><!--引入ES相关的包 --> <dependency> <groupId>org.elasticsearch</groupId> <artifactId>elasticsearch</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.elasticsearch.distribution.integ-test-zip</groupId> <artifactId>elasticsearch</artifactId> <type>zip</type> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.plugin</groupId> <artifactId>transport-netty4-client</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>${elasticsearch.version}</version> <exclusions> <exclusion> <artifactId>commons-logging</artifactId> <groupId>commons-logging</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-client</artifactId> <version>${elasticsearch.version}</version> </dependency>
创建一个ES client 类public class EsClient { static RestHighLevelClient client; public static synchronized void initClint(){ if(client==null){ client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.0.1", 9200, "http") )); } } public static RestHighLevelClient getClient(){ initClint(); return client; } public void closeClient(String s) { try { client.close(); } catch (IOException e) { e.printStackTrace(); } }}
这边使用的 RestHighLevelClient 客户端和ES服务端进行通信,将 192.168.0.1
替换成自己的 ES 服务地址。public class SaveClient { /** * 数据保存到es * @param text * @param fileName * @param id */ public static void save(String text,String fileName,String id){ Map<String, Object> jsonMap = new HashMap<>(); jsonMap.put("url", "http://127.0.0.1:9123/mdwiki.html#!"+fileName); jsonMap.put("postDate", new Date()); jsonMap.put("message", text); IndexRequest indexRequest = new IndexRequest("posts", "doc",id).source(jsonMap); try { EsClient.getClient().index(indexRequest); } catch (IOException e) { e.printStackTrace(); } }}
关键代码:EsClient.getClient().index(indexRequest); import java.io.File;import java.util.regex.Pattern;public class SaveContentTest { public static void main(String[] args) { //调用保存方法 setConent(); } /** * 读取目录下的makedown文件 */ public static void setConent(){ String pendingPath="E://mdwiki//mdwiki-0.6.2//"; File file = new File(pendingPath); File[] fileList = file.listFiles(); for(File fileOjb:fileList){ if (fileOjb.isFile()) { String name= fileOjb.getName(); String names[] = name.split("//."); if(names.length==2 && "md".equals( names[1].toLowerCase() ) ){ putEs(pendingPath,name,MD5Util.md5low(name)); } } } } /** * 将makedown文件通过正则替换掉特殊字符,然后保存到ES * @param pendingPath * @param fileName * @param id */ public static void putEs(String pendingPath,String fileName,String id){ ReadFileUtil readFileUtil=new ReadFileUtil(); String text= readFileUtil.read(pendingPath, fileName, new ReadFileUtil.FixLine() { @Override public String fixLine(String buff) { String jsonString=Pattern.compile(".*!//[.*?//]//(.*?//).*").matcher(buff).replaceAll(""); jsonString=Pattern.compile(".*//<iframe(.*?)><///iframe//>.*").matcher(jsonString).replaceAll(""); jsonString=jsonString.replaceAll("-",""); jsonString=jsonString.replaceAll("//*",""); jsonString=jsonString.replaceAll("`",""); jsonString=jsonString.replaceAll(">",""); jsonString=jsonString.replaceAll("=",""); return jsonString; } }); System.out.println(text); //数据添加ES SaveClient.save(text,fileName,id); }}
创建一个搜索工具类@Componentpublic class SearchClient { public String doSearch(String s) { //构建一个搜索对象 SearchRequest searchRequest = new SearchRequest("posts"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchPhraseQuery("message", s)); sourceBuilder.from(0); sourceBuilder.size(5); sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS)); searchRequest.source(sourceBuilder); SearchResponse searchResponse = null; try { searchResponse = EsClient.getClient().search(searchRequest); } catch (IOException e) { e.printStackTrace(); } StringBuilder bu=new StringBuilder(); bu.append("<div>"); SearchHits hits = searchResponse.getHits(); for (SearchHit hit : hits.getHits()) { String text= hit.getSourceAsString(); HtmlBean htmlBean= JsonUtils.convert2bean(text,HtmlBean.class); text=htmlBean.getMessage(); int indexOf= text.indexOf(s); int lastOf= text.lastIndexOf(s); int startIndex=(indexOf-100) < 0 ? 0 : indexOf-100 ; int lastIndex=(lastOf +100) > text.length() ? text.length() : lastOf+100 ; text=text.substring( startIndex,lastIndex); text= text.replaceAll(s,"<span style=/"background: yellow;/"> "+s+"</span>"); bu.append("<a href='"); bu.append(htmlBean.getUrl()); bu.append("'>"); bu.append(text); bu.append("</a>"); bu.append("</br>"); } bu.append("</div>"); return bu.toString(); } static class HtmlBean { private String postDate; private String message; private String url; public String getPostDate() { return postDate; } public void setPostDate(String postDate) { this.postDate = postDate; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }}
构建一个SearchController 提高http请求@Controllerpublic class SearchController { private static final Logger logger= LoggerFactory.getLogger(SearchController.class); @Autowired SearchClient searchClientStandardServiceImpl; @ResponseBody @RequestMapping(value = "/search") public String search(String text){ return searchClientStandardServiceImpl.doSearch(text); }}
输入 http://127.0.0.1:9300/sync/search?text=控件关键词:服务,利用