java springboot客户端测试elasticsearch6.x版本和7.x 版本案例

elasticsearch7.x版本测试案例:

一、pom.xml文件

        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        

我的项目采用springboot2.3.0版本,注意springboot、rest client-jar、elasticsearch三者版本要兼容,稍早前的springboot版本所默认的Elasticsearch版本是6.x版本。

查看你引入rest-client的jar包版本号方法,亲测在springboot2.3.0版本开始默认为rest client7.6.2的jar版本,如下。

java springboot客户端测试elasticsearch6.x版本和7.x 版本案例_第1张图片

二、创建ElasticsearchRestClientConfig配置类,自定义配置es连接信息。创建Article文档实体类。

package com.example.provider.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 ElasticsearchRestClientConfig {

    //自定义连接属性
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.36.25", 9200, "http")));
        return client;
    }

}
@Data
public class ArticleBean {

    private Integer id;
    private String title;
    private String author;

    public ArticleBean(Integer id, String title, String author) {
        this.id = id;
        this.title = title;
        this.author = author;
    }

    public ArticleBean() {
    }
}

 

三、ES索引管理EsArticleIndexController

我项目中还引入了swagger,如果你自己没引入,去掉相关注解就好

package com.example.provider.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;


@Api(tags = "接口Index")
@RestController
public class EsArticleIndexController {


    @Autowired
    @Qualifier("restHighLevelClient")
    RestHighLevelClient client;

    @ApiOperation(value = "1.add索引")
    @GetMapping("/addArticleToEs")
    public void addArticleToEs(){


        CreateIndexRequest createIndexRequest = new CreateIndexRequest("article_index");

        try {
            CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            System.out.println(createIndexRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "2.检查索引是否存在")
    @GetMapping("/getIndexFromEs")
    public void getIndexFromEs(){

        GetIndexRequest getIndexRequest = new GetIndexRequest("my_article_index_01");
        try {
            boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
            System.out.println(exists);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @ApiOperation(value = "3.删除指定索引")
    @GetMapping("/DelIndexFromEs")
    public void DelIndexFromEs(){

        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("my_article_index_01");
        try {
            AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
            System.out.println(delete);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

四、ES文档管理EsArticleController

package com.example.provider.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.provider.bean.ArticleBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
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.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
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.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

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



@Api(tags = "接口doc")
@Controller
public class EsArticleDocController {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @ResponseBody
    @ApiOperation(value = "1.add文档")
    @GetMapping("/addDocToEs")
    public String addDocToEs(String index, Integer id, String author, String title){

        ArticleBean article = new ArticleBean();
        article.setId(id);
        article.setAuthor(author);
        article.setTitle(title);

        IndexRequest request = new IndexRequest(index);

        // put /article_index/_doc/1
        //不给id,默认无序ID
//        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(10));
        //将资源放进
        request.source(JSON.toJSONString(article), XContentType.JSON);

        //客户端请求
        try {
            IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            return indexResponse.toString() + "";
        } catch (IOException e) {
            e.printStackTrace();
            return "IO错误";
        }
    }

    @ResponseBody
    @ApiOperation(value = "2.查找文档")
    @GetMapping("/getDocFromEs")
    public String getDocFromEs(String index, Integer id) throws IOException {

        GetRequest getRequest = new GetRequest(index,id.toString());
        boolean exists = false;
        //客户端请求
        exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);

        if(exists){
            GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
            return documentFields.toString() +"";
        }else {
            return "文档不存在";
        }
    }

    @ResponseBody
    @ApiOperation(value = "3.更新文档")
    @GetMapping("/updateDocFromEs")
    public String updateDocFromEs(String index, Integer id) throws IOException {

        UpdateRequest updateRequest = new UpdateRequest(index, id.toString());
        updateRequest.timeout(TimeValue.timeValueSeconds(10));
        //将资源放进
        ArticleBean article = new ArticleBean();
        article.setId(11);
        article.setAuthor("新author");
        article.setTitle("新title");
        updateRequest.doc(JSON.toJSONString(article),XContentType.JSON);
        UpdateResponse updateResponse = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        return updateResponse.toString() +"";
    }

    @ResponseBody
    @ApiOperation(value = "4.删除文档")
    @GetMapping("/deleteDocFromEs")
    public String deleteDocFromEs(String index, Integer id) throws IOException {

        DeleteRequest deleteRequest = new DeleteRequest(index, id.toString());
        deleteRequest.timeout(TimeValue.timeValueSeconds(10));

        DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        return deleteResponse.toString() +"";
    }

    @ResponseBody
    @ApiOperation(value = "5.json批量添加文档")
    @PostMapping("/bulkAddDocToEs")
    public String bulkAddDocToEs(@RequestBody String jsonParam) throws IOException {

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(10));

        JSONObject jsonObjectNew = JSONObject.parseObject(jsonParam);
        String index = jsonObjectNew.getString("index");
        String data = jsonObjectNew.getString("data");

        JSONArray dataArray = JSONArray.parseArray(data);

        for (int i = 0; i < dataArray.size(); i++) {
            bulkRequest.add(new IndexRequest(index)
//                    .id("")
                    .source(JSON.toJSONString(dataArray.get(i)),XContentType.JSON));
        }
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);


        return bulkResponse.toString() +"";
    }

    @ResponseBody
    @ApiOperation(value = "6.Provider_es中批量添加articleBean")
    @PostMapping("/bulkAddArticleToEs")
    public String bulkAddArticleToEs() throws IOException {

        BulkResponse bulkResponse = null;

        ArticleBean article1 = new ArticleBean(1,"第1个文章","第1个作者");
        ArticleBean article2 = new ArticleBean(2,"第2个文章","第2个作者");
        ArticleBean article3 = new ArticleBean(3,"第3个文章","第3个作者");
        ArticleBean article4 = new ArticleBean(4,"第4个文章","第4个作者");

        List articleBeanList = new ArrayList();
        articleBeanList.add(article1);
        articleBeanList.add(article2);
        articleBeanList.add(article3);
        articleBeanList.add(article4);

        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout(TimeValue.timeValueSeconds(10));

        for(int i=0;i

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

elasticsearch6.x版本测试案例:

请参考感谢:https://www.cnblogs.com/dehigher/p/10162795.html

你可能感兴趣的:(java,Elasticsearch,springboot)