springboot操作es

这篇具有很好参考价值的文章主要介绍了springboot操作es。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

创建springboot整合es项目

springboot操作es
springboot操作es
一定要修改对应es版本
修改es版本,我的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>springboot-es</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-es</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
        <elasticsearch.version>7.6.1</elasticsearch.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
![在这里插入图片描述](https://img-blog.csdnimg.cn/3320bdba0d3047f08aed981397603972.png)

记得把没用文件删掉.mvn,和一些mvn的配置文件,要不然可能会导致项目编译不通过

配置HighLevelClient

注: 在ElasticSearch 7以后,Spring data建议采用High-level REST client。

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 {
    // 注册 rest高级客户端 
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1",9200,"http")
                )
        );
        return client;
    }
}


索引增删改查操作

在测试类进行测试,测试类中直接注入restHighLevelClient即可使用;


@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)  //使用junit4进行测试
public class SpringbootEsApplicationTests {

    @Autowired
    public RestHighLevelClient restHighLevelClient;

    // 创建索引
    @Test
    public void createIndex() throws IOException {
        org.elasticsearch.client.indices.CreateIndexRequest yida = new org.elasticsearch.client.indices.CreateIndexRequest("yida");
        org.elasticsearch.client.indices.CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(yida, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSONString(createIndexResponse));
        restHighLevelClient.close();
    }

    // 测试获取索引,并判断其是否存在
    @Test
    public void testIndexIsExists() throws IOException {
        GetIndexRequest request = new GetIndexRequest("yida");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);// 索引是否存在
        restHighLevelClient.close();
    }

    // 删除索引
    @Test
    public void testDeleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest("yida");
        AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println(response.isAcknowledged());// 是否删除成功
        restHighLevelClient.close();
    }

}

文档的基本操作

文档的增删改查;

  // 测试添加文档(先创建一个User实体类,添加fastjson依赖)
    @Test
    public void testAddDocument() throws IOException {
        // 创建一个User对象
        User yida = new User("yida", 18);
        // 创建请求
        IndexRequest request = new IndexRequest("yida");
        // 制定规则 PUT /yida_index/_doc/1
        request.id("1");// 设置文档ID
        request.timeout(TimeValue.timeValueMillis(1000));// request.timeout("1s")
        // 将我们的数据放入请求中
        request.source(JSON.toJSONString(yida), XContentType.JSON);
        // 客户端发送请求,获取响应的结果
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response.status());// 获取建立索引的状态信息 CREATED
        System.out.println(response);// 查看返回内容 IndexResponse[index=yida_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
    }

    // 获取文档,判断是否存在 get /yida/_doc/1
    @Test
    public void testDocumentIsExists() throws IOException {
        GetRequest request = new GetRequest("yida", "1");
        // 不获取返回的 _source的上下文了
        request.fetchSourceContext(new FetchSourceContext(false));
        request.storedFields("_none_");
        boolean exists = restHighLevelClient.exists(request, RequestOptions.DEFAULT);
        System.out.println(exists);
        restHighLevelClient.close();
    }



    // 测试更新文档内容
    @Test
    public void testUpdateDocument() throws IOException {
        UpdateRequest request = new UpdateRequest("yida", "1");
        User user = new User("doudou",11);
        request.doc(JSON.toJSONString(user),XContentType.JSON);
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.status()); // OK
        restHighLevelClient.close();
    }

    // 测试删除文档
    @Test
    public void testDeleteDocument() throws IOException {
        DeleteRequest request = new DeleteRequest("yida", "1");
        request.timeout("1s");
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.status());// OK
    }

    // 测试获得文档信息
    @Test
    public void testGetDocument() throws IOException {
        GetRequest request = new GetRequest("yida","1");
        GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        System.out.println(response.getSourceAsString());// 打印文档内容
        System.out.println(request);// 返回的全部内容和命令是一样的
        restHighLevelClient.close();
    }

文档的复杂查询

  // 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 高亮
// TermQueryBuilder 精确查询
// MatchAllQueryBuilder
// xxxQueryBuilder ...
    @Test
    public void testSearch() throws IOException {
        // 1.创建查询请求对象
        SearchRequest searchRequest = new SearchRequest("yida");
        // 2.构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // (1)查询条件 使用QueryBuilders工具类创建
        // 精确查询
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张");
        //        // 匹配查询
        //        MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();
        // (2)其他<可有可无>:(可以参考 SearchSourceBuilder 的字段部分)
        // 设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder = highlightBuilder.requireFieldMatch(false).field("*").preTags("<font color='red'>").postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);
        //        // 分页
        //        searchSourceBuilder.from();
        //        searchSourceBuilder.size();
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // (3)条件投入
        searchSourceBuilder.query(termQueryBuilder);
        // 3.添加条件到请求
        searchRequest.source(searchSourceBuilder);
        // 4.客户端查询请求
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        // 5.查看返回结果
        SearchHits hits = search.getHits();
        System.out.println(JSON.toJSONString(hits));
        System.out.println("=======================");

        for (SearchHit documentFields : hits.getHits()) {
            System.out.println(documentFields.getSourceAsMap());
            // 使用新的字段值(高亮),覆盖旧的字段值
            Map<String, Object> sourceAsMap = documentFields.getSourceAsMap();
            // 高亮字段
            Map<String, HighlightField> highlightFields = documentFields.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            // 替换
            if (name != null){
                Text[] fragments = name.fragments();
                StringBuilder new_name = new StringBuilder();
                for (Text text : fragments) {
                    new_name.append(text);
                }
                sourceAsMap.put("name",new_name.toString());
            }
            System.out.println("替换高亮的字段"+JSONObject.toJSON(sourceAsMap));
        }

    }

文档的批量操作

bulk语法
bulk对JSON串的有着严格的要求。每个JSON串不能换行,只能放在同一行,同时,相邻的JSON串之间必须要有换行。bulk的每个操作必须要一对JSON串(delete语法除外)
例如若增加一个文档如下所示:


## 批量操作

POST _bulk
{"create": {"_index": "yida", "_id": 11}}
{"name": "test_bulk", "age":"100"}

## 批量删除
POST _bulk
{"delete": {"_index": "yida","_id": "1"}}
{"delete": {"_index": "yida","_id": "2"}}
{"delete": {"_index": "yida","_id": "3"}}
{"delete": {"_index": "yida","_id": "4"}}

## 可以又新增又删除
POST _bulk
{"index": {"_index": "yida","_id": 11}}
{"name": "test_bulk", "age":"101"}
{"index": {"_index": "yida","_id": 12}}
{"name": "test_bulk", "age":"101"}
{"delete": {"_index": "yida","_id": "11"}}
{"delete": {"_index": "yida","_id": "12"}}

操作类型

  • create 如果文档不存在就创建,但如果文档存在就返回错误
  • index 如果文档不存在就创建,如果文档存在就更新
  • update 更新一个文档,如果文档不存在就返回错误
  • delete 删除一个文档,如果要删除的文档id不存在,就返回错误
    从以上可以看出index是比较常用的,因为bulk操作失败不会影响其他文档操作,我们可以从他的返回结果中查看失败的详细原因。

对应的代码操作也是跟命令一样:文章来源地址https://www.toymoban.com/news/detail-485368.html

  // 批量插入数据
    @Test
    public void testBulkAdd() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList<User> users = new ArrayList<>();
        users.add(new User("张益达-1",1));
        users.add(new User("张益达-2",2));
        users.add(new User("张益达-3",3));
        users.add(new User("张益达-4",4));
        users.add(new User("张益达-5",5));
        users.add(new User("张益达-6",6));
        // 批量请求处理
        for (int i = 0; i < users.size(); i++) {
            bulkRequest.add(
                    // 这里是数据信息
                    new IndexRequest("yida")
                            .id(""+(i + 1)) // 没有设置id 会自定生成一个随机id
                            .source(JSON.toJSONString(users.get(i)),XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());// ok
    }

    @Test
    public void testBulkUpdate() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList<User> users = new ArrayList<>();
        users.add(new User("张益达-1-update1",1));
        users.add(new User("张益达-2-update1",2));
        users.add(new User("张益达-3-update",3));
        users.add(new User("张益达-4-update",4));
        users.add(new User("张益达-5-update",5));
        users.add(new User("张益达-6-update",6));
        // 批量请求处理
        for (int i = 0; i < users.size(); i++) {

            Map map = JSON.parseObject(JSONObject.toJSONString(users.get(i)), Map.class);
            bulkRequest.add(
                    new UpdateRequest("yida", "" + (i + 1))
                            .doc(map)
                            // 不存在就插入
                            .upsert(JSON.toJSONString(users.get(i)),XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());// ok
    }

    @Test
    public void testBulkDelete() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");
        ArrayList<User> users = new ArrayList<>();
        users.add(new User("张益达-1",1));
        users.add(new User("张益达-2",2));
        users.add(new User("张益达-3",3));
        users.add(new User("张益达-4",4));
        users.add(new User("张益达-5",5));
        users.add(new User("张益达-6",6));
        // 批量请求处理
        for (int i = 0; i < users.size(); i++) {
            bulkRequest.add(
                    // 这里是数据信息
                    new DeleteRequest("yida")
                            .id("" + (i + 1))

            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println(bulk.status());// ok
    }

到了这里,关于springboot操作es的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringBoot项目整合RabbitMQ

    消息队列(Message Queue)是分布式系统中常用的组件,它允许不同的应用程序之间通过发送和接收消息进行通信。Spring Boot提供了简单且强大的方式来整合消息队列,其中包括RabbitMQ、ActiveMQ、Kafka等多种消息队列实现。 本文将以RabbitMQ为例,详细介绍如何使用Spring Boot来整合消

    2024年02月09日
    浏览(42)
  • 【SpringBoot】整合Elasticsearch 操作索引及文档

    官网操作文档:Elasticsearch Clients | Elastic                踩坑太多了。。。这里表明一下Spring Boot2.4以上版本可能会出现问题,所以我降到了2.2.1.RELEASE。对于现在2023年6月而言,Es版本已经到了8.8,而SpringBoot版本已经到了3.x版本。如果是高版本的Boot在配置类的时候会发现

    2024年02月09日
    浏览(45)
  • Java操作RabbitMq并整合SpringBoot

    秋风阁-北溪入江流 RabbitMq自带有专门的管理界面,可以在其管理界面对RabbitMq进行管理查看等操作。 RabbitMq的管理界面的对外端口为 15672 ,当我们启动RabbitMq后,需要启动管理界面插件后才能访问界面。 通过参数配置连接RabbitMq 通过amqp协议连接RabbitMq queueDeclarePassive: 创建或

    2024年02月16日
    浏览(51)
  • Shiro整合SpringBoot项目实战

    ✅作者简介:2022年 博客新星 第八 。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏:SpringBoot 框架从入门到精通 ✨特色专栏:国学周更-心性养成之路 🥭本文内容:Shiro整合Sp

    2023年04月09日
    浏览(41)
  • 快速入门Springboot整合Datagpa操作数据库

    Spring Data JPA是Spring Data家族的一部分,可以轻松 实现基于JPA的存储库 。 . JPA是ORM规范,Hibernate是JPA规范的具体实现 ,这样的好处是开发者可以面向JPA规范进行持久层的开发,而底层的实现则是可以切换的。Spring Data Jpa则是在JPA之上添加另一层抽象(Repository层的实现),极大

    2024年02月07日
    浏览(38)
  • SpringBoot项目(支付宝整合)——springboot整合支付宝沙箱支付 & 从极简实现到IOC改进

    1.springboot整合支付宝沙箱支付; 2.准备工作:沙箱api,内网穿透; 3.极简实现理解支付,异步回调等; 4.按照spring依赖注入的思想改造基础demo; https://gitee.com/pet365/springboot-alipay 支付宝开放平台 (alipay.com) 支付参数 natapp.cn官网 启动和配置 订单ID,需要唯一;价格;物品名称(

    2024年02月11日
    浏览(31)
  • SpringBoot 整合 ChatGPT API 项目实战

    SpringBoot 整合 ChatGPT API 项目实战 一、准备工作 二、补全接口示例 三、申请API-KEY 四、JavaScript调用API 五、SpringBoot使用ChatGPT API 体验到了ChatGPT的强大之后,那么我们会想,如果我们想基于ChatGPT开发一个自己的聊天机器人,这个能搞定吗? ChatGPT平台已经为技术提供了一个入口

    2023年04月20日
    浏览(25)
  • SpringBoot 整合ChatGPT API项目实战

    直接可以使用js+html开发一个对话,具体的源码如下: 注意:需要替换自己的api-key,修改这一行代码: xhr.setRequestHeader(“Authorization”, “Bearer API-KEY”)。

    2024年02月05日
    浏览(32)
  • SpringBoot整合Easy-ES操作演示文档

    1.1 官网 Easy-ES官网: https://www.easy-es.cn/ 官方示例: https://gitee.com/dromara/easy-es/tree/master/easy-es-sample 参考链接: https://blog.51cto.com/yueshushu/6193710 1.2 主要特性 **零侵入:**针对ES官方提供的RestHighLevelClient只做增强不做改变,引入EE不会对现有工程产生影响,使用体验如丝般顺滑。 *

    2024年02月07日
    浏览(39)
  • springboot3整合elasticsearch8.7.0实现为bean对象创建索引添加映射

    目录 准备工作 添加相关依赖 在yml中配置elasticsearch 主要内容 实体类 ElasticSearch配置类 测试 确认当前没有counter索引 启动spring 再次查询counter索引​ 在测试类中输出counter索引的映射 官方文档 要注意版本对应关系 spring官方文档中有版本对照表 目前我使用的都是最新的版本,

    2024年02月03日
    浏览(51)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包