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

SpringBoot整合ElasticSearch之Java High Level REST Client

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

1 搭建SpringBoot工程

2 引入ElasticSearch相關(guān)坐標(biāo)。

<properties>
    		<!--一定重新定義版本   版本號(hào)一定要和您所安裝的ES版本號(hào)一致-->
        <elasticsearch.version>7.4.0</elasticsearch.version>
</properties>
<dependencies>
    <!--引入es的坐標(biāo)-->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>7.4.0</version>
    </dependency>
    ................

3 編寫核心配置類

編寫核心配置文件:

這里可以不寫在配置,可以直接寫在代碼中,只是一般都是寫在配置文件中

#這個(gè)是我們自寫的,如果看有es提示,不要用
elasticsearch:
  host: 192.168.126.20   
  port: 9200

編寫核心配置類

@Configuration
@ConfigurationProperties(prefix="elasticsearch")
public class ElasticSearchConfig {

    private String host;
    private int port;

    @Bean
    public RestHighLevelClient client(){
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host,port,"http")
        ));
    }  
    
    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

4 測(cè)試客戶端對(duì)象

記得把maven的單元測(cè)試關(guān)了

springboot集成resthighlevelclient,ES,springboot,java,elasticsearch,spring boot

注意:使用@Autowired注入RestHighLevelClient 如果報(bào)紅線,則是因?yàn)榕渲妙愃诘陌蜏y(cè)試類所在的包,包名不一致造成的

@SpringBootTest
class SpringElasticsearchApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    void contextLoads() {
        System.out.println(restHighLevelClient);
    }
}

(二)操作ElasticSearch

操作索引要索引的對(duì)象來(lái)進(jìn)行操作

//獲取索引對(duì)象     這個(gè)對(duì)象提供操作索引的方法
IndicesClient indices = client.indices();
//添加索引對(duì)象    RequestOptions.DEFAULT默認(rèn)的動(dòng)作
indices.create(new CreateIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//查詢索引對(duì)象
indices.get(new GetIndexRequest("offcn_index3"),RequestOptions.DEFAULT);
//刪除索引對(duì)象
indices.delete(new DeleteIndexRequest("offcn_index3"),RequestOptions.DEFAULT);

1 添加索引

/**
 * 添加索引:
 * @throws Exception
 */
@Test
   public void addindex() throws IOException {
       // 獲取索引對(duì)象
       IndicesClient indices = client.indices();
       //create()  CreateIndexRequest("索引名稱")    RequestOptions.DEFAULT默的行為
       CreateIndexResponse indexResponse = indices.create(new CreateIndexRequest("student123"), RequestOptions.DEFAULT);
       System.out.println(indexResponse.isAcknowledged());
   }

2 添加索引,并添加映射

/**
  * 創(chuàng)建索引并且添加映射
  * @throws IOException
  */
@Test
public void addIndexAndMapping() throws IOException {
    //1.使用client獲取操作索引的對(duì)象
    IndicesClient indicesClient = restHighLevelClient.indices();
    //2.具體操作,獲取返回值
    CreateIndexRequest createRequest = new CreateIndexRequest("offcn");
    //2.1 設(shè)置mappings
    String mapping = "{\n" +
        "      \"properties\" : {\n" +
        "        \"address\" : {\n" +
        "          \"type\" : \"text\",\n" +
        "          \"analyzer\" : \"ik_max_word\"\n" +
        "        },\n" +
        "        \"age\" : {\n" +
        "          \"type\" : \"long\"\n" +
        "        },\n" +
        "        \"name\" : {\n" +
        "          \"type\" : \"keyword\"\n" +
        "        }\n" +
        "      }\n" +
        "    }";
    createRequest.mapping(mapping, XContentType.JSON);
    //2.2執(zhí)行創(chuàng)建,返回對(duì)象
    CreateIndexResponse response = indicesClient.create(createRequest, RequestOptions.DEFAULT);
    //3.根據(jù)返回值判斷結(jié)果
    System.out.println(response.isAcknowledged());
}

3 查詢、刪除、判斷索引

3.1 查詢索引
/**
  * 查詢索引
  */
@Test
public void queryIndex() throws IOException {
    //1:使用client獲取操作索引的對(duì)象
    IndicesClient indices = restHighLevelClient.indices();
    //2:獲得對(duì)象,執(zhí)行具體的操作
    //2.1 創(chuàng)建獲取索引的請(qǐng)求對(duì)象,設(shè)置索引名稱
    GetIndexRequest getReqeust = new GetIndexRequest("offcn");
    //2.2 執(zhí)行查詢,獲得返回值
    GetIndexResponse response = indices.get(getReqeust, RequestOptions.DEFAULT);
    //3:獲取結(jié)果,遍歷
    Map<String, MappingMetaData> mappings = response.getMappings();
    for (String key : mappings.keySet()) {
        System.out.println(key + ":" + mappings.get(key).getSourceAsMap());
    }
}  
3.2 刪除索引
/**
  * 刪除索引
  */
@Test
public void deleteIndex() throws IOException {
    IndicesClient indices = restHighLevelClient.indices();
    DeleteIndexRequest deleteRequest = new DeleteIndexRequest("offcn");
    AcknowledgedResponse response = indices.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(response.isAcknowledged());
}
3.3 索引是否存在
/**
  * 判斷索引是否存在
  */
@Test
    public void getIndex() throws IOException {
        IndicesClient indices = client.indices();
        GetIndexRequest student0517 = new GetIndexRequest("student0517");
        boolean exists = indices.exists(student0517, RequestOptions.DEFAULT);
        if(exists){
            GetIndexResponse indexResponse = indices.get(student0517, RequestOptions.DEFAULT);
            Map<String, MappingMetaData> mappings = indexResponse.getMappings();
            System.out.println(mappings);
        }else{
            System.out.println("索引不存在");
        }
    }

4 操作文檔

4.1 添加文檔

添加文檔,使用map作為數(shù)據(jù)

/**
  * 添加文檔,使用map作為數(shù)據(jù)
  */
@Test
public void addDoc() throws IOException {
    //數(shù)據(jù)對(duì)象,map   key要與映射屬性對(duì)應(yīng)
    Map data = new HashMap();
    data.put("address", "北京昌平");
    data.put("name", "馬同志");
    data.put("age", 20);

    //1:獲取操作文檔的對(duì)象
    IndexRequest request = new IndexRequest("offcn").id("1").source(data);
    //2:添加數(shù)據(jù),獲取結(jié)果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印響應(yīng)結(jié)果
    System.out.println(response.getResult());
}

添加文檔,使用對(duì)象作為數(shù)據(jù)

添加依賴

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

創(chuàng)建實(shí)體類,屬性名與映射字段名對(duì)應(yīng)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
    private String brand;
    private Integer price;
    private String title;
}


{
  "sutdent78" : {
    "mappings" : {
      "properties" : {
        "brand" : {
          "type" : "keyword"
        },
        "price" : {
          "type" : "integer"
        },
        "title" : {
          "type" : "text",
          "analyzer" : "ik_max_word"
        }
      }
    }
  }
}
/**
  * 添加文檔,使用對(duì)象作為數(shù)據(jù)
  */
@Test
public void addDoc2() throws IOException {
    //數(shù)據(jù)對(duì)象,javaObject
    Student student=new Student("kaka",22,"南沙中公教育");

    //將對(duì)象轉(zhuǎn)為json
    String data = JSON.toJSONString(p);
    //1:獲取操作文檔的對(duì)象
    IndexRequest request = new IndexRequest("offcn").id(p.getId()).source(data, XContentType.JSON);
    //2:添加數(shù)據(jù),獲取結(jié)果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印響應(yīng)結(jié)果
    System.out.println(response.getId());
}
4.2 修改文檔:添加文檔時(shí),如果id存在則修改,id不存在則添加
/**
  * 修改文檔:添加文檔時(shí),如果id存在則修改,id不存在則添加
  */
@Test
public void updateDoc() throws IOException {
    //數(shù)據(jù)對(duì)象,map
    Map data = new HashMap();
    data.put("address", "北京昌平");
    data.put("name", "朱同志");
    data.put("age", 20);

    //1:獲取操作文檔的對(duì)象
    IndexRequest request = new IndexRequest("offcn").id("1").source(data);
    //2:添加數(shù)據(jù),獲取結(jié)果
    IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    //3:打印響應(yīng)結(jié)果
    System.out.println(response.getId());
}
4.3 根據(jù)id查詢文檔
    @Test
    public void getDoc() throws IOException {
        GetRequest getRequest = new GetRequest("sutdent78").id("1002");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        //集合方式
        Map<String, Object> source = documentFields.getSource();
        for (String key : source.keySet()) {
            System.out.println(source.get(key));
        }
        //字符串  -----JSON
        String sourceAsString = documentFields.getSourceAsString();
        System.out.println(sourceAsString);
        //把JSON轉(zhuǎn)換為 stuent
        //JSON字符串-->JSON對(duì)象
        JSONObject jsonObject = JSONObject.parseObject(sourceAsString);
        //JSON對(duì)象-->Java對(duì)象
        Student student = JSONObject.toJavaObject(jsonObject, Student.class);
        System.out.println(student);

    }
4.4 根據(jù)id刪除文檔
/**
  * 根據(jù)id刪除文檔
  */
@Test
public void delDoc() throws IOException {
    DeleteRequest deleteRequest = new DeleteRequest("offcn", "1");
    DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
    System.out.println(response.getId());
}

總結(jié):

//添加、修改   第一個(gè):索引名稱   第二個(gè)是文檔id     第三個(gè)是文檔內(nèi)容
restHighLevelClient
    .index( new IndexRequest("offcn_index2").id("as1122").source(data),RequestOptions.DEFAULT)
//查詢    第一個(gè)參數(shù)是索引名稱   第二個(gè)是文檔id
restHighLevelClient.get( new GetRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)
//刪除    第一個(gè)參數(shù)是索引名稱   第二個(gè)是文檔id
restHighLevelClient.delete( new DeleteRequest("offcn_index2","as1122"),RequestOptions.DEFAULT)

(三)ElasticSearch的文檔批量操作

1 bulk文檔 批量操作腳本實(shí)現(xiàn)

需求:同時(shí)完成【刪除,更新,添加】操作 這里的JSON格式不能格式化

POST _bulk
{"delete":{"_index":"person1","_id":"4"}}
{"create":{"_index":"person1","_id":"5"}}
{"name":"八號(hào)","age":18,"address":"北京"}
{"update":{"_index":"person1","_id":"2"}}
{"doc":{"name":"2號(hào)"}}

查詢運(yùn)行結(jié)果~ 

2 bulk批量操作JavaAPI 實(shí)現(xiàn)

/**
     *  Bulk 批量操作
     */
    @Test
    public void test2() throws IOException {

        //創(chuàng)建bulkrequest對(duì)象,整合所有操作
        BulkRequest bulkRequest =new BulkRequest();

           /*
        # 1. 刪除5號(hào)記錄
        # 2. 添加6號(hào)記錄
        # 3. 修改3號(hào)記錄 名稱為 “三號(hào)”
         */
        //添加對(duì)應(yīng)操作
        //1. 刪除5號(hào)記錄
        DeleteRequest deleteRequest=new DeleteRequest("person1","5");
        bulkRequest.add(deleteRequest);

        //2. 添加6號(hào)記錄
        Map<String, Object> map=new HashMap<>();
        map.put("name","六號(hào)");
        IndexRequest indexRequest=new IndexRequest("person1").id("6").source(map);
        bulkRequest.add(indexRequest);
        //3. 修改3號(hào)記錄 名稱為 “三號(hào)”
        Map<String, Object> mapUpdate=new HashMap<>();
        mapUpdate.put("name","三號(hào)");
        UpdateRequest updateRequest=new UpdateRequest("person1","3").doc(mapUpdate);

        bulkRequest.add(updateRequest);
        //執(zhí)行批量操作

        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(response.status());
    }

官方文檔:
https://www.elastic.co/guide/en/elasticsearch/client/index.html

Java REST Client 》Java High Level REST Client文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-745528.html

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

本文來(lái)自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(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)文章

  • elasaticsearch新版java客戶端ElasticsearchClient詳細(xì)教程,支持響應(yīng)式編程,Lambda表達(dá)式,兼容舊版High Level Rest Client

    elasaticsearch新版java客戶端詳細(xì)教程,支持響應(yīng)式編程,Lambda表達(dá)式。兼容舊版High Level Rest Client。網(wǎng)上相關(guān)教程少,我在這里出一個(gè)。elasaticsearch相關(guān)安裝這里不介紹了 有幾種方式,這里介紹兩種,如果不考慮之前舊版High Level Rest Client的客戶端采用第一種就行 阻塞和異步客戶

    2023年04月15日
    瀏覽(19)
  • Java SpringBoot整合elasticsearch 7.17相關(guān)問(wèn)題記錄

    Java SpringBoot整合elasticsearch 7.17相關(guān)問(wèn)題記錄

    話不多說(shuō)直接上代碼,首先關(guān)注點(diǎn)Springboot相關(guān)ES相關(guān)的版本對(duì)應(yīng) 找到對(duì)應(yīng)的版本號(hào),我這里對(duì)應(yīng)7.17.1 對(duì)應(yīng)的springboot版本 2.3.* 即可 上圖為Springboot相關(guān)依賴 ES 創(chuàng)建索引以及映射相關(guān)(首先映射分詞要保持環(huán)境中Es下的分詞器安裝正確) //創(chuàng)建索引 對(duì)應(yīng)的增刪改查 //增加 文檔

    2024年02月11日
    瀏覽(25)
  • java-springboot整合ElasticSearch8.2復(fù)雜查詢

    近期有大數(shù)據(jù)項(xiàng)目需要用到es,而又是比較新的es版本,網(wǎng)上也很少有8.x的java整合教程,所有寫下來(lái)供各位參考。 首先 1.導(dǎo)包: 2.客戶端連接代碼EsUtilConfigClint: 一開始按照其他博主的方法,長(zhǎng)時(shí)間連接不操作查詢?cè)俅握{(diào)用查詢時(shí)會(huì)報(bào)錯(cuò)timeout,所以要設(shè)置RequestConfigCallback 3

    2024年02月11日
    瀏覽(16)
  • SpringBoot整合最新Elasticsearch Java API Client 7.16教程

    SpringBoot整合最新Elasticsearch Java API Client 7.16教程

    ????最新在學(xué)習(xí)SpringBoot整合es的一些知識(shí),瀏覽了網(wǎng)上的一些資料,發(fā)現(xiàn)全都是es很久之前的版本了,其中比較流行的是Java REST Client的High Level Rest Client版本,但是官方文檔的說(shuō)明中,已經(jīng)申明該版本即將廢棄,不再進(jìn)行維護(hù)了??梢姡汗俜轿臋n ????目前官方推薦的版本是

    2023年04月24日
    瀏覽(33)
  • java SpringBoot2.7整合Elasticsearch(ES)7 進(jìn)行文檔增刪查改

    java SpringBoot2.7整合Elasticsearch(ES)7 進(jìn)行文檔增刪查改

    首先 我們?cè)?ES中加一個(gè) books 索引 且?guī)в蠭K分詞器的索引 首先 pom.xml導(dǎo)入依賴 application配置文件中編寫如下配置 spring.elasticsearch.hosts: 172.16.5.10:9200 我這里是用的yml格式的 告訴它指向 我們本地的 9200服務(wù) 然后 我們?cè)趩?dòng)類同目錄下 創(chuàng)建一個(gè)叫 domain的包 放屬性類 然后在這個(gè)包

    2024年02月19日
    瀏覽(19)
  • 【Elasticsearch學(xué)習(xí)筆記五】es常用的JAVA API、es整合SpringBoot項(xiàng)目中使用、利用JAVA代碼操作es、RestHighLevelClient客戶端對(duì)象

    目錄 一、Maven項(xiàng)目集成Easticsearch 1)客戶端對(duì)象 2)索引操作 3)文檔操作 4)高級(jí)查詢 二、springboot項(xiàng)目集成Spring Data操作Elasticsearch 1)pom文件 2)yaml 3)數(shù)據(jù)實(shí)體類 4)配置類 5)Dao數(shù)據(jù)訪問(wèn)對(duì)象 6)索引操作 7)文檔操作 8)文檔搜索 三、springboot項(xiàng)目集成bboss操作elasticsearch

    2023年04月09日
    瀏覽(37)
  • Elasticsearch Java REST Client 批量操作(Bulk API)

    上一篇:Elasticsearch Java REST Client Term Vectors API 下一篇:Elasticsearch Java REST Client Search APIs 查詢 BulkRequest可用于使用單個(gè)請(qǐng)求執(zhí)行多個(gè)索引、更新和/或刪除操作。 它需要至少一個(gè)操作添加到 Bulk 請(qǐng)求中: multiGetAPI 在單個(gè) http 請(qǐng)求中并行執(zhí)行多個(gè)請(qǐng)求get 。 MultiGetRequest,添加 `M

    2024年02月11日
    瀏覽(25)
  • Elasticsearch基礎(chǔ),SpringBoot整合Elasticsearch

    Elasticsearch基礎(chǔ),SpringBoot整合Elasticsearch

    Elasticsearch,簡(jiǎn)稱為es,es是一個(gè)開源的高擴(kuò)展的分布式全文檢索引擎,它可以近乎實(shí)時(shí)的存儲(chǔ)、檢索數(shù)據(jù);本身擴(kuò)展性很好,可以擴(kuò)展到上百臺(tái)服務(wù)器,處理PB級(jí)別(大數(shù)據(jù)時(shí)代)的數(shù)據(jù)。es也使用Java開發(fā)并使用Lucene作為其核心來(lái)實(shí)現(xiàn)所有索引和搜索的功能,但是它的目的是通

    2024年01月19日
    瀏覽(21)
  • 【ElasticSearch系列-05】SpringBoot整合elasticSearch

    【ElasticSearch系列-05】SpringBoot整合elasticSearch

    ElasticSearch系列整體欄目 內(nèi)容 鏈接地址 【一】ElasticSearch下載和安裝 https://zhenghuisheng.blog.csdn.net/article/details/129260827 【二】ElasticSearch概念和基本操作 https://blog.csdn.net/zhenghuishengq/article/details/134121631 【三】ElasticSearch的高級(jí)查詢Query DSL https://blog.csdn.net/zhenghuishengq/article/details/1

    2024年02月06日
    瀏覽(50)
  • ElasticSearch8 - SpringBoot整合ElasticSearch

    springboot 整合 ES 有兩種方案,ES 官方提供的 Elasticsearch Java API Client 和 spring 提供的 [Spring Data Elasticsearch](Spring Data Elasticsearch) 兩種方案各有優(yōu)劣 Spring:高度封裝,用著舒服。缺點(diǎn)是更新不及時(shí),有可能無(wú)法使用 ES 的新 API ES 官方:更新及時(shí),靈活,缺點(diǎn)是太靈活了,基本是一

    2024年03月25日
    瀏覽(78)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包