Springboot 操作 elasticsearch

news/2024/7/7 6:36:37 标签: elasticsearch, spring boot, java

elasticsearch_0">Springboot 操作 elasticsearch

一、es 6.8版本

使用高级客户端

pom.xml

 		<!-- ES 客户端 -->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>6.8.22</version>
        </dependency>
        <!-- ES 版本 -->
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>6.8.22</version>
        </dependency

application.yml

elasticsearch:
  host: 10.0.1.192:9200,10.0.1.192:9300

config.java

java">import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {
    @Value("${elasticsearch.host}")
    private String hostlist; // 127.0.0.1:9200

    @Bean // 高版本客户端
    public RestHighLevelClient restHighLevelClient() {
        // 解析 host 配置信息。假如以后有多个,则需要用 , 分开
        String[] split = hostlist.split(",");
        // 创建 HttpHost 数组,其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        // 创建RestHighLevelClient客户端
        return new RestHighLevelClient(RestClient.builder(httpHostArray));
    }

    // 项目主要使用 RestHighLevelClient,对于低级的客户端暂时不用
    @Bean
    public RestClient restClient() {
        // 解析host配置信息
        String[] split = hostlist.split(",");
        // 创建HttpHost数组,其中存放es主机和端口的配置信息
        HttpHost[] httpHostArray = new HttpHost[split.length];
        for (int i = 0; i < split.length; i++) {
            String item = split[i];
            httpHostArray[i] = new HttpHost(item.split(":")[0], Integer.parseInt(item.split(":")[1]), "http");
        }
        return RestClient.builder(httpHostArray).build();
    }
}

service接口

java">public interface AwGoodsService {
    public void getAll() ;
}

1、范围查询rangeQuery

实现类

java">public class AwGoodsServiceImpl implements AwGoodsService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public void getAll() {

        //创建查询请求
        SearchRequest searchRequest = new SearchRequest("goods");

        //查询条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //创建范围查询
        RangeQueryBuilder rang = QueryBuilders.rangeQuery("crawl_time").gte("2023-03-08 09:25:31").lte("2023-03-09 07:40:58");
        //设置范围查询
        searchSourceBuilder.query(rang);
        //设置查询结果降序
        searchSourceBuilder.sort("crawl_time", SortOrder.DESC);
        //设置查询主体
        searchRequest.source(searchSourceBuilder);
        //执行查询
        SearchResponse response = null;
        try {
            response = client.search(searchRequest, RequestOptions.DEFAULT);
            System.out.println(response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //获取结果
        SearchHits hits = response.getHits();
        List<AwGoodsDo> all = new ArrayList<>();
        SearchHit[] smallHits = hits.getHits();
        for (SearchHit smallHit : smallHits) {
            String sourceAsString = smallHit.getSourceAsString();
            AwGoodsDo awGoodsDo= JSON.parseObject(sourceAsString, AwGoodsDo.class);
            all.add(awGoodsDo);
        }
        System.out.println("111111"+all.get(0).toString());
        System.out.println("!!!!!"+all.toString());
    }


}

注意:

执行不同语句是不同api 比如SearchXX、GetXX、CreateXX等等

2、精确查询termQuery

java">//describe字段中含有特价的查询出来 
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("describe", "特价"));
或者
TermQueryBuilder term = QueryBuilders.termQuery("describe", "特价"));
searchSourceBuilder.query(term)

注意

不同查询就是构建不同XXQuery

searchSourceBuilder.query(XXQuery)

学习于https://maimai.cn/article/detail?fid=1744761944&efid=4C4zcI79tmI0h5aTGq_LRA

二、es 7.0以上

推荐使用easy-es 类似于mybatis plus 操作MySQL数据库

<!-- 引入easy-es的依赖,类似与mybatis plus操作es-->
        <dependency>
            <groupId>cn.easy-es</groupId>
            <artifactId>easy-es-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <!-- 排除springboot中内置的es依赖,以防和easy-es中的依赖冲突-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.elasticsearch.client</groupId>
                    <artifactId>elasticsearch-rest-high-level-client</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.elasticsearch</groupId>
                    <artifactId>elasticsearch</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>7.14.0</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>7.14.0</version>
        </dependency>

application.yaml

easy-es:
  address: 10.0.1.192:9200,10.0.1.192:9300 # es连接地址+端口 格式必须为ip:port,如果是集群则可用逗号隔开
  keep-alive-millis: 30000 # 心跳策略时间 单位:ms
  connect-timeout: 5000 # 连接超时时间 单位:ms
  socket-timeout: 600000 # 通信超时时间 单位:ms
  request-timeout: 5000 # 请求超时时间 单位:ms
  connection-request-timeout: 5000 # 连接请求超时时间 单位:ms
  max-conn-total: 100 # 最大连接数 单位:个
  max-conn-per-route: 100 # 最大连接路由数 单位:个

实体

java">@Data
@AllArgsConstructor
@NoArgsConstructor
@IndexName(value = "user",keepGlobalPrefix = true) //索引名
public class UserDo {
    //es的id(_id)
    //IdType.NONE: 由ES自动生成,是默认缺省时的配置,无需您额外配置 推荐
    //IdType.UUID: 系统生成UUID,然后插入ES (不推荐)
    //IdType.CUSTOMIZE: 由用户自定义,用户自己对id值进行set,如果用户指定的id在es中不存在,则在insert时就会新增一条记录,如果		用户指定的id在es中已存在记录,则自动更新该id对应的记录
    //实体类中被作为ES主键的字段
    @IndexId
    private String id;

    //es 对应的字段名 字段类型
    @IndexField(value = "user_name" ,fieldType = FieldType.KEYWORD)
    private String userName;

}

mapper

java">public interface UserMapper extends BaseEsMapper< UserDo> {
}

启动类扫描

java">@EsMapperScan(包路径)

service接口

java">public interface UserService {
}

service实现类

java">@Service
public class UserServiceImpl implementsUserService {
    @Autowired
    private UserMapper userMapper;

    //查询创建时间(create_time)在某个时间段的数据,方法传入起止时间和结束时间字符串
    public List<UserDo> getAllByInterval(String startDate, String endDate) {
        LambdaEsQueryWrapper<UserDo> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.ge("create_time_time",startDate);
        wrapper.le("create_time_time",endDate);
        List<UserDo> all = userMapper.selectList(wrapper);
        return all;
    }
}


注意:复杂的查询语句通过Wrapper构建

easy-es官网https://www.easy-es.cn/


http://www.niftyadmin.cn/n/230461.html

相关文章

分享一个RecyclerView嵌套webview 滑动不流畅的解决方法

因RecyclerView 和webview 或者X5的webview 都具有滑动的功能 所以在做嵌套的时候 会出现滑动不流畅 等问题 解决思路 就是判断滑动的时候 是否自身消耗 或者父布局的RecycleView消耗 开发中还遇到个问题 就是 更换成x5的时候 getScrolly() 返回的一直是0 改成getWebScrollY(…

Mysql学习(九)-- mysql字段的使用

1. 可以使用MySQL直接存储文件吗&#xff1f; 可以使用 BLOB (binary large object)&#xff0c;用来存储二进制大对象的字段类型。 TinyBlob 255 值的长度加上用于记录长度的1个字节(8位)Blob 65K值的长度加上用于记录长度的2个字节(16位)MediumBlob 16M值的长度加上用于记录…

Android UI渲染组件 HWUI

Android HWUI&#xff08;Hardware UI&#xff09;是Android系统中的一个组件&#xff0c;用于处理应用程序的UI渲染操作。相比传统的软件渲染方式&#xff0c;HWUI可以利用GPU硬件绘制界面&#xff0c;提高绘制效率和流畅度&#xff0c;同时支持一些高级特性&#xff0c;如视图…

【周末闲谈】新的编程方式,程序员的未来何在?

个人主页&#xff1a;【&#x1f60a;个人主页】 系列专栏&#xff1a;【❤️周末闲谈】 系列目录 ✨第一周 二进制VS三进制 ✨第二周 文心一言&#xff0c;模仿还是超越&#xff1f; ✨第二周 畅想AR 文章目录系列目录前言了解编程语言机器语言&#x1f4bb;&#x1f4bb;&am…

SQL语句要点一文速览

以下内容参考《SQL必知必会&#xff08;第4版&#xff09;》 了解 SQL 数据库&#xff08;database&#xff09;&#xff1a;保存有组织的数据的容器&#xff08;通常是一个文件或一组文件&#xff09;。最简单的办法是将数据库想象为一个文件柜。这个文件柜是一个存放数据的…

MATLAB 神经网络变量筛选—基于BP的神经网络变量筛选(链接在文末)

灰色系统理论是一种研究少数据、贫信息、不确定性问题的新方法&#xff0c;它以部分信息已知&#xff0c;部分信息未知的“小样本”&#xff0c;“贫信息”不确定系统为研究对象&#xff0c;通过对“部分”已知信息的生成、开发&#xff0c;提取有价值的信息&#xff0c;实现对…

数据结构入门(C语言版)栈和队列之栈的介绍及实现

栈栈的概念栈的实现过程栈的结构体与接口的定义1、静态栈结构2、动态栈结构3、栈的接口定义栈的接口实现①初始化栈(StackInit)②入栈(StackPush)③出栈(StackPop)④栈顶(StackTop)⑤栈元素个数(StackSize)⑥检测栈是否为空(StackEmpty)⑦销毁栈(StackDestroy)结语栈的概念 栈…

【毕业设计】基于程序化生成和音频检测的生态仿真与3D内容生成系统----程序化生成多图层地形贴图的算法设计

(2条消息) 【开发日志】2023.04 ZENO----Image Processing----CompositeCV、Composite2、Composite3_EndlessDaydream的博客-CSDN博客 (2条消息) 【开发日志】2023.04 ZENO----Image Processing----ImageEdit、EditRGB、EditHSV_EndlessDaydream的博客-CSDN博客 (2条消息) 【…