spring boot学习第八篇:操作elastic search的索引和索引中的数据

前提参考:elastic search入门-CSDN博客

前提说明:已经安装好了elastic search 7.x版本,我的es版本是7.11.1

1、 pom.xml文件内容如下:

<?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.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.hmblogs</groupId>
    <artifactId>hmblogs</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>hmblogs</name>
    <description>hmblogs</description>
    <properties>
        <java.version>8</java.version>
        <druid.version>1.2.8</druid.version>
        <log4jdbc.version>1.16</log4jdbc.version>
        <es.version>7.9.2</es.version>
    </properties>
    <dependencies>
        <!-- druid数据源驱动 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--Mysql依赖包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--lombok插件-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--监控sql日志-->
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>${log4jdbc.version}</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.9</version>
        </dependency>

        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>

        </dependency>

        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>

        </dependency>

        <!-- high client-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${es.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-client</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- rest-high-level-client 依赖如下2个jar -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${es.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${es.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、application.yml文件内容如下:

server:
  port: 8081
  servlet.context-path: /

#配置数据源
spring:
  datasource:
    druid:
      db-type: com.alibaba.druid.pool.DruidDataSource
      driverClassName: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
      url: jdbc:log4jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:eladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false
      username: ${DB_USER:root}
      password: ${DB_PWD:123456}
  redis:
    host: localhost
    port: 6379
    password: heming
    database: 10

es:
  host: 43.138.0.199
  port: 9200
  scheme: http

3、BackendApplication.java文件内容如下:

package com.hmblogs.backend;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }

}

4、测试验证,ElasticsearchClientTest.java文件内容如下:


import com.alibaba.fastjson.JSONObject;
import com.hmblogs.backend.entity.Users;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
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.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

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

@Slf4j
//@Component
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchClientTest {
    @Autowired
    private RestHighLevelClient client;

    String index = "users";

    /**
     * 创建索引
     *
     * @throws IOException
     */
    @Test
    public void createIndex() throws IOException {
        CreateIndexRequest indexRequest = new CreateIndexRequest(index);
        CreateIndexResponse response = client.indices()
                .create(indexRequest, RequestOptions.DEFAULT);
        log.info("创建索引:"+response.isAcknowledged());
    }

    /**
     * 判断索引是否存在
     *
     * @throws IOException
     */
    @Test
    public void indexExists() throws IOException {
        GetIndexRequest request = new GetIndexRequest(index);
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        log.info("索引是否存在:"+exists);
    }

    /**
     * 添加文档
     *
     * @throws IOException
     */
    @Test
    public void addDoc() throws IOException {
        IndexRequest request = new IndexRequest(index);
        String source = JSONObject.toJSONString(new Users(10000, "逍遥", 30));
        // 手动设置id
//        request.id("10000");
        request.source(source, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        log.info("添加文档:"+response.getResult());
    }


    /**
     * 批量添加文档
     */
    @Test
    public void batchAddDoc() throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        List<IndexRequest> requests = generateRequests();
        for (IndexRequest indexRequest : requests) {
            bulkRequest.add(indexRequest);
        }
        BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        log.info("批量添加结果:"+!responses.hasFailures());
    }

    public List<IndexRequest> generateRequests() {
        List<IndexRequest> requests = new ArrayList<>();
        requests.add(generateNewsRequest(1, "小明", 22));
        requests.add(generateNewsRequest(2, "隔壁老王", 30));
        requests.add(generateNewsRequest(3, "lily", 25));
        return requests;
    }

    public IndexRequest generateNewsRequest(Integer id, String name, Integer age) {
        IndexRequest indexRequest = new IndexRequest(index);
        String source = JSONObject.toJSONString(new Users(id, name, age));
        indexRequest.source(source, XContentType.JSON);
        return indexRequest;
    }

    /**
     * 更新文档
     *
     * @throws IOException
     */
    @Test
    public void updateDoc() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest(index, "AmxCP40BM8-M0To1vOET");
        Map<String, Object> params = new HashMap<>();
        params.put("id", "1");
        params.put("name", "逍遥");
        params.put("age", 33);
        params.put("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");
        updateRequest.doc(params);
        UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
        log.info("修改文档结果:"+response.getResult());
    }

    /**
     * 搜索
     *
     * @throws IOException
     */
    @Test
    public void search() throws IOException {
        SearchRequest request = new SearchRequest(index);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder
                .must(new RangeQueryBuilder("age").from(20).to(30))
                .must(new TermQueryBuilder("id", 3));
        builder.query(boolQueryBuilder);
        request.source(builder);
        log.info("搜索语句为: " + request.source().toString());
        SearchResponse search = client.search(request, RequestOptions.DEFAULT);
        log.info("搜索结果为:"+search);
        SearchHits hits = search.getHits();
        SearchHit[] hitsArr = hits.getHits();
        for (SearchHit documentFields : hitsArr) {
            log.info(documentFields.getSourceAsString());
        }
    }


    @Test
    public void search2() {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.from(0);
        sourceBuilder.size(10);
        sourceBuilder.fetchSource(new String[]{"name", "age"}, new String[]{});
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "逍遥");
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
        rangeQueryBuilder.gte(20);
        rangeQueryBuilder.lte(40);
        BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
        boolBuilder.must(matchQueryBuilder);
        boolBuilder.must(termQueryBuilder);
        boolBuilder.must(rangeQueryBuilder);
        sourceBuilder.query(boolBuilder);
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.source(sourceBuilder);
        try {
            log.info("搜索语句为: " + searchRequest.source().toString());
            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
            log.info("搜索结果为:"+search);
            SearchHits hits = search.getHits();
            SearchHit[] hitsArr = hits.getHits();
            for (SearchHit documentFields : hitsArr) {
                log.info(documentFields.getSourceAsString());
            }
        } catch (IOException e) {
            log.error("搜索报错:{}",e);
        }
    }

    /**
     * 删除文档
     * @throws IOException
     */
    @Test
    public void deleteDoc() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(index, "3g8vP40Bi8WQ8ue06wWd");
        DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
        log.info("删除结果为:"+response.getResult());
    }

    /**
     * 删除索引
     * @throws IOException
     */
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);
        AcknowledgedResponse response = client.indices()
                .delete(request, RequestOptions.DEFAULT);
        log.info("删除索引结果为:"+response.isAcknowledged());
    }

}

每个方法的作用见注释说明,

 这里点击Run search2()

然后查看console的log,验证OK

这样写代码,还是不够灵活,能不能执行自定义的SQL或者DSL语句,这样就可以不用去想办法看下Builder那些类对象怎么设置了。

其实,要想实现这样的效果,就是调用http接口而已

RestTemplateUtil.java文件内容如下:


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class RestTemplateUtil {

    @Autowired
    private RestTemplate restTemplate;

    public String post(String url,Map map){
        // 设置请求头属性
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
        String results = restTemplate.postForObject(url, httpEntity, String.class);
        return results;
    }
}

ElasticsearchClientSqlDslTest.java类文件内容如下:


import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.Map;

@Slf4j
//@Component
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchClientSqlDslTest {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Test
    public void complexQueryEsData() {
        // 请求参数
        Map map = new HashMap<>();
        map.put("query", "SELECT id,name,age FROM users order by name desc limit 6");
        String url = "http://43.138.0.199:9200/_sql?format=json";
        String studentData = restTemplateUtil.post(url, map);
        log.info("studentData:"+studentData);
    }
}

执行后,查出了数据,console如下截图:

返回数据如下:

{"columns":[{"name":"id","type":"long"},{"name":"name","type":"text"},{"name":"age","type":"long"}],"rows":[[2,"隔壁老王",30],[1,"逍遥",33],[1,"小明",22],[3,"lily",25]]}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/356064.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

C++ QT入门1——记事本基础功能实现(基本控件布局+信号与槽+文件类操作)

C QT入门1——记事本基础功能实现&#xff08;基本控件布局信号与槽文件类操作&#xff09; 一、UI界面的基础设置样式表通用配置通过样式表设置按钮三态以图片作为按钮背景 二、按键响应——☆信号与槽信号与槽基本概念按键QPushButton设置信号与槽自定义信号与槽自定义信号与…

【TCP】重传与超时机制

前言 在网络通信的世界里&#xff0c;传输控制协议&#xff08;TCP&#xff09;扮演着一个至关重要的角色。它确保了数据的可靠传输&#xff0c;就像邮差确保每一封信都能准确无误地送达收件人手中一样。但是&#xff0c;网络环境充满了不确定性&#xff0c;数据包可能会因为各…

云堡垒机是软件堡垒机吗?是一种产品吗?

很多小伙伴傻傻分不清楚云堡垒机和软件堡垒机&#xff1f;在问云堡垒机是软件堡垒机吗&#xff1f;是一种产品吗&#xff1f;两者有区别吗&#xff1f;今天我们大家就来一起探讨下&#xff0c;仅供参考哦&#xff01; 首先我们需要知道的是&#xff0c;云堡垒机和软件堡垒机是两…

数字美妆技术:美颜SDK和动态贴纸技术的崭新时代

数字美妆的兴起标志着人们对于自身形象的追求不再局限于现实生活&#xff0c;而是延伸到了虚拟世界。同时&#xff0c;美颜SDK的动态贴纸技术也开始进入到大家的视野之中。 一、美颜SDK&#xff1a;技术之作 通过复杂的图像处理算法&#xff0c;美颜SDK能够实时检测人脸&…

AWS 专题学习 P10 (Databases、 Data Analytics)

文章目录 专题总览1. Databases1.1 选择合适的数据库1.2 数据库类型1.3 AWS 数据库服务概述Amazon RDSAmazon AuroraAmazon ElastiCacheAmazon DynamoDBAmazon S3DocumentDBAmazon NeptuneAmazon Keyspaces (for Apache Cassandra)Amazon QLDBAmazon Timestream 2. Data & …

用java识别出文本中的文字并用in进行拼接

用java识别出来文本&#xff08;txt&#xff09;中的文字&#xff0c;并用in进行拼接。 话不多少&#xff0c;直接上代码。 先看结果 待转换数据&#xff1a; 处理结果&#xff1a; 代码如下&#xff1a; import java.io.*; import java.util.ArrayList; import java.util.Li…

高原涡轮增压20KVA柴油发电机产品样册

高原涡轮增压20KVA柴油发电机产品样册 大泽动力柴油发电机产品品质性能稳定、功率大、维修率好低、能适应各种恶劣环境以及高海拔地区使用&#xff1b; 发电机波形畸变率小于5%&#xff0c;适合给精密设备供电。功率衰减低&#xff0c;机组输出稳定&#xff1b;无励磁绕组&…

毕业找工作只会C语言是不是完蛋了?

今日话题&#xff0c;毕业找工作只会C语言是不是完蛋了&#xff1f;不必担心&#xff0c;C语言是一门非常有价值的编程语言&#xff0c;拥有广泛的应用领域&#xff0c;包括系统编程、嵌入式系统和驱动程序开发&#xff0c;为你提供了多样化的就业机会。学习C语言还有助于深入理…

DjangoURL调度器(一)

一、介绍 当一个用户请求 Django 站点的一个页面&#xff0c;下面是 Django 系统决定执行哪个 Python 代码使用的算法&#xff1a; Django确定要使用的根URLconf模块&#xff0c;一般是在settings中的ROOT_URLCONF设置的值&#xff0c;但是如果传入 HttpRequest 对象具有一个ur…

影响可变利差有几个因素,Anzo Capital昂首资本再说两个

在之前的文章中&#xff0c;Anzo Capital昂首资本抛砖引玉说了影响可变利差的两个因素&#xff0c;后台评论区也是热闹非凡&#xff0c;纷纷留言讨论&#xff0c;攻陷了评论区&#xff0c;今天Anzo Capital昂首资本就把各位投资者的留言进行整理&#xff0c;继续补充影响可变…

航空MRO行业研究:2027年全球市场将达1200亿美元

随着全球航空运输业的不断发展&#xff0c;越来越多的航空器进入了使用年限&#xff0c;需要进行维修、修理和大修。这促进了航空MRO市场的不断增长。此外&#xff0c;航空器设备和技术的不断更新换代&#xff0c;也对航空MRO市场带来了新的机遇和挑战。 航空MRO市场是指维修、…

2024最新版IntelliJ IDEA安装使用指南

2024最新版IntelliJ IDEA安装使用指南 Installation and Usage Guide to the Latest JetBrains IntelliJ IDEA Community Editionn in 2024 By JacksonML JetBrains公司开发的IntelliJ IDEA一经问世&#xff0c;就受到全球Java/Kotlin开发者的热捧。这款集成开发环境&#xf…

vue-admin-template框架

vue-admin-template框架地址&#xff1a;项目地址 项目预览地址&#xff1a;项目预览 框架简介&#xff1a;这是一个极简的 vue admin 管理后台。它只包含了 Element UI & axios & iconfont & permission control & lint&#xff0c;这些搭建后台必要的东西。 …

go包与依赖管理

包&#xff08;package&#xff09; 包介绍 Go语言中支持模块化的开发理念&#xff0c;在Go语言中使用包&#xff08;package&#xff09;来支持代码模块化和代码复用。一个包是由一个或多个Go源码文件&#xff08;.go结尾的文件&#xff09;组成&#xff0c;是一种高级的代码…

uniCloud ---- JQL语法 连表查询

目录 JQL数据库操作 JQL流程图解 JQL的限制 单表查询 联表查询 新增 修改 删除 联表查询 例子 字段过滤field 字段别名as 限制查询记录的条数limit 只查一条记录getone JQL数据库操作 JQL&#xff0c;全称 javascript query language&#xff0c;是一种js方式操…

vue3 el-pagination 将组件中英文‘goto’ 修改 为 中文到‘第几’

效果如图&#xff1a; 要求&#xff1a;将英文中Go to 改为到第几 操作如下&#xff1a; <template><div class"paging"><el-config-provider :locale"zhCn"> // 注意&#xff1a;这是重要部分<el-pagination //分页组件根据官…

解锁创意无限:Adobe Photoshop 2023(PS2023)引领设计革命

Adobe Photoshop 2023 (PS2023)&#xff0c;作为图像处理软件的翘楚&#xff0c;以其卓越的性能和无限的可能性&#xff0c;继续引领着数字创意设计的潮流。对于设计师、摄影师、艺术家以及那些对视觉效果有高要求的人们来说&#xff0c;PS2023无疑是他们的必备工具。 在PS202…

OpenHarmony—ArkTS限制throw语句中表达式的类型

规则&#xff1a;arkts-limited-throw 级别&#xff1a;错误 ArkTS只支持抛出Error类或其派生类的实例。禁止抛出其他类型&#xff08;例如number或string&#xff09;的数据。 TypeScript throw 4; throw ; throw new Error();ArkTS throw new Error();限制省略函数返回类…

SpringBoot + Mybatis 快速入门实战

一.创建Spring项目 出现报错的话&#xff0c;换一个jdk创建&#xff0c;一般java 8 选择Spring Web 测试一下 默认端口8080&#xff0c;但是Vue也需要8080&#xff0c;因此&#xff0c;后端设置一个端口3000 再次测试&#xff0c;成功 此处&#xff0c;如何kill一个端口占…

Spring Cloud + Vue前后端分离-第14章 项目优化

源代码在GitHub - 629y/course: Spring Cloud Vue前后端分离-在线课程 Spring Cloud Vue前后端分离-第14章 项目优化 14-1 项目初始化 1.增加readme.md&#xff0c;添加项目介绍 2.修改初始化sql README.md readme.md是用来写一些项目描述信息&#xff0c;git远程仓库可…
最新文章