springboot集成elasticsearch(10)

本文详细介绍了如何在Maven和Gradle项目中配置Elasticsearch高阶客户端,包括创建、检查、删除索引,以及执行文档的CRUD操作,如添加用户数据、更新和删除,还涉及Fastjson的集成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引入依赖

在maven项目管理中的pom.xml加入以下内容:

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

在gradle项目中的build.gradle文佳中添加下面的内容:

dependencies {
    compile 'org.elasticsearch.client:elasticsearch-rest-high-level-client:7.6.1'
}

注意:elasticsearch依赖版本号需要和elasticsearch服务版本号保持一致

初始化

编写ElasticSearchClientConfig配置类

package mybatis_plus.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 ElasticSearchClientConfig {
    @Bean
    RestHighLevelClient restHighLevelClientConfig(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
        return client;
    }
}

索引API操作

  • 创建索引
@Test
    void createIndex() throws IOException {
        CreateIndexRequest index = new CreateIndexRequest("user");
        CreateIndexResponse createIndexResponse = client.indices().create(index, RequestOptions.DEFAULT);
        System.out.println(createIndexResponse);
    }
  • 判断所引是否存在,并获取存在索引
 @Test
    void existsIndex() throws IOException {
        //创建请求内容对象
        GetIndexRequest index = new GetIndexRequest("user");
        //判断
        boolean exists = client.indices().exists(index, RequestOptions.DEFAULT);
        System.out.println(exists);
        GetIndexResponse getIndexResponse = client.indices().get(index, RequestOptions.DEFAULT);
        System.out.println(getIndexResponse);
    }
  • 删除索引
    @Test
    void deleteIndex() throws IOException {
        //创建请求内容对象,删除时索引需要存在
        DeleteIndexRequest index = new DeleteIndexRequest("posts");
        //删除操作
        AcknowledgedResponse delete = client.indices().delete(index, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());

    }

文档API操作

  • 添加阿里巴巴fastjson依赖
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.73</version>
        </dependency>
  • 创建文档:一个IndexRequest需要以下三个参数
    • 索引:表明要操作的索引是那个索引
    • 文档id:可以唯一确定文档记录,当id不设置是,默认使用UUID
    • 文档源:文档内容,一条记录的内容,以字符串形式提供
  • 创建JSON格式文档是可以使用以下几种方法:
    • Map:文档内容可以通过map自动转换json格式
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
IndexRequest indexRequest = new IndexRequest("user")
    .id("1").source(jsonMap); 
  • XContentBuilder:通过XContentBuilder对象,可以帮助构建一个JSON文件
IndexRequest indexRequest = new IndexRequest("user")
    .id("1")
    .source("user", "kimchy",
        "postDate", new Date(),
        "message", "trying out Elasticsearch"); 

创建文档集成测试

 @Test
    void createDocument() throws IOException {
        //从数据库中查询用户
        User user = userMapper.selectById(4l);
//        System.out.println(user);
        //构建创建的文档内容
        IndexRequest request = new IndexRequest("user");
        request.timeout("1s");
        request.id("1");
        request.source(JSON.toJSONString(user), XContentType.JSON);
        //发送请求
        IndexResponse index = client.index(request, RequestOptions.DEFAULT);
        System.out.println(index.status());
        System.out.println(index);


    }
  • 更新文档记录
 @Test
    void updateDocument() throws IOException {
        //从数据库中查询用户
        User user = userMapper.selectById(5l);
//        System.out.println(user);
        //构建创建的文档内容
        UpdateRequest request = new UpdateRequest("user", "1");
        request.timeout("1s");
//        request.id("1");
        request.doc(JSON.toJSONString(user), XContentType.JSON);
        //发送请求
        UpdateResponse index = client.update(request, RequestOptions.DEFAULT);
        System.out.println(index.status());
        System.out.println(index.toString());


    }
  • 删除文档记录
  @Test
        void deleteDocument() throws IOException {
            //构建创建的文档内容
        DeleteRequest request = new DeleteRequest("user", "1");
        request.timeout("1s");
        DeleteResponse delete = client.delete(request, RequestOptions.DEFAULT);
         System.out.println(delete.status());
         System.out.println(delete.toString());


     }

  • 批量插入
@Test
    void batchAdd() throws IOException {
        //构建批量请求体
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        List<User> list = userMapper.selectList(null);
        for (User user : list) {
            IndexRequest request = new IndexRequest("user");
            request.timeout("1s");
            request.source(JSON.toJSONString(user),XContentType.JSON);
            bulkRequest.add(request);
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(!bulk.hasFailures());
        System.out.println(bulk.toString());


    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

heromps

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值