Elasticsearch rest-high-level-client 基本操作

Elasticsearch rest-high-level-client 基本操作

本篇主要講解一下 rest-high-level-client 去操作 Elasticsearch , 雖然這個客戶端在後續版本中會慢慢淘汰,但是目前大部分公司中使用Elasticsearch 版本都是6.x 所以這個客戶端還是有一定的瞭解

image-20221025135725969

前置準備

  • 準備一個SpringBoot環境 2.2.11 版本
  • 準備一個Elasticsearch 環境 我這裏是8.x版本
  • 引入依賴 elasticsearch-rest-high-level-client 7.4.2

1.配置依賴

注意: 我使用的是 springboot 2.2.11 版本 , 它內部的 elasticsearch 和 elasticsearch-rest-client 都是 6.8.13 需要注意

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

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
       <!-- 引入 elasticsearch 7.4.2  -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.4.2</version>
            <exclusions>
                <exclusion>
                    <artifactId>log4j-api</artifactId>
                    <groupId>org.apache.logging.log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

      <!-- 排除 elasticsearch-rest-client , 也可不排除 爲了把maven衝突解決   -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.4.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
                <exclusion>
                    <artifactId>elasticsearch</artifactId>
                    <groupId>org.elasticsearch</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- 不引入會導致可能 使用 springboot的 elasticsearch-rest-client 6.8.13 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>7.4.2</version>
        </dependency>

        <!-- elasticsearch 依賴 2.x 的 log4j -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.8.2</version>
            <!--  排除掉 log4j-api 因爲springbootstarter 中引入了loging模塊 -->
            <exclusions>
                <exclusion>
                    <artifactId>log4j-api</artifactId>
                    <groupId>org.apache.logging.log4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- junit 單元測試 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

2.構建 RestHighLevelClient

highlevelclient 是 高級客戶端 需要通過它去操作 Elasticsearch , 它底層也是要依賴 rest-client 低級客戶端

@Slf4j
public class TestEsClient {

    private RestHighLevelClient client = null;
    private ObjectMapper objectMapper = new ObjectMapper();
		
    //構建 RestHighLevelClient
    @Before
    public void prepare() {
        // 創建Client連接對象
        String[] ips = {"172.16.225.111:9200"};
        HttpHost[] httpHosts = new HttpHost[ips.length];
        for (int i = 0; i < ips.length; i++) {
            httpHosts[i] = HttpHost.create(ips[i]);
        }
        RestClientBuilder builder = RestClient.builder(httpHosts);
        client = new RestHighLevelClient(builder);
    }
}

3.創建索引 client.indices().create

創建索引 需要使用 CreateIndexRequest 對象 , 操作 索引基本上是 client.indices().xxx

構建 CreateIndexRequest 對象

@Test
public void test1() {
    CreateIndexRequest request = new CreateIndexRequest("blog1");
    try {
        CreateIndexResponse createIndexResponse =
                client.indices().create(request, RequestOptions.DEFAULT);
        boolean acknowledged = createIndexResponse.isAcknowledged();
        log.info("[create index blog :{}]", acknowledged);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

4.刪除索引 client.indices().delete

構建 DeleteIndexRequest 對象

@Test
public void testDeleteIndex(){
    DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("blog1");
    try {
        AcknowledgedResponse response = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        log.info("[delete index response: {}", response.isAcknowledged());
    } catch (IOException e) {
        e.printStackTrace();
    }

}

4.查詢索引 client.indices().get

構建 GetIndexRequest 對象

@Test
public void testSearchIndex() {

    GetIndexRequest request = new GetIndexRequest("blog1");
    try {
        GetIndexResponse getIndexResponse =
                client.indices().get(request, RequestOptions.DEFAULT);
        Map<String, List<AliasMetaData>> aliases = getIndexResponse.getAliases();
        Map<String, MappingMetaData> mappings = getIndexResponse.getMappings();
        Map<String, Settings> settings = getIndexResponse.getSettings();
        log.info("[aliases: {}]", aliases);
        log.info("[mappings: {}]", mappings);
        log.info("[settings: {}", settings);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

image-20221025110635194

可以根據 response 獲取 aliases , mappings , settings 等等 和 Kibana 中返回的一樣

image-20221025110052958

5.插入文檔 client.index

插入文檔 需要使用 IndexRequest 對象 , 注意 不是 InsertRequest , 不知道爲什麼不這樣定義 感覺會更加好理解

request.source(blogInfoJsonStr, XContentType.JSON);

@Test
public void insertDoc() {
    IndexRequest request = new IndexRequest();
    request.index("blog1").id("1");
    BlogInfo blogInfo =
            new BlogInfo()
                    .setBlogName("Elasticsearch 入門第一章")
                    .setBlogType("Elasticsearch")
                    .setBlogDesc("本篇主要介紹了Elasticsearch 的基本client操作");
    try {
         //提供java 對象的 json str
        String blogInfoJsonStr = objectMapper.writeValueAsString(blogInfo);
        
        request.source(blogInfoJsonStr, XContentType.JSON);
        // 這裏會拋錯 原因是 我的 Elasticsearch 版本8.x 而 使用的 restHighLevel 已經解析不了,因爲新的es已經不推薦使用
        // restHighLevel,而使用 Elasticsearch Java API Client
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        log.info("[Result insert doc :{} ]", index);
    } catch (IOException e) {
    }
}

6.查詢文檔 client.get

注意 getResponse.getSourceAsString() 返回文檔數據

@Test
public void testSelectDoc() {
    GetRequest getRequest = new GetRequest();
    getRequest.index("blog1").id("1");
    try {
        GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
        BlogInfo blogInfo =
                objectMapper.readValue(getResponse.getSourceAsString(), BlogInfo.class);
        log.info("[get doc :{}] ", blogInfo);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

image-20221025110707411

7.刪除文檔 client.delete

注意 刪除文檔 的 response 也解析不了 Elasticsearch 8.x 版本

@Test
public void testDeleteDoc() {
    DeleteRequest deleteRequest = new DeleteRequest();
    deleteRequest.index("blog1").id("1");
    try {
        // 這裏也會拋錯 和上面的一樣
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        log.info("[delete response:{} ]", deleteResponse);
    } catch (IOException e) {
    }
}

總結

本篇主要介紹了 java 操作Elasticsearch 的客戶端 rest-high-level-client 的基本使用 , 如果你是使用springboot 需要注意jar 衝突問題, 後續操作 Elasticsearch 客戶端 逐漸變成 Elasticsearch Java API Client , 不過目前大部分還是使用 rest-high-level-client

歡迎大家訪問 個人博客 Johnny小屋
歡迎關注個人公衆號

歡迎關注個人公衆號

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章