SpringBoot整合7.6.x版本ES入門學(xué)習(xí)

1.Elaticsearch概述

1.1Elaticsearch是什么

The Elastic Stack, 包括 Elasticsearch、Kibana、Beats 和 Logstash(也稱為 ELK Stack)。能夠安全可靠地獲取任何來源著角、任何格式的數(shù)據(jù),然后實時地對數(shù)據(jù)進行搜索、分析和可視化捡硅。Elaticsearch,簡稱為ES盗棵, ES是一個開源的高擴展的分布式全文搜索引擎壮韭,是整個Elastic Stack技術(shù)棧的核心北发。它可以近乎實時的存儲、檢索數(shù)據(jù)喷屋;本身擴展性很好琳拨,可以擴展到上百臺服務(wù)器,處理PB級別的數(shù)據(jù)屯曹。

1.2Elaticsearch And Solr

ElasticsearchSolr,這兩款都是基于Lucene搭建的狱庇,可以獨立部署啟動的搜索引擎服務(wù)軟件。由于內(nèi)核相同是牢,所以兩者除了服務(wù)器安裝僵井、部署、管理驳棱、集群以外批什,對于數(shù)據(jù)的操作 修改、添加社搅、保存驻债、查詢等等都十分類似。

1.3Elaticsearch的應(yīng)用案例

GitHub形葬、維基百科合呐、SoundCloud、百度笙以、新浪淌实、阿里、Stack Overflow

2.相關(guān)軟件的下載

2.1Elaticsearch7.6.x版本下載

在elasticsearch-7.6.1/config/elasticsearch.yml配置文件加上xpack.ml.enabled: false猖腕;則可進入到bin目錄拆祈,./elasticsearch啟動Elaticsearch。


image-20210409190038357.png

新開一個黑窗口輸入:curl localhost:9200倘感,收到如下信息說明啟動成功放坏。


image-20210410092548897.png

默認(rèn)只允許本機訪問,如果想遠(yuǎn)程訪問可以修改config/elasticsearch.yml老玛,去掉network.host的注釋淤年,將它的值改成0.0.0.0,然后重新啟動Elasticsearch 蜡豹。

2.2Head插件

打開谷歌瀏覽器搜索谷歌商城麸粮,打開搜索elasticsearch head即可看見如下:


image-20210410093127297.png

點擊添加至chrome,即可在擴展程序找到打開elasticsearch head余素。

image-20210410093331194.png

2.3 Kibana7.6.1

打開kibana.yml配置文件豹休,將 i18n.locale: "en"-->i18n.locale: "zh-CN",可以將kibana漢化桨吊。進入bin目錄威根,./kibana啟動凤巨。

2.4 ik分詞器

將下載好的ik文件放到elasticsearch的plugins文件夾下面,重啟elasticsearch即可生效洛搀。


image-20210410172811254.png

3.springboot-2.2.5整合ES-7.6.1

3.1依賴

<properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
<!--&lt;!&ndash;        自定義es版本依賴敢茁,保證和本地一致&ndash;&gt;-->
        <elasticsearch.version>7.6.1</elasticsearch.version>
    </properties>

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

3.2配置ES連接

package com.sanzhu.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")
                )
        );
    }

}

3.3索引的CRUD

//1.測試索引的創(chuàng)建
 @Test
 public void test01() throws IOException {
 //1.創(chuàng)建索引請求
 CreateIndexRequest request = new CreateIndexRequest("sanzhu_index");
 //2.執(zhí)行創(chuàng)建請求
 CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
 System.out.println("response.index() = " + response.index());
    }

//2.獲取索引
 @Test
 public void text02() throws IOException {
 //1.獲取索引請求
 GetIndexRequest request = new GetIndexRequest("sanzhu_index");
 boolean exists = client.indices().exists(request,RequestOptions.DEFAULT);
 System.out.println("exists = " + exists);
    }
//3.刪除索引
 @Test
 public void test03() throws IOException {
 DeleteIndexRequest request = new DeleteIndexRequest("sanzhu_index");
 AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);
 System.out.println("response.isAcknowledged() = " + response.isAcknowledged());
    }

3.4文檔的CRUD

//4.添加文檔
 @Test
 public void text04() throws IOException {
 User user = new User();
 user.setName("陳輝");
 user.setAge(18);
 IndexRequest request = new IndexRequest("sanzhu_index");
 // 添加數(shù)據(jù)的規(guī)則  PUT /sanzhu_index/_doc/1
 request.id("1");
 request.timeout(TimeValue.timeValueSeconds(1));
 request.timeout("1s");
 //添加數(shù)據(jù)進索引庫
 request.source(JSON.toJSONString(user), XContentType.JSON);
 IndexResponse response = client.index(request, RequestOptions.DEFAULT);
 System.out.println("response.status() = " + response.status());
 System.out.println("response.toString() = " + response.toString());
    }


//5.判斷文檔是否存在
 @Test
 public void test05() throws IOException {
 GetRequest getRequest = new GetRequest("sanzhu_index", "1");
 getRequest.fetchSourceContext();
 boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
 System.out.println("exists = " + exists);
    }


//6.獲取文檔信息
 @Test
 public void test06() throws IOException {
 GetRequest getRequest = new GetRequest("sanzhu_index", "1");
 GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
 System.out.println("documentFields.getSourceAsString() = " + documentFields.getSourceAsString());
 System.out.println("documentFields = " + documentFields);
    }


//7.更新文檔信息
 @Test
 public void test07() throws IOException {
 UpdateRequest updateRequest = new UpdateRequest("sanzhu_index", "1");
 updateRequest.timeout("1s");
 User user = new User();
 user.setName("張家輝");
 user.setAge(1918);
 updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
 UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
 System.out.println("update.status() = " + update.status());
 System.out.println("update.toString() = " + update.toString());
    }


//8.刪除文檔請求
 @Test
 public void test08() throws IOException {
 DeleteRequest deleteRequest = new DeleteRequest("sanzhu_index", "1");
 deleteRequest.timeout();
 DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
 System.out.println("response.status() = " + response.status());
 System.out.println("response.toString() = " + response.toString());
    }


//9.批量插入數(shù)據(jù)
 @Test
 public void test09() throws IOException {
 BulkRequest bulkRequest = new BulkRequest();
 bulkRequest.timeout("10s");

 ArrayList<User> users = new ArrayList<>();
 for (int i = 0; i < 10; i++) {
 User user = new User();
 user.setName("張家輝"+i+"號");
 user.setAge(i+20);
 users.add(user);
        }

 for (int i = 0; i < users.size(); i++) {
 bulkRequest.add(
 new IndexRequest("sanzhu_index").id("" + (i + 2))
                            .source(JSON.toJSONString(users.get(i)), XContentType.JSON)
            );
        }
 
 BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
 System.out.println("responses.status() = " + responses.status());
 System.out.println("responses.hasFailures() = " + responses.hasFailures());
    }

//單條件查詢
 @Test
 public void test14() throws IOException {
 SearchRequest searchRequest = new SearchRequest("sanzhu_index");
 SearchSourceBuilder builder = new SearchSourceBuilder();
 builder.timeout(TimeValue.timeValueSeconds(2));
 //過濾字段
 builder.fetchSource("name","age");
 //分頁
 builder.from(0);
 builder.size(3);
 //排序
 builder.sort("_id", SortOrder.DESC);
 //條件查詢
 TermQueryBuilder query = QueryBuilders.termQuery("age", "99");
 builder.query(query);
 searchRequest.source(builder);
 SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
 SearchHit[] hits = response.getHits().getHits();
 for (SearchHit hit : hits) {
 System.out.println("hit = " + hit);
 System.out.println("hit = " + hit.getSourceAsMap());
        }
    }

 //  多條件查詢
 @Test
 public void test15() throws IOException{
 SearchRequest searchRequest = new SearchRequest("sanzhu_index");
 SearchSourceBuilder builder = new SearchSourceBuilder();
 builder.timeout(TimeValue.timeValueSeconds(2));
 //多條件查詢器
 BoolQueryBuilder query = QueryBuilders.boolQuery();
 //必須滿足
 query.must(QueryBuilders.matchQuery("name","peter"));
 //必須不滿足
 query.mustNot(QueryBuilders.matchQuery("age","999"));
 //或者  should查詢和must查詢一起用會無效
//        query.should(QueryBuilders.matchQuery("age","777"));
//        query.should(QueryBuilders.matchQuery("age","888"));
 builder.query(query);
 searchRequest.source(builder);
 SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
 SearchHit[] hits = response.getHits().getHits();
 for (SearchHit hit : hits) {
 System.out.println("hit = " + hit);
        }
    }

//范圍查詢
 @Test
 public void test16() throws Exception{
 SearchRequest searchRequest = new SearchRequest("sanzhu_index");
 SearchSourceBuilder builder = new SearchSourceBuilder();
 RangeQueryBuilder queryBuilder = QueryBuilders.rangeQuery("age").gte(200).lte(666);
 builder.query(queryBuilder);
 searchRequest.source(builder);
 SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
 SearchHit[] hits = response.getHits().getHits();
 for (SearchHit hit : hits) {
 System.out.println("hit = " + hit);
        }
    }

//高亮查詢
@Test
 public void test13() throws IOException {
 SearchRequest searchRequest = new SearchRequest("sanzhu_index");
 SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
 TermQueryBuilder query = QueryBuilders.termQuery("name", "peter");
 searchSourceBuilder.query(query);
 searchSourceBuilder.timeout(TimeValue.timeValueSeconds(1));
 searchSourceBuilder.from(1);
 searchSourceBuilder.size(5);
 searchRequest.source(searchSourceBuilder);
 //高亮
 HighlightBuilder highlightBuilder = new HighlightBuilder();
 highlightBuilder.field("name");
 highlightBuilder.preTags("<span style='color:red'>");
 highlightBuilder.postTags("</span>");
 highlightBuilder.requireFieldMatch(false);//關(guān)閉多個高亮,只第一個高亮
 searchSourceBuilder.highlighter(highlightBuilder);

 SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
 SearchHit[] hits = response.getHits().getHits();
 System.out.println("hits.length = " + hits.length);
 for (SearchHit hit : hits) {
 //獲取高亮字段
 Map<String, HighlightField> map = hit.getHighlightFields();
 HighlightField name = map.get("name");
 Map<String, Object> map1 = hit.getSourceAsMap();
 //用高亮的字段替換原來的字段
 if (name!=null){
 Text[] fragments = name.fragments();//獲取高亮內(nèi)容
 String n_name = "";
 for (Text fragment : fragments) {
 n_name+=fragment;
                }
 map1.put("name",n_name);
            }
 System.out.println("map1 = " + map1);
        }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末留美,一起剝皮案震驚了整個濱河市彰檬,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌谎砾,老刑警劉巖逢倍,帶你破解...
    沈念sama閱讀 212,454評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異景图,居然都是意外死亡较雕,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,553評論 3 385
  • 文/潘曉璐 我一進店門挚币,熙熙樓的掌柜王于貴愁眉苦臉地迎上來亮蒋,“玉大人,你說我怎么就攤上這事妆毕∩骶粒” “怎么了?”我有些...
    開封第一講書人閱讀 157,921評論 0 348
  • 文/不壞的土叔 我叫張陵笛粘,是天一觀的道長趁怔。 經(jīng)常有香客問我,道長薪前,這世上最難降的妖魔是什么痕钢? 我笑而不...
    開封第一講書人閱讀 56,648評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮序六,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘蚤吹。我一直安慰自己例诀,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,770評論 6 386
  • 文/花漫 我一把揭開白布裁着。 她就那樣靜靜地躺著繁涂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪二驰。 梳的紋絲不亂的頭發(fā)上扔罪,一...
    開封第一講書人閱讀 49,950評論 1 291
  • 那天,我揣著相機與錄音桶雀,去河邊找鬼矿酵。 笑死唬复,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的全肮。 我是一名探鬼主播敞咧,決...
    沈念sama閱讀 39,090評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼辜腺!你這毒婦竟也來了休建?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,817評論 0 268
  • 序言:老撾萬榮一對情侶失蹤评疗,失蹤者是張志新(化名)和其女友劉穎测砂,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體百匆,經(jīng)...
    沈念sama閱讀 44,275評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡砌些,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,592評論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了胧华。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片寄症。...
    茶點故事閱讀 38,724評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖矩动,靈堂內(nèi)的尸體忽然破棺而出有巧,到底是詐尸還是另有隱情,我是刑警寧澤悲没,帶...
    沈念sama閱讀 34,409評論 4 333
  • 正文 年R本政府宣布篮迎,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏思犁。R本人自食惡果不足惜躯泰,卻給世界環(huán)境...
    茶點故事閱讀 40,052評論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望岂傲。 院中可真熱鬧,春花似錦子檀、人聲如沸镊掖。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,815評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽亩进。三九已至,卻和暖如春缩歪,著一層夾襖步出監(jiān)牢的瞬間归薛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,043評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留主籍,地道東北人习贫。 一個月前我還...
    沈念sama閱讀 46,503評論 2 361
  • 正文 我出身青樓,卻偏偏與公主長得像崇猫,于是被迫代替她去往敵國和親沈条。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,627評論 2 350

推薦閱讀更多精彩內(nèi)容