springboot整合Elasticsearch簡單操作


概述

  Java存在三種es的客戶端

  1. Transport Client
  2. Java Low Level Rest Client
  3. Java High Level Rest Client

造成這種混亂的原因是es開始是沒有Java版的客戶端,但Java自己是可以簡單的支持es的API,所以有了第一種客戶端(Transport Client)。后來官方推出了第二種版本(Java Low Level Rest Client),但缺點也是顯而易見的,因為從第一種版本遷移到第二版本工作量是比較的大的,官方還特意出一堆文檔來提供參考。而第三種版本的客戶端是兼容兩種客戶端的優點,他是在第二種版本的基礎上進行了封裝,也讓代碼遷移變得更方便,但依然存在缺點,小的版本更新頻繁,經常出現莫名其妙的錯誤,我們盡量保持客戶端和服務器相同的版本。lz這邊的用的是es 6.6.2版本

整合

搭建springboot框架就不介紹了,直接看下依賴jar

  <!--es引入-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.6.2</version>
        </dependency>

創建EsConfig類

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;

/**
 *
 * Description:es配置
 * @author huangweicheng
 * @date 2020/3/19
*/
@Configuration
public class EsConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("10.105.9.119",9200,"http")
                )
        );
        return client;
    }
}

接下去就很簡單了,去調用客戶端的API操作即可

查找

先看下在服務端的數據

 

 查詢id為1的文檔

    @Autowired
    private RestHighLevelClient client;

    @GetMapping("/teacher")
    public ResponseEntity get(@RequestParam(value = "id",defaultValue = "") String id) throws IOException {
        try {
            if (id.isEmpty()){
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            GetRequest request = new GetRequest("user","teacher",id);
            GetResponse result = client.get(request, RequestOptions.DEFAULT);
            if (!result.isExists()){
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity(result.getSource(),HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

結果

 

 添加

    @PostMapping("/add")
    public ResponseEntity add(
            @RequestParam String name,
            @RequestParam String gender,
            @RequestParam int age,
            @RequestParam String country,
            @RequestParam String date
    ) throws IOException {
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name",name)
                .field("gender",gender)
                .field("age",age)
                .field("country",country)
                .field("date",date)
                .endObject();
        IndexRequest indexRequest = new IndexRequest("user","teacher");
        indexRequest.source(xContentBuilder);
        IndexResponse response = client.index(indexRequest,RequestOptions.DEFAULT);
        return new ResponseEntity(response.getId(),HttpStatus.OK);
    }

結果

 

 

修改

 @PutMapping("/update/teacher")
    public ResponseEntity update(
            @RequestParam(name = "id") String id,
            @RequestParam(name = "name",required = false) String name,
            @RequestParam(name = "gender",required = false) String gender
    ) throws IOException
    {
        UpdateRequest updateRequest = new UpdateRequest("user","teacher",id);
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name",name)
                .field("gender",gender)
                .endObject();
        updateRequest.doc(xContentBuilder);
        UpdateResponse result = client.update(updateRequest,RequestOptions.DEFAULT);
        return new ResponseEntity(result.getId(),HttpStatus.OK);
    }

 

 

刪除

將剛才添加的數據刪除

@DeleteMapping("/delete/teacher")
    public ResponseEntity delete(@RequestParam(name = "id") String id) throws IOException
    {
        DeleteRequest deleteRequest = new DeleteRequest("user","teacher",id);
        DeleteResponse deleteResponse = client.delete(deleteRequest,RequestOptions.DEFAULT);
        return new ResponseEntity(deleteResponse.status(),HttpStatus.OK);
    }

 

 以上就是springboot整合es后基本操作,下面是完整的偽代碼

import com.alibaba.fastjson.annotation.JSONField;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.get.GetResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Date;

/**
 * 
 * Description:
 * @author huangweicheng
 * @date 2020/3/19   
*/ 
@RestController
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RestHighLevelClient client;

    @GetMapping("/teacher")
    public ResponseEntity get(@RequestParam(value = "id",defaultValue = "") String id) throws IOException {
        try {
            if (id.isEmpty()){
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            GetRequest request = new GetRequest("user","teacher",id);
            GetResponse result = client.get(request, RequestOptions.DEFAULT);
            if (!result.isExists()){
                return new ResponseEntity(HttpStatus.NOT_FOUND);
            }
            return new ResponseEntity(result.getSource(),HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping("/add")
    public ResponseEntity add(
            @RequestParam String name,
            @RequestParam String gender,
            @RequestParam int age,
            @RequestParam String country,
            @RequestParam String date
    ) throws IOException {
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name",name)
                .field("gender",gender)
                .field("age",age)
                .field("country",country)
                .field("date",date)
                .endObject();
        IndexRequest indexRequest = new IndexRequest("user","teacher");
        indexRequest.source(xContentBuilder);
        IndexResponse response = client.index(indexRequest,RequestOptions.DEFAULT);
        return new ResponseEntity(response.getId(),HttpStatus.OK);
    }

    @DeleteMapping("/delete/teacher")
    public ResponseEntity delete(@RequestParam(name = "id") String id) throws IOException
    {
        DeleteRequest deleteRequest = new DeleteRequest("user","teacher",id);
        DeleteResponse deleteResponse = client.delete(deleteRequest,RequestOptions.DEFAULT);
        return new ResponseEntity(deleteResponse.status(),HttpStatus.OK);
    }

    @PutMapping("/update/teacher")
    public ResponseEntity update(
            @RequestParam(name = "id") String id,
            @RequestParam(name = "name",required = false) String name,
            @RequestParam(name = "gender",required = false) String gender
    ) throws IOException
    {
        UpdateRequest updateRequest = new UpdateRequest("user","teacher",id);
        XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
                .startObject()
                .field("name",name)
                .field("gender",gender)
                .endObject();
        updateRequest.doc(xContentBuilder);
        UpdateResponse result = client.update(updateRequest,RequestOptions.DEFAULT);
        return new ResponseEntity(result.getId(),HttpStatus.OK);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM