SpringBoot整合ElasticSearch

SpringBoot整合ElasticSearch,第1张

SpringBoot整合ElasticSearch SpringBoot整合ElasticSearch 一、Maven依赖

创建SpringBoot项目,并导入依赖

        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
二、配置 1、配置类

非SpringBoot项目,可通过配置类的方式配置ES

    @Bean
    public RestHighLevelClient restHighLevelClient(){
        HttpHost httpHost = new HttpHost("localhost", 9200, "http");
        RestClientBuilder clientBuilder = RestClient.builder(httpHost);
        return new RestHighLevelClient(clientBuilder);
    }
2、配置文件

SpringBoot项目可通过配置文件配置ES

spring:
  elasticsearch:
    rest:
      uris: http://localhost:9200
三、索引 1、创建索引
    @PutMapping("createIndex")
    public String createIndex(@RequestParam String indexName){
        // 封装请求
        CreateIndexRequest indexRequest=new CreateIndexRequest(indexName);
        CreateIndexResponse createIndexResponse = null;
        try {
            // 发送请求
            createIndexResponse = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (createIndexResponse.isAcknowledged()){
            return indexName+"  索引创建创建成功";
        }
        return indexName+"  索引创建失败";
    }
2、删除索引
    @DeleteMapping("deleteIndex")
    public String deleteIndex(@RequestParam String indexName){
        DeleteIndexRequest indexRequest=new DeleteIndexRequest(indexName);
        AcknowledgedResponse acknowledgedResponse = null;
        try {
            acknowledgedResponse = restHighLevelClient.indices().delete(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (acknowledgedResponse.isAcknowledged()){
            return indexName+"  索引删除成功";
        }
        return indexName+"  索引删除失败";
    }
四、文档 1、创建/修改文档
    @PostMapping("createDoc/{docId}")
    public String createdocument(@PathVariable String docId,@RequestBody String doc){
        IndexRequest indexRequest=new IndexRequest("index2");
        indexRequest.id(docId);
        indexRequest.source(doc, XContentType.JSON);
        IndexResponse indexResponse = null;
        try {
            indexResponse = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        RestStatus status = indexResponse.status();
        if (status.getStatus() == 200){
            return "文档创建成功,id为"+docId;
        }
        return docId+ "文档创建失败";
    }
2、删除文档
    @DeleteMapping("deleteDoc/{docId}")
    public String deleteDoc(@PathVariable String docId){
        DeleteRequest indexRequest=new DeleteRequest("index2");
        indexRequest.id(docId);
        DeleteResponse deleteResponse=null;
        try {
            deleteResponse = restHighLevelClient.delete(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (deleteResponse.status().getStatus() == 201) {
            return "文档删除成功";
        }
        return "文档删除失败";
    }
五、查询文档

查询的逻辑比较复杂,如下图所示

    public String searchDoc(){
        List> result=new ArrayList<>();
        try {
            SearchRequest searchRequest=new SearchRequest("index1");
            SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
            // 构造查询条件
            // 模糊查
            MatchQueryBuilder queryBuilder = QueryBuilders.matchQuery("bookName", "Java");
            // MatchAllQueryBuilder queryBuilder = QueryBuilders.matchAllQuery(); 全查
            // MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery("语言", "bookName", "bookAuthor"); 多字段查询

            // 精确查询
            // TermQueryBuilder termQuery = QueryBuilders.termQuery("bookName", "C语言从入门到放弃");
            sourceBuilder.query(queryBuilder);

            // 构造分页条件
            sourceBuilder.from(0);
            sourceBuilder.size(5);

            // 构造高亮显示条件
            HighlightBuilder highlightBuilder=new HighlightBuilder();
            HighlightBuilder.Field field = new HighlightBuilder.Field("bookName");
            highlightBuilder.field(field);
            highlightBuilder.preTags("");
            sourceBuilder.highlighter(highlightBuilder);

            searchRequest.source(sourceBuilder);
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits SearchHits = searchResponse.getHits();
            SearchHit[] hits = SearchHits.getHits();
            for (SearchHit hit : hits) {
                Map sourceAsMap = hit.getSourceAsMap();
                result.add(sourceAsMap);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.toJSonString(result);
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5695980.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存