Elasticsearch集成spring boot操作API

本文介绍如何在SpringBoot项目中集成Elasticsearch,并通过Java客户端进行基本的CRUD操作及高级查询。涵盖依赖配置、索引管理、文档操作等核心功能。

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

集成spring boot

找到Elasticsearch Clients

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pp0kz8UG-1668858297271)(ElasticSearch.assets/image-20221113105318578.png)]

选择Java client

在这里插入图片描述

找到所需的maven依赖

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>8.5.0</version>
</dependency>

依赖以下包
在这里插入图片描述

初始化
在这里插入图片描述

在这里插入图片描述

创建配置类

package com.esapi.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
 public RestHighLevelClient restHighLevelClient(){
  RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
          RestClient.builder(
                  new HttpHost("localHost",9200,"http")));
  return  restHighLevelClient;
}
}

具体api测试

创建实体类**user

package com.esapi.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
public class User {
    private  String name;
    private  int age;
}

测试API操作

package com.esapi;


import com.alibaba.fastjson.JSON;
import com.esapi.config.ElasticsearchClientConfig;
import com.esapi.pojo.User;
import lombok.SneakyThrows;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
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.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@SpringBootTest
class EsApiApplicationTests {

@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
    @SneakyThrows
    @Test
    void contextLoads() {


    }


    //创建
    @Test
    public  void  createTest() throws IOException {
       CreateIndexRequest request = new CreateIndexRequest("chen_index");
       CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

    //查询是否存在
    @Test
    public  void  queryTest() throws IOException {
      GetIndexRequest request = new GetIndexRequest("chen_index");
   boolean exists =client.indices().exists(request,RequestOptions.DEFAULT);
        System.out.println(exists);
    }


    //删除
   @Test
    public  void  deleteTest() throws IOException {
       DeleteIndexRequest request = new DeleteIndexRequest("chen_index");
      AcknowledgedResponse delete = client.indices().delete(request,RequestOptions.DEFAULT);
        System.out.println(delete.isAcknowledged());
    }


    //添加文档
    @Test
    public  void addDocument() throws IOException {
        User user = new User("陈平安",3);
        IndexRequest request = new IndexRequest("chen_index");

        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.timeout("1s");

        //把数据放入请求 json
        IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);

        //客户端发送请求 获取响应结果
        IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        // 返回的索引信息 IndexResponse[index=chen_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
        System.out.println(indexResponse.toString());
        //对应命令返回的状态 CREATED 添加
        System.out.println(indexResponse.status());



    }

    //获取文档判断是否存在get/index/doc/1
    @Test
    public  void  testExists() throws IOException {
        GetRequest getRequest = new GetRequest("chen_index","1");
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        getRequest.storedFields("_none_");
        boolean exists = client.exists(getRequest,RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    //获得文档信息
    @Test
    public  void  testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("chen_index","1");

        GetResponse documentFields = client.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.getSourceAsString());
        System.out.println(documentFields);
    }


    //修改文档信息
    @Test
    public  void  testUpdateRequest() throws IOException {

        UpdateRequest updateRequest = new UpdateRequest("chen_index","1");
        User user = new User("宁姚", 14);

        updateRequest.timeout("1s");
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
        UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
        //打印状态 ok
        System.out.println(updateResponse.status());

    }

    //删除文档信息
    @Test
    public  void  test() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("chen_index","1");
        deleteRequest.timeout("1s");
        DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(deleteResponse);

    }


    //批量操作文档信息
    @Test
    public  void  testBulkRequest() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList<User> userArrayList = new ArrayList<>();

        userArrayList.add(new User("陈平安1",14));
        userArrayList.add(new User("陈平安2",14));
        userArrayList.add(new User("陈平安3",14));
        userArrayList.add(new User("陈平安4",14));
        userArrayList.add(new User("陈平安5",14));
        //批量处理请求
        for (int i = 0; i < userArrayList.size(); i++) {
            //批量更新或者批量删除 ,在这里修改对应请求比如 bulkRequest.delete
            bulkRequest.add(
                    new IndexRequest("chen_index")
                            //设置自增id 不设置会默认随机id
                            .id(""+(i+1))
                            .source(JSON.toJSONString(userArrayList.get(i))
                                    ,XContentType.JSON));
            BulkResponse bulk = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            //是否失败,返回false代表成功
            System.out.println(bulk.hasFailures());
        }
    }


    //查询
    //SearchRequest 搜索请求
    //  SearchSourceBuilder条件构造
    //HighlightBuilder 构建高亮
    // TermQueryBuilder 精确查询
    //MatchAllQueryBuilder 匹配所有
    //xxxx  QueryBuilder 对应刚刚的所有命令
    @Test
    public  void  testSearch() throws IOException {
        SearchRequest searchRequest = new SearchRequest("chen_index");

        //构造搜索条件
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //查询条件可以用工具类实现 QueryBuilders
        //termQuery精确查询
        //matchAllQuery 匹配所有

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword","陈平安1");
       // MatchAllQueryBuilder matchAllQuery = QueryBuilders.matchAllQuery();
      //  HighlightBuilder highlightBuilder = sourceBuilder.highlighter();
        sourceBuilder.query(termQueryBuilder);
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
      //  sourceBuilder.highlighter();高亮
        searchRequest.source(sourceBuilder);


        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSONString(searchResponse.getHits()));

        for (SearchHit documentFields : searchResponse.getHits().getHits()) {
            System.out.println(documentFields.getSourceAsMap());
        }
    }




}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值