elasticsearch--RestClient操作索引库(java)

发布于:2024-08-08 ⋅ 阅读:(65) ⋅ 点赞:(0)

参考:https://blog.csdn.net/CYK_byte/article/details/133255773

https://blog.csdn.net/weixin_45404884/article/details/137402463

java pom依赖:

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

测试案例:

测试类,开始是创建restClient。结束是关闭client

private RestHighLevelClient client;

@BeforeEach
public void setUp() {
    client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http//127.0.0.1:9200")
            //将来如果是集群,这里还可以通过 HttpHost.create 继续连接多个节点
    ));
}

@AfterEach
public void tearDown() throws IOException {
    client.close();
}
这里我们创建一个测试类 HotelIndexTest ,用来演示 RestClient 操作的相关方法.
package com.gen.test.elc;

import com.gen.test.elasticsearch.ElcTestApplication;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
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.index.IndexResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest(classes = ElcTestApplication.class)
public class HotelIndexTest {

    private RestHighLevelClient client;

    @BeforeEach
    public void setUp() {
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http//127.0.0.1:9200")
                //将来如果是集群,这里还可以通过 HttpHost.create 继续连接多个节点
        ));
    }

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

    /**
    * 创建索引库
    * */
    private 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" +
            "      },\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" +
            "      },\n" +
            "      \"city\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"star_name\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"business\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"location\":{\n" +
            "        \"type\": \"geo_point\"\n" +
            "      },\n" +
            "      \"pic\":{\n" +
            "        \"type\": \"keyword\",\n" +
            "        \"index\": false\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
    @Test
    public void testCreateHotelIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
        // 1.创建 Request 对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 2.请求参数, MAPPING_TEMPLATE是静态常量字符串,内容是创建索引库的 DSL语句
        request.source(MAPPING_TEMPLATE, XContentType.JSON);
        // 3.发起请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    /**
    * 删除索引库
    * */
    @Test
    public void testDeleteHotelIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
        // 1.创建 Request对象
        DeleteIndexRequest request = new DeleteIndexRequest("hotel");
        // 2.发起请求
        AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(delete);
    }

    /**
    * 判断索引库是否存在
    * */
    @Test
    public void testExistsHotelIndex() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
        // 1.创建 Request对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        // 2.发起请求
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /*-----------------------------------文档操作----------------------------------------*/

    /**
    * 添加酒店数据到索引库
    * */
    @Test
    public void testIndexDocument() throws IOException {
        // 创建Elasticsearch客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        try {
            // 构建请求
            Request request = new Request("POST", "/hotel/_doc/1"); // 自定义请求URL
            String template = "{\n" +
                    "  \"name\": \"张三\",\n" +
                    "  \"email\": \"zy@itcast.cn\"\n" +
                    "}";
            request.setJsonEntity(template); // 设置请求体

            // 发送请求并处理响应
            Response response = client.getLowLevelClient().performRequest(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { // 成功创建的状态码
                System.out.println("Document created successfully.");
            } else {
                System.err.println("Failed to create document. Status code: " + statusCode);
            }
        } finally {
            // 关闭客户端
            client.close();
        }
    }


    /**
    *根据 id 查询酒店数据
    * */
    @Test
    public void testGetDocumentById() throws IOException {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://localhost:9200")
        ));
        // 1.创建 request对象
        GetRequest request = new GetRequest("hotel", "1");
        // 2.发送请求,得到结果
        GetResponse response = client.get(request, RequestOptions.DEFAULT);
        // 3.解析结果
        String json = response.getSourceAsString();
        System.out.println(json);
        client.close();
    }

    /**
    * 根据 id 修改酒店数据
    * */
    @Test
    public void testUpdateDocumentById() throws IOException {
        // 创建Elasticsearch客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        try {
            // 构建请求
            Request request = new Request("POST", "/hotel/_doc/1"); // 自定义请求URL
            String template = "{\n" +
                    "  \"name\": \"张三\",\n" +
                    "  \"email\": \"2312123@163.com\"\n" +
                    "}";
            request.setJsonEntity(template); // 设置请求体

            // 发送请求并处理响应
            Response response = client.getLowLevelClient().performRequest(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { // 成功创建的状态码
                System.out.println("Document created successfully.");
            } else {
                System.err.println("Failed to create document. Status code: " + statusCode);
            }
        } finally {
            // 关闭客户端
            client.close();
        }
    }

    /**
    * 根据 id 删除文档数据
    * */
    @Test
    public void testDeleteDocumentById() throws IOException {
        // 创建Elasticsearch客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));

        try {
            // 构建请求
            Request request = new Request("DELETE", "/hotel/_doc/1"); // 自定义请求URL

            // 发送请求并处理响应
            Response response = client.getLowLevelClient().performRequest(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) { // 成功创建的状态码
                System.out.println("Document created successfully.");
            } else {
                System.err.println("Failed to create document. Status code: " + statusCode);
            }
        } finally {
            // 关闭客户端
            client.close();
        }
    }




}

二、springboot-data结合

参考:https://blog.csdn.net/m0_64210833/article/details/135274603


网站公告

今日签到

点亮在社区的每一天
去签到