springboot整合Elasticsearch

本文详细介绍了如何在Springboot项目中集成Elasticsearch,包括创建依赖、配置工具、实现索引操作(创建、删除、存在性检查)、文档管理(添加、查询、删除和修改)、批量操作以及高级查询功能的演示。
摘要由CSDN通过智能技术生成

1 创建一个Springboot工程并加入相关的依赖

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

3 进行相关对ES操作  3.1 操作索引---创建索引

3.2 操作索引--删除索引

3.3 索引操作--判断索引是否存在

3.4 操作文档---添加文档

3.5 查询文档--id

3.6 判断文档是否存在

3.7 删除文档

3.8 修改文档

3.9 批量添加文档

3.10 复杂查询


1 创建一个Springboot工程并加入相关的依赖

<dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <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>
    </dependencies>

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


@Configuration
public class ESConfig {
    //该对象可以对我们的ES进行相关的操作
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));
        return client;
    }
}

3 进行相关对ES操作  
3.1 操作索引---创建索引

  @Autowired
    private RestHighLevelClient client  
 
//创建索引
    @Test
    void testCreateIndex() throws  Exception {
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("xxx");
        CreateIndexResponse response = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());
    }

3.2 操作索引--删除索引

//删除索引
    @Test
    public void tetsDeleteIndex()throws  Exception{
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("xxx");
        AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }

3.3 索引操作--判断索引是否存在

//判断是否存在
    @Test
    public void testIndexExists()throws  Exception{
        GetIndexRequest getIndexRequest = new GetIndexRequest("xxx");
        boolean exists = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

3.4 操作文档---添加文档

 //添加文档--PUT /索引/1 {name:"",age:"",address:""}
 
//添加
    @Test
    public void  testIndexDoc() throws  Exception{
        IndexRequest indexRequest = new IndexRequest("sss");
        indexRequest.id("2");
        indexRequest.source(JSON.toJSONString(new User("李四","北京",21)), XContentType.JSON);
        IndexResponse index = client.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.getResult());
    }

3.5 查询文档--id

 //获取文档 GET /索引/_doc/1
    @Test
    public void testGetDoc()throws  Exception{
 
        GetRequest getRequest = new GetRequest("xzj");
        getRequest.id("1");
        GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
        String string = response.getSourceAsString();
        User user = JSON.parseObject(string, User.class);
        System.out.println(user);
        Map<String, Object> map = response.getSourceAsMap();
        System.out.println(map);
 
    }

3.6 判断文档是否存在

  //判断索引文档是否存在
    @Test
    public void testExist()throws Exception{
        GetRequest getRequest = new GetRequest("xxx");
        getRequest.id("2");
        boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

3.7 删除文档

 //删除
    @Test
    public void testDelete()throws  Exception{
        DeleteRequest deleteRequest = new DeleteRequest("xx");
        deleteRequest.id("2");
        DeleteResponse delete = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.getResult());
    }

3.8 修改文档

  @Test
    public void testUpdate() throws  Exception{
        UpdateRequest updateRequest = new UpdateRequest("sss","2");
        User user = new User();
        user.setAge(18);
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
        UpdateResponse update = client.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.getResult());
    }

3.9 批量添加文档

 //批量添加文档
    @Test
    public void testBulk()throws  Exception{
        BulkRequest bulkRequest = new BulkRequest("xzj");
        List<User> list = new ArrayList<>();
        list.add(new User("2","李四","上海",12));
        list.add(new User("3","王五","北京",13));
        list.add(new User("4","小王","苏州",16));
        list.add(new User("5","赵六","南京",26));
        list.add(new User("6","小赵","长沙",23));
        list.stream().forEach(item->bulkRequest.add(new IndexRequest()
                .id(item.getId()).source(JSON.toJSONString(item),XContentType.JSON)));
 
//        for (User user:list){
          IndexRequest indexRequest = new IndexRequest();
          indexRequest.id(user.getId());
          indexRequest.source(JSON.toJSONString(user),XContentType.JSON);
          bulkRequest.add(indexRequest);
//          bulkRequest.add(new IndexRequest().id(user.getId()).source(JSON.toJSONString(user),XContentType.JSON));
//
//        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());
    }

3.10 复杂查询

   //搜索查询---GET /索引/_search
    // {
    //     "query":{
    //         "":{}
//          },
       //  "from":
     //    "size":
    //     "_source":["",""],
    //     "sort":{}

    // }

    //1. 搜索请求对象SearchRequest
    //2. 构建一个条件对象SearchSourceBuilder
    //3. 把条件对象放入搜索请求对象中
    //4. 执行搜索功能

 //复杂查询
    @Test
    public void testSearch()throws  Exception{
        SearchRequest searchRequest = new SearchRequest("xzj");
        SearchSourceBuilder searchBuilder = new SearchSourceBuilder();
        MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", "王");
        searchBuilder.query(matchQuery);
        searchBuilder.from(0);
        searchBuilder.size(2);
        searchBuilder.sort("age");
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<p color='red'>");
        highlightBuilder.postTags("</p>");
        searchBuilder.highlighter(highlightBuilder);
 
        searchRequest.source(searchBuilder);
        SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
 
        System.out.println("总条数:"+search.getHits().getTotalHits().value);
        SearchHit[] hits = search.getHits().getHits();
        Arrays.stream(hits).forEach(item-> System.out.println(item.getSourceAsString()));
        Arrays.stream(hits).forEach(item-> System.out.println(item.getHighlightFields()));
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值