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

1.配置

1.1.springBoot版本

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

1.2.Maven 依赖

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

1.3.一定要保证elasticsearch 版本要与本机版本一致

    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.6.1</elasticsearch.version>
    </properties>

1.4.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;

@Configuration
public class ESConfig {

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

2.Api测试

pojo

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    private String name;

    private Long age;

    private String desc;
}

import

import com.alibaba.fastjson.JSON;
import com.mine.esapi.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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.support.master.AcknowledgedResponse;
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.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

RestHighLevelClient

    @Resource
    RestHighLevelClient client;

2.1.测试创建索引

    /**
     * 测试创建索引
     */
    @Test
    void testCreateIndex() throws IOException {
        // 1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest("mine_index");
        //2、客户端执行请求 IndicesClient , 请求后获得响应
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());

    }


2.2.判断索引是否存在

    /**
     * 判断索引是否存在
     */
    @Test
    void testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("mine_index");
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

2.3.删除索引

    /**
     * 删除索引
     */
    @Test
    void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("mine_index");
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

2.4.添加文档

    /**
     * 添加文档
     */
    @Test
    void testCreateDoc() throws IOException {
        // 创建对象
        User user = new User("张三", 10L, "1111");
        // 创建请求
        IndexRequest request = new IndexRequest("mine_index");
        // 添加规则
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1L));
        // 将数据放入请求  要将数据转化为 JSON
        request.source(JSON.toJSONString(user), XContentType.JSON);
        // 客户端发送请求,获取响应结果
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        // 获取结果
        System.out.println(response.toString());
        // 获取命令状态
        System.out.println(response.status());
    }


2.5.判断文档是否存在

    @Test
    void testExistDoc() throws IOException {
        GetRequest request = new GetRequest("mine_index", "1");
        // 不获取返回 _source 的上下文 可以省略
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");

        boolean exists = client.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

2.6.获取文档信息

    /**
     * 获取文档信息
     */
    @Test
    void testGetDoc() throws IOException {
        GetRequest request = new GetRequest("mine_index", "1");
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 获取文档内容 返回 Map
        System.out.println(response.getSource());
        // 获取文档所有信息
        System.out.println(response);
    }

2.7.更新文档

    /**
     * 更新文档
     */
    @Test
    void testUpdateDoc() throws IOException {
        UpdateRequest request = new UpdateRequest("mine_index", "1");
        request.timeout("1s");
        // 创建新对象
        User user = new User("张三", 22L, "222");
        request.doc(JSON.toJSONString(user), XContentType.JSON);

        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.out.println(response);
        System.out.println(response.status());
    }


2.8.删除文档

    /**
     * 删除文档
     */
    @Test
    void testDeleteDoc() throws IOException {
        DeleteRequest request = new DeleteRequest("mine_index", "1");
        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
        System.out.println(response);
        System.out.println(response.status());

    }


2.9.插入多条数据

    /**
     * 插入多条数据
     */
    @Test
    void testBulkInsert() throws IOException {
        BulkRequest request = new BulkRequest();
        request.timeout("1s");

        List<User> userList = new ArrayList<>();
        userList.add(new User("z1", 1L, "11"));
        userList.add(new User("z2", 2L, "22"));
        userList.add(new User("z3", 3L, "33"));
        userList.add(new User("z4", 4L, "44"));
        userList.add(new User("z5", 5L, "55"));
        userList.add(new User("z6", 6L, "66"));

        for (int i = 0; i < userList.size(); i++) {
            request.add(new IndexRequest("mine_index").id(String.valueOf(i + 1)).source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
        }
        BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
        // 如果是false则说明插入成功
        System.out.println(response.hasFailures());
    }


posted on 2021-05-28 15:41  whn051799  阅读(60)  评论(0编辑  收藏  举报