03Springboot集成ElasticSearch

1.导入相关依赖
 <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-elasticsearchartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.74version>
        dependency>
    dependencies>

注意的是:elasticSearch的版本如果与客户端不一致需要自定义版本
03Springboot集成ElasticSearch_第1张图片

03Springboot集成ElasticSearch_第2张图片

2.通过配置类注入restHighLevelClient

注意添加注解 @Configuration,这样可以通过@Autowired来注入

@Configuration
public class ElasticSearchConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client=new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http"))
        );
          return client;
    }
}

3.索引测试

1.创建索引
需要注入RestHighLevelClient

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    void testCreateIndex() throws IOException {
        CreateIndexRequest indexRequest = new CreateIndexRequest("wang_index");
        CreateIndexResponse response = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        System.out.println(response);
    }
}

测试:
后台输出日志:
03Springboot集成ElasticSearch_第3张图片
可视化界面查看:
03Springboot集成ElasticSearch_第4张图片

2.索引是否存在

若索引存在则返回true,不存在则false

@Test
    void ExistIndex() throws IOException{
        GetIndexRequest request=new GetIndexRequest("wang_index");
        boolean exists = restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);
        System.out.println(exists);
    }

测试:
03Springboot集成ElasticSearch_第5张图片

3.删除索引

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

注意观察返回对象与在可视化页面操作删除索引的过程是对应的上的。
测试:
03Springboot集成ElasticSearch_第6张图片
发现索引已经删除

4.文档测试

1.添加文档

新建实体类User并且导入AlibabaFastJson的依赖

@Test
    void addDocument() throws IOException{
    //创建对象
        User user=new User("wangcj",23);
        //创建请求
        IndexRequest request=new IndexRequest("wang_index");
        //规则:put/wang_index/1
        request.id("1");
        request.timeout(TimeValue.timeValueSeconds(1));
//        request.timeout("1");
//将数据放入到Json
        request.source(JSON.toJSONString(user), XContentType.JSON);
//客户端发送请求,获取响应结果
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.status()+response.toString());
    }
}

测试:
03Springboot集成ElasticSearch_第7张图片
03Springboot集成ElasticSearch_第8张图片
2.获取文档是否存在

    @Test
    //规则:get/index/_doc/1
    void existDocument() throws IOException{
        GetRequest getRequest=new GetRequest("wang_index","1");
        getRequest.storedFields("name","age");
        //不返回上下文的内容
        getRequest.fetchSourceContext(new FetchSourceContext(false));
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }
}

测试:
03Springboot集成ElasticSearch_第9张图片
3.获取文档信息

    @Test
    void getDocument() throws IOException{
        GetRequest getRequest=new GetRequest("wang_index","1");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.getSourceAsString());//打印文档内容
        System.out.println(documentFields);
//返回内容与命令一样
    }
}

测试:
03Springboot集成ElasticSearch_第10张图片
4.更新文档信息

    void updateDocument() throws IOException{
        UpdateRequest updateRequest=new UpdateRequest("wang_index","1");
        updateRequest.timeout("1s");
        User user=new User("wangcj",25);
        updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.status());
    }
}

测试:
03Springboot集成ElasticSearch_第11张图片
5.删除文档

   @Test
    void deleteDocument() throws IOException{
        DeleteRequest deleteRequest=new DeleteRequest("wang_index","1");
        deleteRequest.timeout("1s");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }

6.批量插入

@Test
    void bulkAddDocuments() throws IOException{//批量操作
        BulkRequest bulkRequest=new BulkRequest();
        List<User> users=new ArrayList<>();
        users.add(new User("wangcjj",23));
        users.add(new User("chenyh",21));
        for (int i = 0; i < users.size(); i++) {
            bulkRequest.add(new IndexRequest("wang_index")
                    .id(""+(i+1))
                    .source(JSON.toJSONString(users.get(i)),XContentType.JSON));
        }
//批处理请求
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.hasFailures());//是否失败 false则代表没有失败
    }

测试:
03Springboot集成ElasticSearch_第12张图片
7.批量查询
//查询
//searchRequest搜索请求
//searchSourceBuild 条件构造
//highLightBuild 构建高亮

@Test
    void bulkQueryDocument() throws IOException{//批量查询操作
        SearchRequest searchRequest=new SearchRequest();
        //构建搜索条件
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
//查询条件我们可以使用QueryBuild工具来实现
        //精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "wangcj");
        //查询全部
        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        searchSourceBuilder.timeout(TimeValue.MINUS_ONE);

        searchSourceBuilder.query(matchAllQueryBuilder);
        searchRequest.source(searchSourceBuilder);

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

        SearchHit[] hits = search.getHits().getHits();
        for (SearchHit hit: hits
             ) {
            System.out.println(hit.getSourceAsMap());
        }
    }

你可能感兴趣的:(java,elasticsearch,springboot)