Springboot 操作 elasticsearch

文章介绍了如何在Springboot项目中使用Elasticsearch的High-Level客户端进行数据操作,包括配置依赖、建立连接、范围查询和精确查询。此外,还提到了Elasticsearch7.0及以上版本推荐使用easy-es库进行操作。
摘要由CSDN通过智能技术生成

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

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接口

public interface AwGoodsService {
    public void getAll() ;
}

1、范围查询rangeQuery

实现类

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

//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 # 最大连接路由数 单位:个

实体

@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

public interface UserMapper extends BaseEsMapper< UserDo> {
}

启动类扫描

@EsMapperScan(包路径)

service接口

public interface UserService {
}

service实现类

@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/

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值