SpringBoot整合Elasticsearch

本文详细介绍了如何在Spring Boot项目中整合Elasticsearch,从创建工程、添加依赖到配置ES工具类,再到使用RestHighLevelClient进行索引管理和文档操作,包括创建、查询、删除、修改及批量操作。同时,文章还涉及了复杂的查询功能,如匹配查询、精确查询、分页、排序和高亮显示。最后,通过一个爬取京东数据的综合案例展示了实际应用。

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

目录

创建spring boot工程

加入依赖

 创建一个配置,获取ES工具类对象。

RestHighLevelClient

索引管理

创建索引

删除索引 

判断索引是否存在 

 共同点:

文档操作

添加文档

 查询文档

判断文档是否存在  

 删除文档

 修改文档

批量添加文档

 复杂查询

匹配查询match 

精确查询

分页 

排序 

高亮 


创建spring boot工程

加入依赖

 创建一个配置,获取ES工具类对象。

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(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
        return client;
    }

}

RestHighLevelClient

RestHighLevelClient的API作为ElasticSearch备受推荐的客户端组件,其封装系统操作ES的方法,包括索引结构管理,数据增删改查管理,常用查询方法,并且可以结合原生ES查询原生语法,功能十分强大。

 

索引管理

创建索引

索引名不能有大写字母

@Test
    void createIndex() throws IOException {
        /*该类把索引的信息都封装                                             索引名*/
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("ytrtest");
        /*创建索引*/                                                    /*索引名*/                 /*基本固定写这个*/
        CreateIndexResponse r = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
                            /*此方法查看是否创建成功*/
        System.out.println(r.isAcknowledged());

    }

删除索引 

@Test
    void delereIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("ytrtest");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

判断索引是否存在 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值