百科上得描述,Elasticsearch是一個基于Lucene的搜索服務(wù)器。它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web接口。Elastic" />

国产成人精品无码青草_亚洲国产美女精品久久久久∴_欧美人与鲁交大毛片免费_国产果冻豆传媒麻婆精东

15158846557 在線咨詢 在線咨詢
15158846557 在線咨詢
所在位置: 首頁 > 營銷資訊 > 網(wǎng)站運(yùn)營 > 利用Elasticsearch 的java 客戶端為網(wǎng)站開發(fā)一個搜索服務(wù)

利用Elasticsearch 的java 客戶端為網(wǎng)站開發(fā)一個搜索服務(wù)

時間:2023-05-30 10:15:01 | 來源:網(wǎng)站運(yùn)營

時間:2023-05-30 10:15:01 來源:網(wǎng)站運(yùn)營

利用Elasticsearch 的java 客戶端為網(wǎng)站開發(fā)一個搜索服務(wù):Elasticsearch 是什么

百科上得描述,Elasticsearch是一個基于Lucene的搜索服務(wù)器。它提供了一個分布式多用戶能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java語言開發(fā)的,并作為Apache許可條款下的開放源碼發(fā)布,是一種流行的企業(yè)級搜索引擎。

安裝 Elasticsearch

在使用之前,我們需要安裝Elasticsearch 服務(wù),這里就不介紹如何去安裝了,可以參考一些地址進(jìn)行安裝,本次測試使用得是 elasticsearch-6.2.3

https://www.elastic.co/guide/index.html

引入ES java client端包,注意客戶包要和ES服務(wù)的版本一致,客戶端也使用 6.2.3

<elasticsearch.version>6.2.3</elasticsearch.version><!--引入ES相關(guān)的包 --> <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>創(chuàng)建一個ES client 類

創(chuàng)建一個Java類,用去獲取一個連接到 ES服務(wù)的客戶端對象,通過這個對象可以操作ES的數(shù)據(jù)了,比如網(wǎng)ES添加數(shù)據(jù),搜索數(shù)據(jù)。

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服務(wù)端進(jìn)行通信,將 192.168.0.1 替換成自己的 ES 服務(wù)地址。

創(chuàng)建一個保存類

創(chuàng)建一個Java類,提供將內(nèi)容保存到ES服務(wù)的方法

public class SaveClient { /** * 數(shù)據(jù)保存到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(); } }}關(guān)鍵代碼:EsClient.getClient().index(indexRequest);

意思是通過 EsClient.getClient() 獲取一個client , 調(diào)用 index方法,傳遞一個IndexRequest,將內(nèi)容保存到ES

"posts" : 索引標(biāo)識

"doc":索引類型

id:文檔ID,類似關(guān)系表的標(biāo)識列

讀取內(nèi)容寫入到ES

本例做的是將本地的makedown 文本內(nèi)容,替換掉特殊標(biāo)簽之后,保存到ES中,以下是一個寫入的工具類

import java.io.File;import java.util.regex.Pattern;public class SaveContentTest { public static void main(String[] args) { //調(diào)用保存方法 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); //數(shù)據(jù)添加ES SaveClient.save(text,fileName,id); }}創(chuàng)建一個搜索工具類

創(chuàng)建一個搜索工具類,根據(jù)關(guān)鍵字,返回匹配到的內(nèi)容,本例是返回匹配到的前5行,并且將關(guān)鍵字符標(biāo)黃,用于突出顯示;匹配的一行內(nèi)容可能會過長,這里截取了關(guān)鍵字位置的前100個字符和后100個字符

@Componentpublic class SearchClient { public String doSearch(String s) { //構(gòu)建一個搜索對象 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; } }}構(gòu)建一個SearchController 提高h(yuǎn)ttp請求

在SearchController 中調(diào)用搜索方法,返回內(nèi)容給前端,核心代碼就算完成了

@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=控件

返回匹配到的內(nèi)容



關(guān)鍵詞:服務(wù),利用

74
73
25
news

版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。

為了最佳展示效果,本站不支持IE9及以下版本的瀏覽器,建議您使用谷歌Chrome瀏覽器。 點(diǎn)擊下載Chrome瀏覽器
關(guān)閉