RestHighLevelClient快速入门

创建RestHighLevelClient对象

elasticsearch:
  host: 101.35.247.167
  port: 9200

package com.zhang.elasticsearch.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@ConfigurationProperties(prefix = "elasticsearch")
@Configuration
@Component
public class ElasticsearchConfig {
    private String host;
    private int port;
    private String scheme = "http";

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setScheme(String scheme) {
        this.scheme = scheme;
    }

    @Bean
    public RestHighLevelClient Client() {
        return new RestHighLevelClient(RestClient.builder(new HttpHost(
                host, port, scheme)));

    }
}

package com.zhang.elasticsearch;

import com.alibaba.fastjson.JSON;
import com.zhang.elasticsearch.domain.User;

import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
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.client.*;
import org.elasticsearch.client.ml.PostDataRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.Map;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;


@SpringBootTest
class ElasticsearchApplicationTests {
    @Autowired
    RestHighLevelClient client;

    @Test
    void contextLoads() {
        System.out.println(client);
    }

    
    //创建索引  IndicesClient对索引进行CRUD,IndexRequest则是对文档进行CRUD
    @Test
    public void addIndex() throws IOException {
        //获得索引库对象
        IndicesClient indices = client.indices();

        //创建索引请求
        CreateIndexRequest index = new CreateIndexRequest("zyp");

        //创建索引
        CreateIndexResponse result = indices.create(index, RequestOptions.DEFAULT);

        System.out.println(result.isAcknowledged());
    }
    /* 创建映射 analyzer为制定ik分词器
     * @Author: zyp
     * @Date:   2021/12/14 17:15
     * @Param:  []
     * @Return: void
     * @Description
     */
    @Test
    public void createIndex() throws IOException {
        //获得所有客户端
        IndicesClient indices = client.indices();
        //创建添加映射请求
        PutMappingRequest putMappingReq = new PutMappingRequest("zyp");
        XContentBuilder mapping;
        //构造映射
        //{"properties":{"name":{"type":"text"},"age":{"type":"long"},"adr":{"type":"text","analyzer:"ik_smart""}}} startObject对应左花括号,endObject对应有括号
        mapping = jsonBuilder().startObject().startObject("properties").startObject("name").
                field("type", "text").endObject()
                .startObject("age").field("type", "long").endObject()
                .startObject("adr").field("type", "text").field("analyzer", "ik_smart").endObject()
                .endObject().endObject();
        putMappingReq.type("docs");
        putMappingReq.source(mapping);
        AcknowledgedResponse acknowledgedResponse = indices.putMapping(putMappingReq, RequestOptions.DEFAULT);
        System.out.println(acknowledgedResponse.isAcknowledged());
    }

    /* 添加文档
     * @Author: zyp
     * @Date:   2021/12/14 17:15
     * @Param:  []
     * @Return: void
     * @Description
     */
    @Test
    public void addDoc() throws IOException {
        //创建要存入的对象
        User user = new User();
        user.setName("张三");
        user.setAge(23);
        user.setAddress("永丰");

        //将对象转为json字符串
        String UserJson = JSON.toJSONString(user);

        //创建索引请求
        IndexRequest indexRequest = new IndexRequest("zyp").id("6").source(UserJson, XContentType.JSON);

        //创建文档
        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.getResult());
    }

    @Test
    /* 修改文档,添加文档,存在则为修改 其中version对应该文档的版本号
     * @Author: zyp
     * @Date:   2021/12/14 17:14
     * @Param:  []
     * @Return: void
     * @Description
     */
    public void updateDoc() throws IOException {
        //创建要存入的对象
        User user = new User();
        user.setName("张三");
        user.setAge(23);
        user.setAddress("永丰县");

        //讲对象转为json字符串
        String UserJson = JSON.toJSONString(user);

        //获得更新索引请求对象
        IndexRequest updateRequest = new IndexRequest("zyp").id("6").source(UserJson, XContentType.JSON);
        IndexResponse index = client.index(updateRequest, RequestOptions.DEFAULT);

        System.out.println(index.getResult());
    }

    @Test
    /*查询文档
     * @Author: zyp
     * @Date:   2021/12/14 17:14
     * @Param:  []
     * @Return: void
     * @Description
     */
    public void getDoc() throws IOException {
        //获得查询索引的请求对象
        GetRequest gerRequest = new GetRequest("zyp").id("6");

        //获得文档对象
        GetResponse doc = client.get(gerRequest, RequestOptions.DEFAULT);

        //获得文档数据
        System.out.println(doc.getSourceAsString());
    }

    @Test
    /* 删除文档信息
     * @Author: zyp
     * @Date:   2021/12/14 17:13
     * @Param:  []
     * @Return: void
     * @Description
     */
    public void delDoc() throws IOException {
        //获得删除的索引请求对象
        DeleteRequest delRequest = new DeleteRequest("zyp").id("6");

        //删除文档
        DeleteResponse delete = client.delete(delRequest, RequestOptions.DEFAULT);
        System.out.println(delete.getIndex());
    }

    /*删除索引
     * @Author: zyp
     * @Date:   2021/12/14 17:13
     * @Param:  []
     * @Return: void
     * @Description
     */
    @Test
    public void delIndex() throws IOException {
        IndicesClient indices = client.indices();
        DeleteIndexRequest delReq = new DeleteIndexRequest("zyp");
        AcknowledgedResponse delete = indices.delete(delReq, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }
    //从数据库中批量导入数据到es
   @Test
    void contextLoads() throws IOException {
        //查询mysql中所有数据
        List<Goods> goodes = goodsMapper.listGoods();

        //创建批量处理对象
        BulkRequest bulkRequest = new BulkRequest();

        //循环添加新增处理请求
        for (Goods goods : goodes) {
            goods.setSpec(JSON.parseObject(goods.getSpecStr(), Map.class));
            String goodsJson = JSON.toJSONString(goods);
            IndexRequest indexRequest = new IndexRequest("goods").id(goods.getId() + "").source(goodsJson, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        //提交批量处理对象
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);

        //查看添加状态
        System.out.println(bulk.status());

    }


}

### 使用 RestHighLevelClient 进行开发 #### 添加 Maven 依赖 为了使用 `RestHighLevelClient`,需要先配置项目的Maven依赖,在父工程的`pom.xml`文件中添加如下属性: ```xml <properties> <elasticsearch.version>7.17.18</elasticsearch.version> </properties> <dependencies> <!-- Elasticsearch High Level REST Client --> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency> </dependencies> ``` 这段代码定义了Elasticsearch版本并引入了必要的客户端库[^1]。 #### 创建客户端实例 下面是一个简单的例子展示如何创建一个`RestHighLevelClient`对象,并验证其能否成功连接到本地运行的Elasticsearch服务: ```java import org.apache.http.HttpHost; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; public class ClientTest { public static void main(String[] args) throws Exception { try (RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("localhost", 9200, "http")))) { // 打印client信息表示已建立连接 System.out.println(client); // 此处可以加入更多逻辑... } } } ``` 此程序会尝试与位于`localhost:9200`上的Elasticsearch节点建立联系,并打印出代表该链接状态的对象描述字符串[^2]。 #### 发送HTTP请求 由于Elasticsearch本质上是基于RESTful风格的服务平台,所以Java API的主要作用就是辅助开发者更便捷地构造相应的HTTP命令。这意味着掌握基本的HTTP指令对于理解和运用这些API至关重要[^3]。 例如,如果想要执行一些具体的操作如索引管理或是文档增删改查,则可以通过调用`RestHighLevelClient`所提供的相应方法来实现。以下是几个常见的操作示例: - **获取集群健康状况** ```java GetRequest getRequest = new GetRequest("_cluster/health"); ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT); System.out.println(response.getStatus()); ``` - **创建新索引** ```java CreateIndexRequest request = new CreateIndexRequest("test-index"); request.settings(Settings.builder() .put("index.number_of_shards", 1) .put("index.number_of_replicas", 0)); AcknowledgedResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); if(createIndexResponse.isAcknowledged()){ System.out.println("Index created successfully."); } else{ System.out.println("Failed to create index."); } ``` 以上仅作为入门指导的一部分内容,实际应用过程中还需要深入研究官方文档以及不断实践探索其他高级特性[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值