springboot使用es入门(6.3.2版本)

Posted 好大的月亮

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot使用es入门(6.3.2版本)相关的知识,希望对你有一定的参考价值。

使用前先对照springboot和es和spring-data之间的版本关系

https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#preface.versions

springboot使用es

es有两个端口可以用9200和9300(TCP端口后期es官方弃用),这里整合就使用9200了。

这里工具类采用es官方提供的.使用Java High Level REST Client
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/index.html

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

es的启动类配置
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high-getting-started-initialization.html

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));

配置java bean

package com.fchan.espractice.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 ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9222, "http")));

        return client;
    }


}

增删改查demo

package com.fchan.espractice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fchan.espractice.pojo.User;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.FetchSourceContext;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@SpringBootTest
class EsPracticeApplicationTests {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private ObjectMapper objectMapper;


    //测试创建索引
    @Test
    public void testCreateIndex() throws IOException {
        //创建索引请求
        CreateIndexRequest indexRequest = new CreateIndexRequest("fchan_test");
        //执行创建请求 IndicesClient
        Header header = new BasicHeader("Content-Type", "application/json");
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(indexRequest, header);

        System.out.println(objectMapper.writeValueAsString(createIndexResponse));

    }

    //测试索引是否存在
    @Test
    public void testExistindex() throws IOException {
        GetIndexRequest request = new GetIndexRequest();
        request.indices("fchan_test");

        //执行创建请求 IndicesClient
        Header header = new BasicHeader("Content-Type", "application/json");
        boolean exists = restHighLevelClient.indices().exists(request, header);


        System.out.println(exists);
    }

    //测试删除索引
    @Test
    public void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("fchan_test");
        //执行创建请求 IndicesClient
        Header header = new BasicHeader("Content-Type", "application/json");
        DeleteIndexResponse delete = restHighLevelClient.indices().delete(request, header);

        System.out.println(objectMapper.writeValueAsString(delete));


    }

    //测试添加文档
    @Test
    public void testAddDocument() throws JsonProcessingException {
        User user = new User("张11", 3, "aaa");
        //请求要操作的索引库
        IndexRequest request = new IndexRequest("fchan_test");

        //设置请求的规则  put /fchan_test/_doc/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
        request.type("user_2");

        //将数据放入请求
        request.source(objectMapper.writeValueAsString(user), XContentType.JSON);

        try {
            //发送请求获取响应结果
            Header header = new BasicHeader("Content-Type", "application/json");
            IndexResponse index = restHighLevelClient.index(request, header);
            System.out.println(objectMapper.writeValueAsString(index));
        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    //查询文档是否存在
    @Test
    public void testGetIndex() throws IOException {
        GetRequest request = new GetRequest("fchan_test", "user", "1");
        //是否返回 _source
        request.fetchSourceContext(new FetchSourceContext(false));
        //可以指定返回的字段, 即 select xx,xx,xx from xx_table
        //request.storedFields("_none_");

        Header header = new BasicHeader("Content-Type", "application/json");
        boolean exists = restHighLevelClient.exists(request, header);

        System.out.println(exists);

    }


    //查询文档
    @Test
    public void testQueryDocument() throws IOException {
        GetRequest request = new GetRequest("fchan_test", "user", "1");

        Header header = new BasicHeader("Content-Type", "application/json");
        GetResponse documentFields = restHighLevelClient.get(request, header);

        System.out.println(objectMapper.writeValueAsString(documentFields));


    }


    //更新文档
    @Test
    public void testUpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("fchan_test", "user", "1");
        request.timeout("1s");

        User user = new User("张3333", 33, "11");
        request.doc(objectMapper.writeValueAsString(user), XContentType.JSON);

        Header header = new BasicHeader("Content-Type", "application/json");
        UpdateResponse update = restHighLevelClient.update(request, header);

        System.out.println(objectMapper.writeValueAsString(update));


    }


    //删除文档
    @Test
    public void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("fchan_test", "user", "1");
        request.timeout(TimeValue.timeValueMillis(1));

        Header header = new BasicHeader("Content-Type", "application/json");
        DeleteResponse delete = restHighLevelClient.delete(request, header);

        System.out.println(objectMapper.writeValueAsString(delete));
    }


    //批量新增
    @Test
    public void testBatchAddDocument() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (int i = 0; i < 10; i++) {
            //如果存在id一样的数据,那么此次批量新增的时候会冲掉之前的数据,新增的时候有些字段没给值,那么会将这些字段的值冲掉->null
            IndexRequest request = new IndexRequest("fchan_test", "user");
            //这里不给id的话,es会自己给一个随机id
            request.id("" + (i + 1));
            request.source(objectMapper.writeValueAsString(new User("陈" + (i + 1), i + 1)), XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, new BasicHeader("Content-Type", "application/json"));
        //是否失败 false代表成功,因为这个方法是 hasFailures 就是问有没有失败的,没有失败的那就是false啊
        System.out.println(bulk.hasFailures());
        //全部的返回结果
        System.out.println(objectMapper.writeValueAsString(bulk));
    }


    //带条件查询
    @Test
    public void testQuery() throws IOException {
        SearchRequest searchRequest = new SearchRequest("fchan_test");
        //构建查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //高亮
        //searchSourceBuilder.highlighter()

        //精确匹配
        //TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张5");
        //通配符查询,效率比较低
        WildcardQueryBuilder wildcardQuery = QueryBuilders.wildcardQuery("name.keyword", "*张5*");
        //匹配所有
        //MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        //searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.query(wildcardQuery);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        searchRequest.source(searchSourceBuilder);

        Header header = new BasicHeader("Content-Type", "application/json");
        SearchResponse search = restHighLevelClient.search(searchRequest, header);
        System.out.println(objectMapper.writeValueAsString(search));
        System.out.println("======================================");
        for (SearchHit hit : search.getHits().getHits()) {
            System.out.println(hit.getSourceAsMap());
        }


    }


    //批量删除,这里采用先查询出id,再批量删除
    @Test
    public void testBatchDeleteDocument() throws IOException {

        SearchRequest searchRequest = new SearchRequest("fchan_test");
        searchRequest.types("user");

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.timeout(TimeValue.MINUS_ONE);

        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "张");
        searchSourceBuilder.query(matchQueryBuilder);

        searchRequest.source(searchSourceBuilder);

        Header header = new BasicHeader("Content-Type", "application/json");
        SearchResponse search = restHighLevelClient.search(searchRequest, header);


        BulkRequest bulkRequest = new BulkRequest();
        for (SearchHit hit 001.camunda入门(springboot集成篇)

springboot操作Elasticsearch

ElasticSearch_10_ES和SpringBoot版本对应关系

ElasticSearch_10_ES和SpringBoot版本对应关系

springboot 项目依赖 es包版本异常

ElaticSearch 学习三(springboot 集成ES 7.6.1)