SpringBoot集成ElasticSearch

  • ElasticSearch

    https://www.elastic.co/guide/index.html

    选择 ElasticSearch的客户端Elasticsearch Clients 选择[Java REST Client 7.13] 使用高级的客户端Java High Level REST Client

    高级客户端封装了低级的客户端,里面包含常见的API

    1.原生的依赖(对基本的依赖进行的封装)

    <dependency>
      <groupId>org.elasticsearch.client</groupId>
      <artifactId>elasticsearch-rest-high-level-client</artifactId>
      <version>7.13.4</version>
    </dependency>
    ​
    high-level-clint是对下面的封装
    ​
    org.elasticsearch.client:elasticsearch-rest-client
    org.elasticsearch:elasticsearch

    2.创建对象

      // 创建对对象
      RestHighLevelClient client = new RestHighLevelClient(
              RestClient.builder(
                      new HttpHost("localhost", 9200, "http"),
                      new HttpHost("localhost", 9201, "http")));
      //关闭客户端
      client.close();

    3.API中的方法

  • Springboot集成ElasticSearch

    1.创建SpringBoot项目 选择导入data中的ElasticSearch依赖

    2.指定版本,使得项目底层使用的版本和本地使用的版本一致.

    <!--在prorerties中指定版本使之与本地的版本一致-->
    <properties>
         <java.version>1.8</java.version>
         <!--自定义版本-->
         <elasticsearch.version> 7.6.1</elasticsearch.version>
    </properties>
    ​
    ​

    3.配置Config把需要的对象交给Spring管理

    package com.qingyan.elasticsearchdemo.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;
    ​
    /**
     * @ClassName ElasticSearchConfig
     * @Author 11
     **/
    ​
    //把需要的对象交给Spring管理
    @Configuration
    public class ElasticSearchConfig {
    ​
        @Bean
        public RestHighLevelClient restHighLevelClient() {
            RestHighLevelClient client = new RestHighLevelClient(
                    RestClient.builder(
                            new HttpHost("172.0.0.1", 9200, "http")));
            return client; 
        }
    }
    ​
    ​

    4.源码中提供的对象(拿来即用)

    //RestClientBuilderConfiguration
    //RestHighLevelClientConfiguration
    //RestClientSnifferConfiguration
    ​
    @Import({RestClientBuilderConfiguration.class, RestHighLevelClientConfiguration.class, RestClientSnifferConfiguration.class})
    public class ElasticsearchRestClientAutoConfiguration {
        public ElasticsearchRestClientAutoConfiguration() {
        }
    }

    5.API中的方法

    package com.qingyan.elasticsearchdemo;
    ​
    ​
    import com.alibaba.fastjson.JSON;
    import com.qingyan.elasticsearchdemo.domain.User;
    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.RequestOptions;
    import org.elasticsearch.client.RestHighLevelClient;
    import org.elasticsearch.client.indices.CreateIndexRequest;
    import org.elasticsearch.client.indices.CreateIndexResponse;
    import org.elasticsearch.client.indices.GetIndexRequest;
    import org.elasticsearch.common.unit.TimeValue;
    import org.elasticsearch.common.xcontent.XContentType;
    import org.elasticsearch.index.query.MatchAllQueryBuilder;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.elasticsearch.index.query.TermQueryBuilder;
    import org.elasticsearch.search.SearchHit;
    import org.elasticsearch.search.SearchHits;
    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 javax.naming.directory.SearchResult;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Map;
    import java.util.concurrent.TimeUnit;
    ​
    ​
    @SpringBootTest
    class ElasticsearchDemoApplicationTests {
    ​
        //这两个是等价的 当不想使用原来的名字时可以用@Qualifier注解来指定
    /*
        @Autowired
        private RestHighLevelClient restHighLevelClient;
    */
    ​
        @Autowired
        @Qualifier("restHighLevelClient")//我们自己对应的bean方法名字,对应上面的配置类
        private RestHighLevelClient client;
    ​
    ​
        //创建索引CreateIndexRequest
        @Test
        void testCreateIndex() throws IOException {
            //创建索引
            CreateIndexRequest request = new CreateIndexRequest("test_index");
            //执行请求indices()
            CreateIndexResponse createIndexResponse =
                    client.indices().create(request, RequestOptions.DEFAULT);
    ​
            System.out.println(createIndexResponse);
        }
    ​
    ​
        //获取索引是否存在 GetIndexRequest
        @Test
        void testExistIndex() throws IOException {
            GetIndexRequest request = new GetIndexRequest("test_index");
            boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
            System.out.println(exists);
    ​
        }
    ​
        //删除创建的索引 DeleteIndexRequest
        @Test
        void testDeleteIndex() throws IOException {
            DeleteIndexRequest request = new DeleteIndexRequest("test_index");
            //根据返回的delete的值来判断索引是否删除成功
            AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
            System.out.println(delete);
        }
    ​
        //添加文档
        @Test
        void testAddDocument() throws IOException {
            User user = new User("张三", 20);
            IndexRequest request = new IndexRequest("test_index");
            request.id("1");
            request.timeout(TimeValue.timeValueSeconds(1));
            request.timeout("2s");
    ​
            //将获取到的数据封装到对象中装换为json对象
            request.source(JSON.toJSONString(user), XContentType.JSON);
            //发送请求获取结果
            IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
    ​
            System.out.println(indexResponse.toString());
            //返回的状态
            System.out.println(indexResponse.status());
    ​
        }
    ​
        //获取文档判断是否存在 get /index/doc/1
        @Test
        void testIsExist() throws IOException {
            GetRequest getRequest = new GetRequest("test_index", "1");
            //为了提高效率 不获取上下人了
            getRequest.fetchSourceContext(new FetchSourceContext(false));
            getRequest.storedFields("_none_");
    ​
            boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);
            System.out.println(exists);
    ​
        }
    ​
    ​
        //获取文档信息
        @Test
        void testGetDocument() throws IOException {
            GetRequest getRequest = new GetRequest("test_index", "1");
    ​
            GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
            // Map<String, Object> source = getResponse.getSource();
            String sourceAsString = getResponse.getSourceAsString();
            System.out.println(sourceAsString);
        }
    ​
        //更新文档信息
        @Test
        void testUpdateDocument() throws IOException {
            UpdateRequest updateRequest = new UpdateRequest("test_index", "1");
            updateRequest.timeout("1s");
            User user = new User("lisi", 21);
            updateRequest.doc(JSON.toJSONString(user));
            UpdateResponse updateResponse = client.update(updateRequest, RequestOptions.DEFAULT);
            System.out.println(updateResponse.status());
        }
    ​
        //删除文档信息
        @Test
        void testDeleteDocument() throws IOException {
            DeleteRequest deleteRequest = new DeleteRequest("test_index", "1");
            DeleteResponse deleteResponse = client.delete(deleteRequest, RequestOptions.DEFAULT);
            System.out.println(deleteResponse.status());
        }
    ​
        //批量插入数据
        @Test
        void testBulkRequest() throws IOException {
            BulkRequest bulkRequest = new BulkRequest();
            bulkRequest.timeout("10s");
    ​
            ArrayList<User> list = new ArrayList<>();
            list.add(new User("张三",21));
            list.add(new User("张三",21));
            list.add(new User("张三",21));
    ​
            for (int i = 0; i < list.size(); i++) {
                bulkRequest.add(
                        new IndexRequest("test_index")
                                .id("" + (i + 1))
                                .source(JSON.toJSONString(list.get(i)), XContentType.JSON));
            }
            BulkResponse bulkResponses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println(bulkResponses);
    ​
        }
        //ElasticSearch中的重点是查询
        //查询
        @Test
        void testQuery() throws IOException {
            //搜索请求
            SearchRequest searchRequest = new SearchRequest("Test_index");
            //构建查询条件
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //构建高亮
            //HighlightBuilder highlight = SearchSourceBuilder.highlight();
            //查询条件 使用QueryBuilder 工具类实现
            //精确查询
            TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangwu");
            //匹配所有
           // MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
    ​
            sourceBuilder.query(termQueryBuilder);
            sourceBuilder.timeout(new TimeValue(10,TimeUnit.SECONDS));
    ​
    ​
            searchRequest.source(sourceBuilder);
    ​
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            //查询的数据都在getHits()
            SearchHits hits = searchResponse.getHits();
    ​
            System.out.println(JSON.toJSONString(hits));
    ​
            //searchResponse.getHits().getHits()获取searchResponse.getHits()中的每一个数据
            SearchHit[] hits1 = searchResponse.getHits().getHits();
            for (int i = 0; i < hits1.length; i++) {
                System.out.println(hits1[i].getSourceAsMap());
            }
    ​
        }
    ​
    ​
    }
     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值