首页 > 编程语言 >Java Spring Boot 集成 elasticsearch6.8.x

Java Spring Boot 集成 elasticsearch6.8.x

时间:2023-12-23 16:12:02浏览次数:38  
标签:elasticsearch6.8 Java String Spring request new elasticsearch import org

在全文搜索领域,毫无疑问,当下 elasticsearch 应用广泛,其优势自不必说,凭借全文快速搜索,可以在短时内实现大数据量的查询。

今天学习下在 Spring Boot 中 集成 elasticsearch 开发,这里主要展示可以怎么用,至于开发人员向通过 ElasticsearchORM 封装,也可以参考下面的示例。

环境:

  • Spring Boot: 3.1.6
  • JDK:17
  • elasticsearch:6.8.23

依赖

在添加依赖需要注意,如果服务段的 es 是什么版本,请在我们的 客户端 依赖中也用同样额版本,别问为啥,问就是版本兼容性。

<!-- High-level-Rest-Client-->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.8.23</version>
</dependency>
<!-- es 依赖 -->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>6.8.23</version>
</dependency>
<!--   @Data     -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.30</version>
</dependency>

自定义配置及读取

配置文件

application.yaml

elasticsearch:
  host: 172.xx.xx.xx
  port: 9200
  user: admin
  password: password
  scheme: http

配置读取

配置类

package com.example.springbootesdemo.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class ESConfig {
    private String host;

    private int port;

    private String scheme;

    private String user;

    private String password;

    @Override
    public String toString() {
        return String.format("elasticsearch{host=%s, port=%d, user=%s, password=%s}", host, port, user, password);
    }
}

es客户端

package com.example.springbootesdemo.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticSearchClientConfig {
    @Autowired
    private ESConfig es;

    @Bean(name = "restHighLevelClient")
    public RestHighLevelClient restHighLevelClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(es.getHost(), es.getPort(), es.getScheme())
                )
        );
    }
}

后面的测试中会用到下面的 User bean:

package com.example.springbootesdemo.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;

    private Integer age;

    private String[] hobbies;
}

集成使用示例

索引操作

package com.example.springbootesdemo;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
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.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class EsIndexTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询索引是否存在
     */
    @Test
    public void testIndexIsExist() throws IOException {
        String indexName = "demo";
        // 1.create req
        GetIndexRequest req = new GetIndexRequest(indexName);
        // 2.client run req
        boolean exists = restHighLevelClient.indices().exists(req, RequestOptions.DEFAULT);
        System.out.println(String.format("%s exist: %b", indexName, exists));
    }

    /**
     * 创建索引
     */
    @Test
    public void testIndexCreate() {
        // 1.create req
        String indexName = "demo1222";
        CreateIndexRequest req = new CreateIndexRequest(indexName);
        // 2.run req
        try {
            CreateIndexResponse resp = restHighLevelClient.indices().create(req, RequestOptions.DEFAULT);
            System.out.println("create resp: " + resp.isAcknowledged());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 通过自定义构建索引
     * @throws IOException
     */
    @Test
    public void testIndexCreateUseXContent() throws IOException {
        XContentBuilder builder = XContentFactory.jsonBuilder();
        // build mappings and settings
        // 注意start开始,end结束
        builder.startObject()

                .startObject("settings")
                .field("priority", 80)
                .field("number_of_shards", 1)
                .field("number_of_replicas", 0)
                .endObject()

                .startObject("mappings")
                .endObject()

                .endObject();

        CreateIndexRequest request = new CreateIndexRequest("demo1223");
        request.source(builder);

        CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);

        System.out.println("isAcknowledge: " + response.isAcknowledged());
    }

    /**
     * 删除索引
     */
    @Test
    public void testIndexDelete() {
        String index = "demo*";
        DeleteIndexRequest req = new DeleteIndexRequest(index);
        try {
            AcknowledgedResponse resp = restHighLevelClient.indices().delete(req, RequestOptions.DEFAULT);
            System.out.println("delete result: " + resp.isAcknowledged());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

文档操作

package com.example.springbootesdemo;

import com.example.springbootesdemo.model.User;
import net.minidev.json.JSONValue;
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.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class EsDocTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 插入数据
     * @throws IOException
     */
    @Test
    public void testAddDoc() throws IOException {
        User user = new User("Alice", 21, new String[]{"table tennis", "soccer"});
        IndexRequest request = new IndexRequest("demo1222");
        // set docID, refresh time
        request.type("_doc"); // 6.8.x 需要
        request.id("10001");
        request.timeout("1s");

        // put data to req, and trans to json format
        request.source(JSONValue.toJSONString(user), XContentType.JSON);

        // req
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.toString());
        System.out.println(response.status());
    }

    /**
     * 获取文档
     */
    @Test
    public void testGetDoc() throws IOException {
        GetRequest request = new GetRequest("demo1222","_doc",  "10001");
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);

        System.out.println(response);
        System.out.println(response.getSourceAsString());
    }

    /**
     * 更新文档
     * @throws IOException
     */
    @Test
    public void testUpdateDoc() throws IOException {
        UpdateRequest request = new UpdateRequest("demo1222", "_doc", "10001");
        User user = new User("Alice", 33, new String[]{"table tennis", "soccer"});
        // put obj to doc
        request.doc(JSONValue.toJSONString(user), XContentType.JSON);

        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status() + " " + response.getResult());
    }

    /**
     * 删除文档
     * @throws IOException
     */
    @Test
    public void testDeleteDoc() throws IOException {
        DeleteRequest request = new DeleteRequest("demo1222", "_doc", "10001");

        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status() + " " + response.getResult());
    }
}

批量操作

package com.example.springbootesdemo;

import com.example.springbootesdemo.model.User;
import net.minidev.json.JSONValue;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
public class EsBulkTest {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Test
    public void testBulkInsertDocs() throws IOException {
        BulkRequest request = new BulkRequest();

        // set timeout
        request.timeout("10s");

        // build docs
        ArrayList<User> users = new ArrayList<>();
        users.add(new User("aaa", 11, new String[]{"111", "222"}));
        users.add(new User("bbb", 22, new String[]{"111", "222"}));
        users.add(new User("ccc", 33, new String[]{"111", "222"}));
        users.add(new User("ddd", 44, new String[]{"111", "222"}));
        users.add(new User("eee", 55, new String[]{"111", "222"}));

        int id = 1000;
        // bulk handle
        for (User user: users) {
            request.add(new IndexRequest("demo1222")
                    .id("" + (id++))
                    .type("_doc")
                    .source(JSONValue.toJSONString(user), XContentType.JSON)
            );
        }

        BulkResponse response = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
        System.out.println(response.hasFailures());
    }
}

条件查询与聚合

package com.example.springbootesdemo;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.MinAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.min.ParsedMin;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class EsSearchTest {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 条件查询
     * @throws IOException
     */
    @Test
    public void testSearch() throws IOException {
        SearchRequest request = new SearchRequest();
        // add search add, can put indices
        request.indices("demo1222");
        request.types("_doc");
        // build search query
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.size(10000);
        builder.from(0);

        builder.sort("age");

        builder.fetchSource(new String[]{"name", "age"}, new String[]{"hobbies"});

        // query all
        builder.query(QueryBuilders.matchAllQuery());
        // query terms
        builder.query(QueryBuilders.termsQuery("name", new String[]{"aaa", "bbb", "ccc"}));

        // add source
        request.source(builder);

        // send req
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        // total docs
        System.out.println("total:" + response.getHits().getTotalHits());

        // output result
        SearchHit[] results = response.getHits().getHits();
        for (SearchHit result: results) {
            System.out.println("score: " + result.getScore() + " " + result.getId());
            Map<String, Object> source = result.getSourceAsMap();
            for (Map.Entry<String, Object> s: source.entrySet()) {
                System.out.println(s.getKey() + "--" + s.getValue());
            }
        }
    }

    /**
     * 聚合查询
     * @throws IOException
     */
    @Test
    public void testAggSearch() throws IOException {
        SearchRequest request = new SearchRequest();
        // add index
        request.indices("demo1222");
        request.types("_doc");

        // build search builder
        SearchSourceBuilder builder = new SearchSourceBuilder();

        builder.size(0);

        // build agg builder
        // if string, use keyword, or use field name self
        TermsAggregationBuilder termsAggregationBuilder = AggregationBuilders.terms("indexName")
                .field("name.keyword")
                .size(10000);
        MinAggregationBuilder minAggregationBuilder = AggregationBuilders.min("minAge").field("age");
        // sub agg
        termsAggregationBuilder.subAggregation(minAggregationBuilder);

        // put agg to search builder
        builder.aggregation(termsAggregationBuilder);

        // put search builder to request
        request.source(builder);

        // send request
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        Map<String, Aggregation> stringAggMap = response.getAggregations().asMap();
        System.out.println(stringAggMap.get("indexName"));

        ParsedStringTerms stringTerms = (ParsedStringTerms) stringAggMap.get("indexName");

        List<? extends Terms.Bucket> buckets = stringTerms.getBuckets();

        // parse and get bucket key value, minAgg's value
        for (Terms.Bucket bucket: buckets) {
            String name = (String) bucket.getKey();

            Map<String, Aggregation> ageMap = bucket.getAggregations().asMap();

            ParsedMin ageAgg = (ParsedMin) ageMap.get("minAge");
            long age = (long) ageAgg.getValue();

            System.out.println(String.format("name: %s, age: %d", name, age));
        }
    }
}

参考:

标签:elasticsearch6.8,Java,String,Spring,request,new,elasticsearch,import,org
From: https://www.cnblogs.com/davis12/p/17923229.html

相关文章

  • Spring MVC 源码分析 - HandlerMapping 组件(三)之 AbstractHandlerMethodMapping
    HandlerMapping组件HandlerMapping组件,请求的处理器匹配器,负责为请求找到合适的 HandlerExecutionChain 处理器执行链,包含处理器(handler)和拦截器们(interceptors)handler 处理器是Object类型,可以将其理解成HandlerMethod对象(例如我们使用最多的 @RequestMapping 注解所标......
  • JAVA面试心得
    当参加Java面试时,了解一些常见的问题和准备相应的答案是至关重要的。在我的面试经验中,我总结出了一些有助于成功的关键因素。以下是我在Java面试中的一些心得:1.深入理解Java基础知识在面试中,Java的基础知识是至关重要的。包括面向对象编程(OOP)的概念,如封装、继承和多态,以及Java的基......
  • spring-jcl 模块源码分析
    目录简介源码分析总结简介spring-jcl是spring用于处理日志打印的模块,被spring-core所依赖:jcl全称是JakartaCommonsLogging,是apache提供的日志门面(功能同slf4j),日志门面利用设计模式中的门面模式提供统一的日志接口,实际的日志实现可以任意更换。不过jcl支持的日志实现有限,已......
  • 基于SpringBoot+Vue的文理医院预约挂号系统设计实现(源码+lw+部署文档+讲解等)
    (文章目录)前言:heartpulse:博主介绍:✌全网粉丝10W+,CSDN特邀作者、博客专家、CSDN新星计划导师、全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战✌:heartpulse:......
  • 【开源】基于JAVA的超市商品管理系统
    一、摘要1.1简介随着社会的发展,人们的生活水平不断地提高,超市遍布城市各个社区,它们繁荣了社会经济,也便利了人们的生活,是人们生活中不可缺少的一部份。顾客需要非常方便的找到自己想要的商品,超巿商品库存、摆放、价格方面的工作,需要一个稳定、可靠的管理系统帮助寻找管理商品的位置......
  • 抓取java堆栈失败的思考-Safepoint等的学习
    抓取java堆栈失败的思考-Safepoint等的学习背景前期解决问题都是靠抓取进程堆栈jstack,后者是jmap到内存dump的方式来进行分析.最近连续有两个比较大的项目出现了抓取dump/stack失败的情况.具体原因可能还不太一样.周末再翻找之前的资料时猜到了可能得几个原因.想总结......
  • 【转载】JAVA 百度坐标,火星坐标和WGS84之间互转
    原出处:https://www.cnblogs.com/Fooo/p/16986453.html/***a*/publicfinalstaticdoublea=6378245.0;/***ee*/publicfinalstaticdoubleee=0.00669342162296594323;//圆周率GCJ_02_To_WGS_84publicfinalstatic......
  • Spring的BeanDefinitionRegistryPostProcessor接口详解
    BeanDefinitionRegistryPostProcessor介绍BeanDefinitionRegistryPostProcessor它是Spring框架的一个扩展点,用于对Bean定义的注册过程进行干预和定制,例如添加,修改或删除Bean定义等。BeanDefinitionRegistryPostProcessor它继承BeanFactoryPostProcessor接口,并在其基础上扩展了......
  • Spring的Bean后置处理器之AnnotationAwareAspectJAutoProxyCreator
    本文能帮你回答以下几个问题;AnnotationAwareAspectJAutoProxyCreator后置器的作用是什么?SpringAOP自动增强bean是如何实现的。如何在spring上下文添加AnnotationAwareAspectJAutoProxyCreator?如何利用ProxyFactory硬编码实现一个bean的增强?AnnotationAwareAspectJAutoProx......
  • 【poi】使用poi时报错:java.io.EOFException: Unexpected end of ZLIB input stream
    错误写法Workbookworkbook=null;try{//会报错Filefile=newFile("D:\\1.xlsx");workbook=newXSSFWorkbook(file);ByteArrayOutputStreambaos=newByteArrayOutputStream(); workbook.write(baos); workbook.close(); bytes=baos......