iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot+Elasticsearch如何实现数据搜索
  • 755
分享到

SpringBoot+Elasticsearch如何实现数据搜索

2023-06-30 17:06:48 755人浏览 薄情痞子
摘要

这篇文章主要介绍了SpringBoot+elasticsearch如何实现数据搜索的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springBoot+Elasticsearch如何实现数据搜索文章都会有所收获,

这篇文章主要介绍了SpringBoot+elasticsearch如何实现数据搜索的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇springBoot+Elasticsearch如何实现数据搜索文章都会有所收获,下面我们一起来看看吧。

    一、简介

    SpringBoot 连接 ElasticSearch,主流的方式有以下四种方式

    • 方式一:通过Elastic Transport Client客户端连接 es 服务器,底层基于 tcp 协议通过 transport 模块和远程 ES 服务端通信,不过,从 V7.0 开始官方不建议使用,V8.0开始正式移除。

    • 方式二:通过Elastic Java Low Level Rest Client客户端连接 es 服务器,底层基于 Http 协议通过 restful api 来和远程 ES 服务端通信,只提供了最简单最基本的 API,类似于上篇文章中给大家介绍的 API 操作逻辑。

    • 方式三:通过Elastic Java High Level Rest Client客户端连接 es 服务器,底层基于Elastic Java Low Level Rest Client客户端做了一层封装,提供了更高级得 API 且和Elastic Transport Client接口及参数保持一致,官方推荐的 es 客户端。

    • 方式四:通过JestClient客户端连接 es 服务器,这是开源社区基于 HTTP 协议开发的一款 es 客户端,官方宣称接口及代码设计比 ES 官方提供的 Rest 客户端更简洁、更合理,更好用,具有一定的 ES 服务端版本兼容性,但是更新速度不是很快,目前 ES 版本已经出到 V7.9,但是JestClient只支持 V1.0~V6.X 版 本的 ES。

    还有一个需要大家注意的地方,那就是版本号的兼容!

    在开发过程中,大家尤其需要关注一下客户端和服务端的版本号,要尽可能保持一致,比如服务端 es 的版本号是6.8.2,那么连接 es 的客户端版本号,最好也是6.8.2,即使因项目的原因不能保持一致,客户端的版本号必须在6.0.0 ~6.8.2,不要超过服务器的版本号,这样客户端才能保持正常工作,否则会出现很多意想不到的问题,假如客户端是7.0.4的版本号,此时的程序会各种报错,甚至没办法用!

    为什么要这样做呢?主要原因就是 es 的服务端,高版本不兼容低版本;es6 和 es7 的某些 API 请求参数结构有着很大的区别,所以客户端和服务端版本号尽量保持一致。

    废话也不多说了,直接上代码!

    二、代码实践

    本文采用的SpringBoot版本号是2.1.0.RELEASE,服务端 es 的版本号是6.8.2,客户端采用的是官方推荐的Elastic Java High Level Rest Client版本号是6.4.2,方便与SpringBoot的版本兼容。

    2.1、导入依赖

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

    2.2、配置环境变量

    在application.properties全局配置文件中,配置elasticsearch自定义环境变量。

    elasticsearch.scheme=httpelasticsearch.address=127.0.0.1:9200elasticsearch.userName=elasticsearch.userPwd=elasticsearch.SocketTimeout=5000elasticsearch.connectTimeout=5000elasticsearch.connectionRequestTimeout=5000

    2.3、创建 elasticsearch 的 config 类

    @Configurationpublic class ElasticsearchConfiguration {    private static final Logger log = LoggerFactory.getLogger(ElasticsearchConfiguration.class);    private static final int ADDRESS_LENGTH = 2;    @Value("${elasticsearch.scheme:http}")    private String scheme;    @Value("${elasticsearch.address}")    private String address;    @Value("${elasticsearch.userName}")    private String userName;    @Value("${elasticsearch.userPwd}")    private String userPwd;    @Value("${elasticsearch.socketTimeout:5000}")    private Integer socketTimeout;    @Value("${elasticsearch.connectTimeout:5000}")    private Integer connectTimeout;    @Value("${elasticsearch.connectionRequestTimeout:5000}")    private Integer connectionRequestTimeout;        @Bean(name = "restHighLevelClient")    public RestHighLevelClient restClientBuilder() {        HttpHost[] hosts = Arrays.stream(address.split(","))                .map(this::buildHttpHost)                .filter(Objects::nonNull)                .toArray(HttpHost[]::new);        RestClientBuilder restClientBuilder = RestClient.builder(hosts);        // 异步参数配置        restClientBuilder.setHttpClientConfiGCallback(httpClientBuilder -> {            httpClientBuilder.setDefaultCredentialsProvider(buildCredentialsProvider());            return httpClientBuilder;        });        // 异步连接延时配置        restClientBuilder.setRequestConfigCallback(requestConfigBuilder -> {            requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeout);            requestConfigBuilder.setSocketTimeout(socketTimeout);            requestConfigBuilder.setConnectTimeout(connectTimeout);            return requestConfigBuilder;        });        return new RestHighLevelClient(restClientBuilder);    }        private HttpHost buildHttpHost(String s) {        String[] address = s.split(":");        if (address.length == ADDRESS_LENGTH) {            String ip = address[0];            int port = Integer.parseInt(address[1]);            return new HttpHost(ip, port, scheme);        } else {            return null;        }    }        private CredentialsProvider buildCredentialsProvider(){        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePassWordCredentials(userName,                userPwd));        return credentialsProvider;    }}

    至此,客户端配置完毕,项目启动的时候,会自动注入到Spring的ioc容器里面。

    2.4、索引管理

    es 中最重要的就是索引库,客户端如何创建呢?请看下文!

    创建索引

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void createIndex() throws IOException {        CreateIndexRequest request = new CreateIndexRequest("cs_index");        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);        System.out.println(response.isAcknowledged());    }        @Test    public void createIndexComplete() throws IOException {        CreateIndexRequest request = new CreateIndexRequest();        //索引名称        request.index("cs_index");        //索引配置        Settings settings = Settings.builder()                .put("index.number_of_shards", 3)                .put("index.number_of_replicas", 1)                .build();        request.settings(settings);        //映射结构字段        Map<String, Object> properties = new HashMap();        properties.put("id", ImmutableBiMap.of("type", "text"));        properties.put("name", ImmutableBiMap.of("type", "text"));        properties.put("sex", ImmutableBiMap.of("type", "text"));        properties.put("age", ImmutableBiMap.of("type", "long"));        properties.put("city", ImmutableBiMap.of("type", "text"));        properties.put("createTime", ImmutableBiMap.of("type", "long"));        Map<String, Object> mapping = new HashMap<>();        mapping.put("properties", properties);        //添加一个默认类型        System.out.println(JSON.tojsONString(request));        request.mapping("_doc",mapping);        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);        System.out.println(response.isAcknowledged());    }}

    删除索引

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void deleteIndex() throws IOException {        DeleteIndexRequest request = new DeleteIndexRequest("cs_index1");        AcknowledgedResponse response = client.indices().delete(request, RequestOptions.DEFAULT);        System.out.println(response.isAcknowledged());    }}

    查询索引

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void getIndex() throws IOException {        // 创建请求        GetIndexRequest request = new GetIndexRequest();        request.indices("cs_index");        // 执行请求,获取响应        GetIndexResponse response = client.indices().get(request, RequestOptions.DEFAULT);        System.out.println(response.toString());    }}

    查询索引是否存在

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void exists() throws IOException {        // 创建请求        GetIndexRequest request = new GetIndexRequest();        request.indices("cs_index");        // 执行请求,获取响应        boolean response = client.indices().exists(request, RequestOptions.DEFAULT);        System.out.println(response);    }}

    查询所有的索引名称

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void getAllIndices() throws IOException {        GetAliasesRequest request = new GetAliasesRequest();        GetAliasesResponse response =  client.indices().getAlias(request,RequestOptions.DEFAULT);        Map<String, Set<AliasMetaData>> map = response.getAliases();        Set<String> indices = map.keySet();        for (String key : indices) {            System.out.println(key);        }    }}

    查询索引映射字段

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void getMapping() throws IOException {        GetMappingsRequest request = new GetMappingsRequest();        request.indices("cs_index");        request.types("_doc");        GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT);        System.out.println(response.toString());    }}

    添加索引映射字段

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class IndexJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void addMapping() throws IOException {        PutMappingRequest request = new PutMappingRequest();        request.indices("cs_index");        request.type("_doc");        //添加字段        Map<String, Object> properties = new HashMap();        properties.put("accountName", ImmutableBiMap.of("type", "keyword"));        Map<String, Object> mapping = new HashMap<>();        mapping.put("properties", properties);        request.source(mapping);        PutMappingResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);        System.out.println(response.isAcknowledged());    }}

    2.5、文档管理

    所谓文档,就是向索引里面添加数据,方便进行数据查询,详细操作内容,请看下文!

    添加文档

    ublic class UserDocument {    private String id;    private String name;    private String sex;    private Integer age;    private String city;    private Date createTime;    //省略get、set...}
    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class DocJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void aDDDocument() throws IOException {        // 创建对象        UserDocument user = new UserDocument();        user.setId("1");        user.setName("里斯");        user.setCity("武汉");        user.setSex("男");        user.setAge(20);        user.setCreateTime(new Date());        // 创建索引,即获取索引        IndexRequest request = new IndexRequest();        // 外层参数        request.id("1");        request.index("cs_index");        request.type("_doc");        request.timeout(TimeValue.timeValueSeconds(1));        // 存入对象        request.source(JSON.toJSONString(user), XContentType.JSON);        // 发送请求        System.out.println(request.toString());        IndexResponse response = client.index(request, RequestOptions.DEFAULT);        System.out.println(response.toString());    }}

    更新文档

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class DocJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void updateDocument() throws IOException {        // 创建对象        UserDocument user = new UserDocument();        user.setId("2");        user.setName("程咬金");        user.setCreateTime(new Date());        // 创建索引,即获取索引        UpdateRequest request = new UpdateRequest();        // 外层参数        request.id("2");        request.index("cs_index");        request.type("_doc");        request.timeout(TimeValue.timeValueSeconds(1));        // 存入对象        request.doc(JSON.toJSONString(user), XContentType.JSON);        // 发送请求        System.out.println(request.toString());        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);        System.out.println(response.toString());    }}

    删除文档

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class DocJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void deleteDocument() throws IOException {        // 创建索引,即获取索引        DeleteRequest request = new DeleteRequest();        // 外层参数        request.id("1");        request.index("cs_index");        request.type("_doc");        request.timeout(TimeValue.timeValueSeconds(1));        // 发送请求        System.out.println(request.toString());        DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);        System.out.println(response.toString());    }}

    查询文档是不是存在

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class DocJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void exists() throws IOException {        // 创建索引,即获取索引        GetRequest request = new GetRequest();        // 外层参数        request.id("3");        request.index("cs_index");        request.type("_doc");        // 发送请求        System.out.println(request.toString());        boolean response = client.exists(request, RequestOptions.DEFAULT);        System.out.println(response);    }}

    通过 ID 查询指定文档

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class DocJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void getById() throws IOException {        // 创建索引,即获取索引        GetRequest request = new GetRequest();        // 外层参数        request.id("1");        request.index("cs_index");        request.type("_doc");        // 发送请求        System.out.println(request.toString());        GetResponse response = client.get(request, RequestOptions.DEFAULT);        System.out.println(response.toString());    }}

    批量添加文档

    @RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes = ElasticSearchApplication.class)public class DocJunit {    @Autowired    private RestHighLevelClient client;        @Test    public void batchAddDocument() throws IOException {        // 批量请求        BulkRequest bulkRequest = new BulkRequest();        bulkRequest.timeout(TimeValue.timeValueSeconds(10));        // 创建对象        List<UserDocument> userArrayList = new ArrayList<>();        userArrayList.add(new UserDocument("张三", "男", 30, "武汉"));        userArrayList.add(new UserDocument("里斯", "女", 31, "北京"));        userArrayList.add(new UserDocument("王五", "男", 32, "武汉"));        userArrayList.add(new UserDocument("赵六", "女", 33, "长沙"));        userArrayList.add(new UserDocument("七七", "男", 34, "武汉"));        // 添加请求        for (int i = 0; i < userArrayList.size(); i++) {            userArrayList.get(i).setId(String.valueOf(i));            IndexRequest indexRequest = new IndexRequest();            // 外层参数            indexRequest.id(String.valueOf(i));            indexRequest.index("cs_index");            indexRequest.type("_doc");            indexRequest.timeout(TimeValue.timeValueSeconds(1));            indexRequest.source(JSON.toJSONString(userArrayList.get(i)), XContentType.JSON);            bulkRequest.add(indexRequest);        }        // 执行请求        BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);        System.out.println(response.status());    }}

    关于“SpringBoot+Elasticsearch如何实现数据搜索”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“SpringBoot+Elasticsearch如何实现数据搜索”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注编程网精选频道。

    --结束END--

    本文标题: SpringBoot+Elasticsearch如何实现数据搜索

    本文链接: https://www.lsjlt.com/news/330456.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    本篇文章演示代码以及资料文档资料下载

    下载Word文档到电脑,方便收藏和打印~

    下载Word文档
    猜你喜欢
    • SpringBoot+Elasticsearch如何实现数据搜索
      这篇文章主要介绍了SpringBoot+Elasticsearch如何实现数据搜索的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot+Elasticsearch如何实现数据搜索文章都会有所收获,...
      99+
      2023-06-30
    • SpringBoot+Elasticsearch实现数据搜索的方法详解
      目录一、简介二、代码实践2.1、导入依赖2.2、配置环境变量2.3、创建 elasticsearch 的 config 类2.4、索引管理2.5、文档管理三、小结一、简介 在上篇 E...
      99+
      2024-04-02
    • SpringBoot 整合 Elasticsearch 实现海量级数据搜索功能
      目录一、简介二、代码实践2.1、导入依赖2.2、配置环境变量2.3、创建 elasticsearch 的 config 类2.4、索引管理2.5、文档管理三、小结今天给大家讲讲&nb...
      99+
      2024-04-02
    • 如何在PHP中使用ElasticSearch实现搜索
      这篇“如何在PHP中使用ElasticSearch实现搜索”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“如何在PHP中使用E...
      99+
      2023-06-05
    • Spring Boot整合Elasticsearch如何实现全文搜索引擎
      这篇文章给大家分享的是有关Spring Boot整合Elasticsearch如何实现全文搜索引擎的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。简单说,ElasticSearch(简称 ES)是搜索引擎,是结构化...
      99+
      2023-05-30
      spring boot elasticsearch
    • 详解elasticsearch实现基于拼音搜索
      目录1、背景2、安装拼音分词器3、拼音分词器提供的功能4、简单测试一下拼音分词器4.1 dsl4.2 运行结果5、es中分词器的组成6、自定义一个分词器实现拼音和中文的搜索1、创建m...
      99+
      2023-01-16
      elasticsearch 拼音搜索 elasticsearch 搜索
    • SQLite3如何实现数据库全文搜索
      这篇文章主要为大家展示了“SQLite3如何实现数据库全文搜索”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“SQLite3如何实现数据库全文搜索”这篇文章吧。对...
      99+
      2024-04-02
    • PHP 中基于 Elasticsearch 的模糊搜索与语义搜索实现
      在现代互联网环境下,搜索功能已经成为了各种应用的必备功能之一。传统的模糊搜索往往只能按照关键字进行简单的匹配,而缺乏了对用户意图的理解。而语义搜索则可以更好地抓住用户的意图,从而提供更加精确的搜索结果。在本文中,我们将介绍如何在 PHP 中...
      99+
      2023-10-21
      elasticsearch 模糊搜索 语义搜索
    • 详解如何在Elasticsearch中搜索空值
      目录引言选项 1:null_value 映射参数选项2:使用 MUST_NOT 查询引言 根据 Elasticsearch 文档,无法索引或搜索空值 null。 当一个字段设置为 ...
      99+
      2023-01-28
      Elasticsearch搜索空值 Elasticsearch 空值
    • 如何实现vue搜索和vue模糊搜索
      小编给大家分享一下如何实现vue搜索和vue模糊搜索,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!1、使用vue来实现一般搜索&...
      99+
      2024-04-02
    • JavaScript实现搜索的数据显示
      本文实例为大家分享了JavaScript实现搜索的数据显示代码,供大家参考,具体内容如下 今天的效果如下: 这个案例的要点有两个: 一是使用CSS显示样式 二是使用js比较输入的内...
      99+
      2024-04-02
    • Android如何实现搜索框
      这篇文章主要介绍了Android如何实现搜索框,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。具体内容如下展示效果代码区SouActivitypublic class...
      99+
      2023-05-30
      android
    • Angular如何实现搜索框
      这篇文章主要介绍Angular如何实现搜索框,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!1.要求:利用 AngularJS 框架实现手机产品搜索功能,题目要求:1)自行查找素材,按...
      99+
      2024-04-02
    • css搜索框如何实现
      这篇文章将为大家详细讲解有关css搜索框如何实现,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。 css实现搜索框的方法:首先组织页面结构;然后...
      99+
      2024-04-02
    • 如何使用MongoDB实现数据的全文搜索功能
      如何使用MongoDB实现数据的全文搜索功能导语:随着信息化时代的迅猛发展,全文搜索功能成为了许多应用程序的必备功能。作为一个流行的NoSQL数据库,MongoDB也提供了强大的全文搜索能力。本文将介绍如何使用MongoDB实现数据的全文搜...
      99+
      2023-10-22
      MongoDB 全文搜索 数据实现
    • PHP 中使用 Elasticsearch 实现分布式搜索引擎
      简介:分布式搜索引擎是现代互联网应用中非常重要的一环,它能够实现快速的全文检索、高效的数据搜索和排序。Elasticsearch是一个基于Lucene的开源分布式搜索引擎,提供了强大的搜索和分析功能。本文将介绍如何在PHP中使用Elasti...
      99+
      2023-10-21
      PHP elasticsearch 分布式搜索引擎
    • HTML5如何实现语音搜索
      这篇文章主要介绍HTML5如何实现语音搜索,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!淘宝网的语音搜索也有了一阵子了,但似乎都没看到相关的博客或帖子在说这个如何实现,今天查了点资料...
      99+
      2024-04-02
    • Xamarin如何实现全局搜索
      这篇文章主要为大家展示了“Xamarin如何实现全局搜索”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Xamarin如何实现全局搜索”这篇文章吧。全局搜索新版本的一个顶级特征就是工具栏上的全局搜...
      99+
      2023-06-27
    • javaweb搜索功能如何实现
      要实现JavaWeb的搜索功能,可以按照以下步骤进行:1. 建立数据库:创建一个适合存储搜索内容的数据库表。例如,可以创建一个包含标...
      99+
      2023-09-21
      javaweb
    • php如何实现搜索效果
      这篇文章将为大家详细讲解有关php如何实现搜索效果,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。php实现搜索效果的方法:1、初始化查询条件;2、调用查询方法;3、计算页面显示数据条数;4、在设置的“搜索...
      99+
      2023-06-22
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作