国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

ES的安裝和RestClient的操作

這篇具有很好參考價(jià)值的文章主要介紹了ES的安裝和RestClient的操作。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

目錄

初識(shí)elasticsearch

什么是elasticsearch

elasticsearch的發(fā)展

Lucene的優(yōu)缺點(diǎn)

elasticsearch的優(yōu)勢

倒排索引?

es與mysql的概念對(duì)比

文檔

索引

概念對(duì)比

架構(gòu)

安裝es

安裝kibana

安裝ik分詞器?

分詞器

安裝ik分詞器

ik分詞器的拓展和停用詞典

操作索引庫

mapping屬性

創(chuàng)建索引庫

查詢、刪除、修改索引庫

文檔操作

新增查詢刪除文檔

修改文檔

方法一:全量修改

方法二:增量修改

RestClient的操作

什么是RestClient

hotel數(shù)據(jù)結(jié)構(gòu)分析

索引庫操作

初始化JavaRestClient

創(chuàng)建索引庫

刪除索引庫

判斷索引庫是否存在

文檔操作

初始化JavaRestClient

添加文檔

查詢文檔

修改文檔

刪除文檔

批量導(dǎo)入文檔


什么是elasticsearch?
1、一個(gè)開源的分布式搜索引擎,可以用來實(shí)現(xiàn)搜索、日志統(tǒng)計(jì)、分析、系統(tǒng)監(jiān)控等功能
什么是elastic stack (ELK) ?
2、是以elasticsearch為核心的技術(shù)棧,包括beats、Logstash、kibana、elasticsearch
什么是Lucene?
3、是Apache的開源搜索引擎類庫,提供了搜索引擎的核心API


什么是文檔和詞條?

1、每一條數(shù)據(jù)就是一個(gè)文檔
2、對(duì)文檔中的內(nèi)容分詞,得到的詞語就是詞條
什么是正向索引?
1、基于文檔id創(chuàng)建索引。查詢?cè)~條時(shí)必須先找到文檔,而后判斷是否包含詞條
什么是倒排索引?
1、對(duì)文檔內(nèi)容分詞,對(duì)詞條創(chuàng)建索引,并記錄詞條所在文檔的信息。查詢時(shí)先根據(jù)詞條查詢到文檔id,而后獲取到文檔


文檔:一條數(shù)據(jù)就是一個(gè)文檔,es中是Json格式
字段:Json文檔中的字段
索引:同類型文檔的集合
映射:索引中文檔的約束,比如字段名稱、類型
elasticsearch與數(shù)據(jù)庫的關(guān)系:
1、數(shù)據(jù)庫負(fù)責(zé)事務(wù)類型操作
2、elasticsearch負(fù)責(zé)海量數(shù)據(jù)的搜索、分析、計(jì)算


分詞器的作用是什么?
1、創(chuàng)建倒排索引時(shí)對(duì)文檔分詞
2、用戶搜索時(shí),對(duì)輸入的內(nèi)容分詞
IK分詞器有幾種模式?
1、ik_smart:智能切分,粗粒度

2、ik_max_word:最細(xì)切分,細(xì)粒度
IK分詞器如何拓展詞條?如何停用詞條?
1、利用config目錄的lkAnalyzer.cfg.xml文件添加拓展詞典和停用詞典

2、在詞典中添加拓展詞條或者停用詞條


mapping常見屬性有哪些?

1、type:數(shù)據(jù)類型
2、index:是否索引

3、analyzer:分詞器

4、properties:子字段

type常見的有哪些?

1、字符串:text、keyword
2、數(shù)字:long、integer、short、 byte、double、float

3、布爾:boolean
4、日期:date
5、對(duì)象:object


索引庫操作有哪些?
1、創(chuàng)建索引庫:PUT/索引庫名
2、查詢索引庫:GET/索引庫名
3、刪除索引庫:DELETE/索引庫名
4、添加字段:PUT/索引庫名/_mapping


文檔操作有哪些?
1、創(chuàng)建文檔:POST/索引庫名/_doc/文檔id { json文檔}
2、查詢文檔:GET/索引庫名/_doc/文檔id
3、刪除文檔:DELETE/索引庫名/_doc/文檔id
4、修改文檔:
全量修改:PUT/索引庫名/_doc/文檔id { json文檔}
增量修改:POST/索引庫名/_update/文檔id { "doc":{字段}}


索引庫操作的基本步驟:
1、初始化RestHighLevelClient
2、創(chuàng)建XxxIndexRequest。XXX是CREATE、Get、Delete
3、準(zhǔn)備DSL ( CREATE時(shí)需要)
4、發(fā)送請(qǐng)求。調(diào)用RestHighLevelClient#tindices().xxx()方法,xxx是create、exists、delete


文檔操作的基本步驟:
1、初始化RestHighLevelClient
2、創(chuàng)建XxxRequest。XXX是Index、Get、Update、Delete
3、準(zhǔn)備參數(shù)((Index和Update時(shí)需要)
4、發(fā)送請(qǐng)求。調(diào)用RestHighLevelClient#t.xxx()方法,xxx是index、get、update、delete
5、解析結(jié)果(Get時(shí)需要)

初識(shí)elasticsearch

什么是elasticsearch

elasticsearch是一款非常強(qiáng)大的開源搜索引擎,可以幫助我們從海量數(shù)據(jù)中快速找到需要的內(nèi)容。

elasticsearch結(jié)合kibana、Logstash、Beats,也就是elastic stack (ELK)。被廣泛應(yīng)用在日志數(shù)據(jù)分析、實(shí)時(shí)監(jiān)控等領(lǐng)域。
elasticsearch是elastic stack的核心,負(fù)責(zé)存儲(chǔ)、搜索、分析數(shù)據(jù)。

elasticsearch的發(fā)展

Lucene的優(yōu)缺點(diǎn)

Lucene的優(yōu)勢:

1、易擴(kuò)展
2、高性能(基于倒排索引)

Lucene的缺點(diǎn):
1、只限于Java語言開發(fā)

2、學(xué)習(xí)曲線陡峭
3、不支持水平擴(kuò)展?

elasticsearch的優(yōu)勢

相比與lucene, elasticsearch具備下列優(yōu)勢:

1、支持分布式,可水平擴(kuò)展
2、提供Restful接口,可被任何語言調(diào)用

倒排索引?

elasticsearch采用倒排索引:
1、文檔(document):每條數(shù)據(jù)就是一個(gè)文檔

2、詞條(term):文檔按照語義分成的詞語

es與mysql的概念對(duì)比

文檔

1、elasticsearch是面向文檔存儲(chǔ)的,可以是數(shù)據(jù)庫中的一條商品數(shù)據(jù),一個(gè)訂單信息。

2、文檔數(shù)據(jù)會(huì)被序列化為json格式后存儲(chǔ)在elasticsearch中。?

索引

索引 ( index):相同類型的文檔的集合
映射(mapping):索引中文檔的字段約束信息,類似表的結(jié)構(gòu)約束

概念對(duì)比

MySQL Elasticsearch 說明
Table Index 索引(index),就是文檔的集合,類似數(shù)據(jù)庫的表(table)
Row Document 文檔(Document),就是一條條的數(shù)據(jù),類似數(shù)據(jù)庫中的行(ROW),文檔都是JSON格式
Column Field 字段(Field),就是JSON文檔中的字段,類似數(shù)據(jù)庫中的列(Column)
Schema Mapping Mapping(映射)是索引中文檔的約束,例如字段類型約束。類似數(shù)據(jù)庫的表結(jié)構(gòu)(Schema)
SQL DSL DSL是elasticsearch提供的JSON風(fēng)格的請(qǐng)求語句,用來操作elasticsearch,實(shí)現(xiàn)CRUD

架構(gòu)

Mysql:擅長事務(wù)類型操作,可以確保數(shù)據(jù)的安全和一致性

Elasticsearch:擅長海量數(shù)據(jù)的搜索、分析、計(jì)算

安裝es

創(chuàng)建網(wǎng)絡(luò):es-net是自己取的名字,隨便取

docker network create es-net

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

加載鏡像:使用提供的es.tar,拖到虛擬機(jī)的tmp目錄下??

es.tarhttps://pan.baidu.com/s/13Z74D-liQaDL0_tM-Rl7Rg?pwd=47qm運(yùn)行加載命令:

docker load -i es.tar

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

運(yùn)行docker命令:

docker run -d \
?? ?--name es \
? ? -e "ES_JAVA_OPTS=-Xms512m -Xmx512m" \
? ? -e "discovery.type=single-node" \
? ? -v es-data:/usr/share/elasticsearch/data \
? ? -v es-plugins:/usr/share/elasticsearch/plugins \
? ? --privileged \
? ? --network es-net \
? ? -p 9200:9200 \
? ? -p 9300:9300 \
elasticsearch:7.12.1

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

訪問網(wǎng)頁:虛擬機(jī)ip和9200端口。成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

安裝kibana

加載鏡像:使用提供的es.tar,拖到虛擬機(jī)的tmp目錄下??

kibanahttps://pan.baidu.com/s/1N3NiLRxLzX42jMxkK9ackQ?pwd=lh2y運(yùn)行docker命令

docker run -d \
--name kibana \
-e ELASTICSEARCH_HOSTS=http://es:9200 \
--network=es-net \
-p 5601:5601 ?\
kibana:7.12.1

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

訪問網(wǎng)頁:虛擬機(jī)ip和5601端口。成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

點(diǎn)擊主頁的Explore on my own后,打開Dev Tools

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

模擬一次請(qǐng)求:可以看到右邊的數(shù)據(jù)和端口9200的數(shù)據(jù)一模一樣?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

安裝ik分詞器?

分詞器

es在創(chuàng)建倒排索引時(shí)需要對(duì)文檔分詞;在搜索時(shí),需要對(duì)用戶輸入內(nèi)容分詞。但默認(rèn)的分詞規(guī)則對(duì)中文處理并不友好。

語法說明:
POST:請(qǐng)求方式
/_analyze:請(qǐng)求路徑

請(qǐng)求參數(shù),json風(fēng)格:analyzer:分詞器類型。text:要分詞的內(nèi)容?

我們可以看到:右邊的數(shù)據(jù)分詞并不友好,比如:世界本應(yīng)該是一起的,它卻分開了

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

安裝ik分詞器

查看es-plugins數(shù)據(jù)卷所在的位置

docker volume inspect es-plugins?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

把ik文件夾放到該路徑:Mountpoint就是要的位置

ik文件夾https://pan.baidu.com/s/1EIkGJDvVjcGx06hDUo34Eg?pwd=dads重啟es

docker restart es

測試

ik_smart:最少切分

ik_max_word:最細(xì)切分 ?

ik_smart:從最多字開始判斷是否切分,若切分,則不會(huì)再繼續(xù)判斷已被切分的詞是否繼續(xù)切分?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

ik_max_word:會(huì)判斷每個(gè)詞是否能再繼續(xù)分?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

ik分詞器的拓展和停用詞典

修改一個(gè)ik分詞器目錄中的config目錄中的lkAnalyzer.cfg.xml文件

在第一個(gè)箭頭這行,添加ext.dic:這是要用來拓展詞典的文件,要在lkAnalyzer.cfg.xml所在的同級(jí)目錄下創(chuàng)建出來。

在第二個(gè)箭頭這行,添加stopword.dic:這是要用來停用詞典的文件,在lkAnalyzer.cfg.xml所在的同級(jí)目錄已經(jīng)創(chuàng)建好了,不需要再創(chuàng)建。

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

在ext.dic添加要拓展的詞典

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

在stopword.dic添加要停用的詞典

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

重啟es:這次重啟后,需要幾十秒的時(shí)間才能訪問網(wǎng)站,否則網(wǎng)站會(huì)報(bào)錯(cuò)

docker restart es?

再次訪問網(wǎng)站,可以看到這次測試“奧利給”并沒有被分開,并且“的”字并沒有出現(xiàn)在右邊。

是因?yàn)椤皧W利給”被寫進(jìn)了ext.dic,?“的”被寫進(jìn)了stopword.dic

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

操作索引庫

mapping屬性

mapping是對(duì)索引庫中文檔的約束,常見的mapping屬性包括:

1、type:字段數(shù)據(jù)類型,常見的簡單類型有:
1.1、字符串:text(可分詞的文本)、keyword(精確值,例如:品牌、國家、ip地址)

1.2、數(shù)值:long、integer、short、byte、double、float

1.3、布爾:boolean
1.4、日期:date

1.5、對(duì)象:object

2、index:是否創(chuàng)建索引,默認(rèn)為true

3、analyzer:使用哪種分詞器
4、properties:該字段的子字段

創(chuàng)建索引庫

這里創(chuàng)建了一個(gè)名叫heima的索引庫,mappings代表它是做映射的,properties代表里面是具體的字段,type代表該字段的數(shù)據(jù)類型,analyzer代表該字段的分詞器,index代表該字段是否創(chuàng)建索引

PUT /heima
{
? "mappings": {
? ? "properties": {
? ? ? "info":{
? ? ? ? "type": "text",
? ? ? ? "analyzer": "ik_smart"
? ? ? },
? ? ? "email": {
? ? ? ? "type": "keyword",
? ? ? ? "index": false
? ? ? },
? ? ? "name": {
? ? ? ? "type": "object",
? ? ? ? "properties": {
? ? ? ? ? "firstName": {
? ? ? ? ? ? "type": "keyword"
? ? ? ? ? },
? ? ? ? ? "lastName": {
? ? ? ? ? ? "type": "keyword"
? ? ? ? ? }
? ? ? ? }
? ? ? }
? ? }
? }
}

運(yùn)行該DSL語句后,右邊會(huì)出現(xiàn)創(chuàng)建的索引庫名字,代表創(chuàng)建成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

查詢、刪除、修改索引庫

查看索引庫語法

GET /索引庫名稱?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

刪除索引庫語法?

DELETE /索引庫名

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

索引庫和mapping一旦創(chuàng)建無法修改,但是可以添加新的字段

PUT /索引庫名稱/_mapping
{
? "properties": {
? ? "新字段名": {
? ? }
? }
}

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

文檔操作

新增查詢刪除文檔

新增文檔語法

POST /索引庫名/_doc/文檔id
{
? "字段1": "值1",
? "字段2": "值2",
? "字段3": {
? ? "子屬性1": "值3",
? ? "子屬性2": "值4"
? }
}

新增文檔,右邊的數(shù)據(jù)result為created。成功?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

查詢文檔語法

GET /索引庫名/_doc/文檔id?

查詢文檔,右邊會(huì)出現(xiàn)文檔的數(shù)據(jù)。成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

刪除文檔語法

DELETE /索引庫名/_doc/文檔id

刪除文檔,右邊數(shù)據(jù)result為deleted,成功?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

修改文檔

方法一:全量修改

會(huì)刪除舊文檔,添加新文檔

PUT /索引庫名/_doc/文檔id
{
? "字段1": "值1",
? "字段2": "值2"
}?

當(dāng)文檔存在時(shí):修改后,右邊的數(shù)據(jù)result為updated。修改成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

當(dāng)文檔不存在時(shí):修改變成了創(chuàng)建。

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

方法二:增量修改

修改指定的字段,注意只能寫指定的字段,而不是把所有字段都寫上

POST /索引庫名/_update/文檔id
{
? "doc": {
? ? "字段1": "值1"
? }
}?

修改后,右邊的result為updated。修改成功?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

RestClient的操作

什么是RestClient

ES官方提供了各種不同語言的客戶端,用來操作ES。這些客戶端的本質(zhì)就是組裝DSL語句,通過http請(qǐng)求發(fā)送給ES。

下載提供的資料

hotel的demo和sqlhttps://pan.baidu.com/s/1uxl7PzshHu09PXsd9zDWbA?pwd=v8bf在本地新建一個(gè)數(shù)據(jù)庫:heima,若使用其他數(shù)據(jù)庫名,記得在demo里修改yml文件?

hotel數(shù)據(jù)結(jié)構(gòu)分析

寫出數(shù)據(jù)庫中該表的DSL語句,但是不要執(zhí)行。我們要使用java來執(zhí)行

PUT /hotel
{
? "mappings": {
? ? "properties": {
? ? ? "id": {
? ? ? ? "type": "keyword"
? ? ? },
? ? ? "name": {
? ? ? ? "type": "text",
? ? ? ? "analyzer": "ik_max_word",
? ? ? ? "copy_to": "all"
? ? ? },
? ? ? "address": {
? ? ? ? "type": "keyword",
? ? ? ? "index": false
? ? ? },
? ? ? "price": {
? ? ? ? "type": "integer"
? ? ? },
? ? ? "score": {
? ? ? ? "type": "integer"
? ? ? },
? ? ? "brand": {
? ? ? ? "type": "keyword",
? ? ? ? "copy_to": "all"
? ? ? },
? ? ? "city": {
? ? ? ? "type": "keyword"
? ? ? },
? ? ? "starName": {
? ? ? ? "type": "keyword"
? ? ? },
? ? ? "business": {
? ? ? ? "type": "keyword",
? ? ? ? "copy_to": "all"
? ? ? },
? ? ? "location": {
? ? ? ? "type": "geo_point"
? ? ? },
? ? ? "pic": {
? ? ? ? "type": "keyword",
? ? ? ? "index": false
? ? ? },
? ? ? "all": {
? ? ? ? "type": "text",
? ? ? ? "analyzer": "ik_max_word"
? ? ? }
? ? }
? }
}?

索引庫操作

初始化JavaRestClient

在hotel.pom文件中引入es的RestHighLevelclient依賴

<!--elasticsearch-->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

因?yàn)镾pringBoot默認(rèn)的ES版本是7.6.2,所以我們需要覆蓋默認(rèn)的ES版本

<properties>
    <java.version>1.8</java.version>
    <elasticsearch.version>7.12.1</elasticsearch.version>
</properties>?
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.10.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.itcast.demo</groupId>
    <artifactId>hotel-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hotel-demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.12.1</elasticsearch.version>
    </properties>
    <dependencies>
        <!--elasticsearch-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
		<!--FastJson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.71</version>
        </dependency>
		<dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

初始化RestHighLevelClient:xxx填虛擬機(jī)ip

RestHighLevelclient client = new RestHighLevelclgent(RestClient.builder(
????????HttpHost.create( "http://xxx.xxx.xxx.xxx:9200")
) );

該代碼我寫成了

@BeforeEach
void setUp() {
    this.client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
    ));
}

@AfterEach
void tearDown() throws IOException {
    this.client.close();
}
package cn.itcast.hotel;

import net.sf.jsqlparser.statement.create.index.CreateIndex;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

public class HotelIndexTest {
    private RestHighLevelClient client;

    @Test
    void testInit() {
        System.out.println(client);
    }


    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

創(chuàng)建索引庫

這個(gè)MAPPING_TEMPLATE的位置是要填寫DSL語句,但因?yàn)樘L,我就把它寫成了常量

@Test
void createHotelIndex() throws IOException {
    //1、創(chuàng)建Request對(duì)象
    CreateIndexRequest request = new CreateIndexRequest("hotel");
    //2、準(zhǔn)備請(qǐng)求的參數(shù),DSL語句
    request.source(MAPPING_TEMPLATE, XContentType.JSON);
    //3、發(fā)送請(qǐng)求
    client.indices().create(request, RequestOptions.DEFAULT);
}?
package cn.itcast.hotel;

import net.sf.jsqlparser.statement.create.index.CreateIndex;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

public class HotelIndexTest {
    private RestHighLevelClient client;

    @Test
    void testInit() {
        System.out.println(client);
    }

    @Test
    void createHotelIndex() throws IOException {
        //1、創(chuàng)建Request對(duì)象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //2、準(zhǔn)備請(qǐng)求的參數(shù),DSL語句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.indices().create(request, RequestOptions.DEFAULT);
    }


    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}
public static final String MAPPING_TEMPLATE = "";
package cn.itcast.hotel.constants;

public class HotelConstants {
    public static final String MAPPING_TEMPLATE = "{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"name\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"address\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"price\": {\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"score\": {\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"brand\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"city\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"starName\": {\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"copy_to\": \"all\"\n" +
            "      },\n" +
            "      \"location\": {\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\": {\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      },\n" +
            "      \"all\": {\n" +
            "        \"type\": \"text\",\n" +
            "        \"analyzer\": \"ik_max_word\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}

運(yùn)行測試代碼,可以看到控制臺(tái)運(yùn)行成功。

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

刪除索引庫

@Test
void testDeleteHotelIndex() throws IOException {
    //1、創(chuàng)建Request對(duì)象
    DeleteIndexRequest request = new DeleteIndexRequest("hotel");
    //2、發(fā)送請(qǐng)求
    client.indices().delete(request, RequestOptions.DEFAULT);
}
package cn.itcast.hotel;

import net.sf.jsqlparser.statement.create.index.CreateIndex;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

public class HotelIndexTest {
    private RestHighLevelClient client;

    @Test
    void testInit() {
        System.out.println(client);
    }

    @Test
    void createHotelIndex() throws IOException {
        //1、創(chuàng)建Request對(duì)象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //2、準(zhǔn)備請(qǐng)求的參數(shù),DSL語句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    void testDeleteHotelIndex() throws IOException {
        //1、創(chuàng)建Request對(duì)象
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        //2、發(fā)送請(qǐng)求
        client.indices().delete(request, RequestOptions.DEFAULT);
    }


    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

?點(diǎn)擊該測試,控制臺(tái)運(yùn)行成功。?

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

判斷索引庫是否存在

@Test
void testExistsHotelIndex() throws IOException {
    //1、創(chuàng)建Request對(duì)象
    GetIndexRequest request = new GetIndexRequest("hotel");
    //2、發(fā)送請(qǐng)求
    boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
    //3、輸出
    System.err.println(exists ? "索引庫存在" : "索引庫不存在");
}
package cn.itcast.hotel;

import net.sf.jsqlparser.statement.create.index.CreateIndex;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

public class HotelIndexTest {
    private RestHighLevelClient client;

    @Test
    void testInit() {
        System.out.println(client);
    }

    @Test
    void createHotelIndex() throws IOException {
        //1、創(chuàng)建Request對(duì)象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        //2、準(zhǔn)備請(qǐng)求的參數(shù),DSL語句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    @Test
    void testDeleteHotelIndex() throws IOException {
        //1、創(chuàng)建Request對(duì)象
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        //2、發(fā)送請(qǐng)求
        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    @Test
    void testExistsHotelIndex() throws IOException {
        //1、創(chuàng)建Request對(duì)象
        GetIndexRequest request = new GetIndexRequest("hotel");
        //2、發(fā)送請(qǐng)求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //3、輸出
        System.err.println(exists ? "索引庫存在" : "索引庫不存在");
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

運(yùn)行該測試,控制臺(tái)運(yùn)行成功,并且打印了“索引庫不存在”,因?yàn)閯倓倓h除了索引庫

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

文檔操作

初始化JavaRestClient

xxx寫虛擬機(jī)ip

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService hotelService;
    private RestHighLevelClient client;


    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

添加文檔

@Test
void testAddDocument() throws IOException {
    //根據(jù)id查詢酒店數(shù)據(jù)
    Hotel hotel = hotelService.getById(61083L);
    //轉(zhuǎn)換成文檔類型
    HotelDoc hotelDoc = new HotelDoc(hotel);

    //1、準(zhǔn)備Request對(duì)象
    IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
    //2、準(zhǔn)備json文檔
    request.source("{\"name"\:\"Jack\",\"age\":21}",XContentType.JSON);
    //3、發(fā)送請(qǐng)求
    client.index(request,RequestOptions.DEFAULT);
}?

我這里的第二步用的是實(shí)體類轉(zhuǎn)JSON的方式?

package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService hotelService;
    private RestHighLevelClient client;

    @Test
    void testAddDocument() throws IOException {
        //根據(jù)id查詢酒店數(shù)據(jù)
        Hotel hotel = hotelService.getById(61083L);
        //轉(zhuǎn)換成文檔類型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //1、準(zhǔn)備Request對(duì)象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2、準(zhǔn)備json文檔
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.index(request,RequestOptions.DEFAULT);
    }

 
    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

實(shí)體類

package cn.itcast.hotel.pojo;

import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
public class HotelDoc {
    private Long id;
    private String name;
    private String address;
    private Integer price;
    private Integer score;
    private String brand;
    private String city;
    private String starName;
    private String business;
    private String location;
    private String pic;

    public HotelDoc(Hotel hotel) {
        this.id = hotel.getId();
        this.name = hotel.getName();
        this.address = hotel.getAddress();
        this.price = hotel.getPrice();
        this.score = hotel.getScore();
        this.brand = hotel.getBrand();
        this.city = hotel.getCity();
        this.starName = hotel.getStarName();
        this.business = hotel.getBusiness();
        this.location = hotel.getLatitude() + ", " + hotel.getLongitude();
        this.pic = hotel.getPic();
    }
}

運(yùn)行該測試,控制臺(tái)運(yùn)行成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

查詢文檔

@Test
void testGetDocumentById() throws IOException {
    //1、準(zhǔn)備Request
    GetRequest request = new GetRequest("hotel", "61083");
    //2、發(fā)送請(qǐng)求,得到響應(yīng)
    GetResponse response = client.get(request, RequestOptions.DEFAULT);
    //3、解析響應(yīng)結(jié)果
    String json = response.getSourceAsString();
    //反序列化
    HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
    System.out.println(hotelDoc);
}
package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService hotelService;
    private RestHighLevelClient client;

    @Test
    void testAddDocument() throws IOException {
        //根據(jù)id查詢酒店數(shù)據(jù)
        Hotel hotel = hotelService.getById(61083L);
        //轉(zhuǎn)換成文檔類型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //1、準(zhǔn)備Request對(duì)象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2、準(zhǔn)備json文檔
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.index(request,RequestOptions.DEFAULT);
    }

    @Test
    void testGetDocumentById() throws IOException {
        //1、準(zhǔn)備Request
        GetRequest request = new GetRequest("hotel", "61083");
        //2、發(fā)送請(qǐng)求,得到響應(yīng)
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3、解析響應(yīng)結(jié)果
        String json = response.getSourceAsString();
        //反序列化
        HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
        System.out.println(hotelDoc);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

運(yùn)行該測試,控制臺(tái)運(yùn)行成功,并且把數(shù)據(jù)打印了出來

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

修改文檔

這里我只演示局部更新?

@Test
void testUpdateDocument() throws IOException {
    //1、準(zhǔn)備Request
    UpdateRequest request = new UpdateRequest("hotel", "61083");
    //2、準(zhǔn)備請(qǐng)求參數(shù)
    request.doc(
            "price", "952",
            "starName", "四鉆"
    );
    //3、發(fā)送請(qǐng)求
    client.update(request,RequestOptions.DEFAULT);
}
package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService hotelService;
    private RestHighLevelClient client;

    @Test
    void testAddDocument() throws IOException {
        //根據(jù)id查詢酒店數(shù)據(jù)
        Hotel hotel = hotelService.getById(61083L);
        //轉(zhuǎn)換成文檔類型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //1、準(zhǔn)備Request對(duì)象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2、準(zhǔn)備json文檔
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.index(request,RequestOptions.DEFAULT);
    }

    @Test
    void testGetDocumentById() throws IOException {
        //1、準(zhǔn)備Request
        GetRequest request = new GetRequest("hotel", "61083");
        //2、發(fā)送請(qǐng)求,得到響應(yīng)
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3、解析響應(yīng)結(jié)果
        String json = response.getSourceAsString();
        //反序列化
        HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
        System.out.println(hotelDoc);
    }

    @Test
    void testUpdateDocument() throws IOException {
        //1、準(zhǔn)備Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        //2、準(zhǔn)備請(qǐng)求參數(shù)
        request.doc(
                "price", "952",
                "starName", "四鉆"
        );
        //3、發(fā)送請(qǐng)求
        client.update(request,RequestOptions.DEFAULT);
    }

   

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

運(yùn)行該測試,控制臺(tái)運(yùn)行成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

刪除文檔

@Test
void testDeleteDocument() throws IOException {
    //1、準(zhǔn)備Request
    DeleteRequest request = new DeleteRequest("hotel", "61083");
    //2、發(fā)送請(qǐng)求
    client.delete(request,RequestOptions.DEFAULT);
}
package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService hotelService;
    private RestHighLevelClient client;

    @Test
    void testAddDocument() throws IOException {
        //根據(jù)id查詢酒店數(shù)據(jù)
        Hotel hotel = hotelService.getById(61083L);
        //轉(zhuǎn)換成文檔類型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //1、準(zhǔn)備Request對(duì)象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2、準(zhǔn)備json文檔
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.index(request,RequestOptions.DEFAULT);
    }

    @Test
    void testGetDocumentById() throws IOException {
        //1、準(zhǔn)備Request
        GetRequest request = new GetRequest("hotel", "61083");
        //2、發(fā)送請(qǐng)求,得到響應(yīng)
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3、解析響應(yīng)結(jié)果
        String json = response.getSourceAsString();
        //反序列化
        HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
        System.out.println(hotelDoc);
    }

    @Test
    void testUpdateDocument() throws IOException {
        //1、準(zhǔn)備Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        //2、準(zhǔn)備請(qǐng)求參數(shù)
        request.doc(
                "price", "952",
                "starName", "四鉆"
        );
        //3、發(fā)送請(qǐng)求
        client.update(request,RequestOptions.DEFAULT);
    }

    @Test
    void testDeleteDocument() throws IOException {
        //1、準(zhǔn)備Request
        DeleteRequest request = new DeleteRequest("hotel", "61083");
        //2、發(fā)送請(qǐng)求
        client.delete(request,RequestOptions.DEFAULT);
    }


    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

運(yùn)行該測試,控制臺(tái)運(yùn)行成功

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

批量導(dǎo)入文檔

@Test
void testBulkRequest() throws IOException {
    //1、創(chuàng)建Request
    BulkRequest request = new BulkRequest();
    //2、準(zhǔn)備參數(shù),添加多個(gè)新增的Request,這里添加兩個(gè)數(shù)據(jù),分別是id為101和102的數(shù)據(jù)
    request.add(new IndexRequest("hotel")
???????????.id("101").source("json source", XContentType.JSON));
    request.add(new IndexRequest("hotel")
???????????.id("102").source("json source", XContentType.JSON));
    //3、發(fā)送請(qǐng)求
    client.bulk(request,RequestOptions.DEFAULT);
}

我這里改成這樣,是因?yàn)槲乙言摫淼乃袛?shù)據(jù)都導(dǎo)入文檔

?@Test
? ? void testBulkRequest() throws IOException {
? ? ? ? //批量查詢酒店數(shù)據(jù)
? ? ? ? List<Hotel> hotels = hotelService.list();
? ? ? ? //1、創(chuàng)建Request
? ? ? ? BulkRequest request = new BulkRequest();
? ? ? ? //2、準(zhǔn)備參數(shù),添加多個(gè)新增的Request
? ? ? ? for(Hotel hotel:hotels){
? ? ? ? ? ? //轉(zhuǎn)換為文檔類型HotelDoc
? ? ? ? ? ? HotelDoc hotelDoc = new HotelDoc(hotel);
? ? ? ? ? ? //創(chuàng)建新增文檔的Request對(duì)象
? ? ? ? ? ? request.add(new IndexRequest("hotel")
? ? ? ? ? ? .id(hotelDoc.getId().toString())
? ? ? ? ? ? .source(JSON.toJSONString(hotelDoc),XContentType.JSON));
? ? ? ? }
? ? ? ? //3、發(fā)送請(qǐng)求
? ? ? ? client.bulk(request,RequestOptions.DEFAULT);
? ? }

package cn.itcast.hotel;

import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

import static cn.itcast.hotel.constants.HotelConstants.MAPPING_TEMPLATE;

@SpringBootTest
public class HotelDocumentTest {
    @Autowired
    private IHotelService hotelService;
    private RestHighLevelClient client;

    @Test
    void testAddDocument() throws IOException {
        //根據(jù)id查詢酒店數(shù)據(jù)
        Hotel hotel = hotelService.getById(61083L);
        //轉(zhuǎn)換成文檔類型
        HotelDoc hotelDoc = new HotelDoc(hotel);

        //1、準(zhǔn)備Request對(duì)象
        IndexRequest request = new IndexRequest("hotel").id(hotel.getId().toString());
        //2、準(zhǔn)備json文檔
        request.source(JSON.toJSONString(hotelDoc),XContentType.JSON);
        //3、發(fā)送請(qǐng)求
        client.index(request,RequestOptions.DEFAULT);
    }

    @Test
    void testGetDocumentById() throws IOException {
        //1、準(zhǔn)備Request
        GetRequest request = new GetRequest("hotel", "61083");
        //2、發(fā)送請(qǐng)求,得到響應(yīng)
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        //3、解析響應(yīng)結(jié)果
        String json = response.getSourceAsString();
        //反序列化
        HotelDoc hotelDoc = JSON.parseObject(json,HotelDoc.class);
        System.out.println(hotelDoc);
    }

    @Test
    void testUpdateDocument() throws IOException {
        //1、準(zhǔn)備Request
        UpdateRequest request = new UpdateRequest("hotel", "61083");
        //2、準(zhǔn)備請(qǐng)求參數(shù)
        request.doc(
                "price", "952",
                "starName", "四鉆"
        );
        //3、發(fā)送請(qǐng)求
        client.update(request,RequestOptions.DEFAULT);
    }

    @Test
    void testDeleteDocument() throws IOException {
        //1、準(zhǔn)備Request
        DeleteRequest request = new DeleteRequest("hotel", "61083");
        //2、發(fā)送請(qǐng)求
        client.delete(request,RequestOptions.DEFAULT);
    }

    @Test
    void testBulkRequest() throws IOException {
        //批量查詢酒店數(shù)據(jù)
        List<Hotel> hotels = hotelService.list();
        //1、創(chuàng)建Request
        BulkRequest request = new BulkRequest();
        //2、準(zhǔn)備參數(shù),添加多個(gè)新增的Request
        for(Hotel hotel:hotels){
            //轉(zhuǎn)換為文檔類型HotelDoc
            HotelDoc hotelDoc = new HotelDoc(hotel);
            //創(chuàng)建新增文檔的Request對(duì)象
            request.add(new IndexRequest("hotel")
            .id(hotelDoc.getId().toString())
            .source(JSON.toJSONString(hotelDoc),XContentType.JSON));
        }
        //3、發(fā)送請(qǐng)求
        client.bulk(request,RequestOptions.DEFAULT);
    }

    @BeforeEach
    void setUp() {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://xxx.xxx.xxx.xxx:9200")
        ));
    }

    @AfterEach
    void tearDown() throws IOException {
        this.client.close();
    }
}

運(yùn)行該測試,控制臺(tái)運(yùn)行成功,并且可以看到導(dǎo)入了201條數(shù)據(jù),正好表的數(shù)據(jù)量

ES的安裝和RestClient的操作,springcloud,spring cloud,微服務(wù),java,spring,spring boot,mybatis,es

代碼文件點(diǎn)擊下載https://pan.baidu.com/s/1NJnwlfThymqPRhqWqqP0FQ?pwd=6c0n?上一篇:SpringAMQP的配置和使用

下一篇:DSL查詢語法和RestClient查詢文檔文章來源地址http://www.zghlxwxcb.cn/news/detail-768003.html

到了這里,關(guān)于ES的安裝和RestClient的操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包