SpringBoot整合elasticsearch实现简单增删改查

文章介绍了如何在Springboot项目中集成Elasticsearch,包括引入相关依赖、配置Nacos连接信息,创建索引,以及实现对Elasticsearch的增、删、改、查等基本操作。示例代码展示了Log类的定义和各种查询方法的使用。
摘要由CSDN通过智能技术生成

Springboot集成elasticsearch

1.引入相关依赖

 <!--引入对应版本依赖需与安装时的elasticsearch版本一致-->
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-high-level-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch.client</groupId>
            <artifactId>elasticsearch-rest-client</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.elasticsearch</groupId>
            <artifactId>elasticsearch</artifactId>
            <version>${elasticsearch.version}</version>
        </dependency>

2、nacos配置

spring:
  elasticsearch:
    rest:
      username: elastic
      password: 123456
      uris: 139.196.***.**:9200

3、创建索引

if (!elasticsearchRestTemplate.indexOps(IndexCoordinates.of(esIndexCreate.getIndexName())).exists()) {
                    // 不存在
                    IndexOperations indexOperations = null;
                    try {
                        indexOperations = elasticsearchRestTemplate.indexOps(Class.forName(esIndexCreate.getBasePackage()));
                    } catch (ClassNotFoundException e) {
                        log.error("创建索引出错=======>{}" + esIndexCreate.getIndexName());
                        e.printStackTrace();
                    }
                    indexOperations.create();
                    Document mapping = indexOperations.createMapping();
                    indexOperations.putMapping(mapping);
                }

4.log类

@Getter
@Setter
@ToString
@Document(indexName = "es_log",createIndex = false)
public class Log {

    @JsonSerialize(using = ToStringSerializer.class)
    @Id
    private Long id;

    /**
     * 请求的resources_id
     */
    @JsonSerialize(using = ToStringSerializer.class)
    private Long resourceId;

    /**
     * 单位id
     */
    @JsonSerialize(using = ToStringSerializer.class)
    private String deptId;

    /**
     * 单位Code
     */
    private String deptCode;

    /**
     * url
     */
    private String url;

    /**
     * 接口名称
     */
    private String interfaceName;

    /**
     * 请求参数(json)
     */
    private String bodyJson;

    /**
     * 调用者
     */
    private String realName;

    /**
     * 时间
     */
    private Date time;

    /**
     * 返回结果(json)
     */
    private String backJson;

    /**
     * 是否成功
     */
    private String flag;

    /**
     * 参数:get和post
     */
    private String parameterType;

    /**
     * 模块名称
     */
    private String module;

    /*客户端ip*/
    private String userIp;

    /*客户端代理*/
    private String userAgent;

    /*调用的java方法*/
    private String javaMethod;
}

5、实现增删改查

5-1、新增

elasticsearchRestTemplate.save(log);

5-2、删除

if (elasticsearchRestTemplate.indexOps(IndexCoordinates.of("overview_of_disease")).exists()) {
            NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchAllQuery()).build();
            elasticsearchRestTemplate.delete(nativeSearchQuery, OverviewOfDisease.class, IndexCoordinates.of("overview_of_disease"));
        }

5-3、修改

Document document = Document.from(map);
        document.setId(entity.getLngId());
        // 这里的UpdateQuery需要构造一个Document对象,但是Document对象不能用实体类转化而来 
        //(可见Document的源码,位于:org.springframework.data.elasticsearch.core.document 
        // 包下),因此上面才会BeanUtils.describe(entity),将实体类转化成一个map,由map转化 
        // 为Document对象。
        UpdateQuery build = UpdateQuery.builder(entity.getLngId())
                .withDocAsUpsert(false) //不加默认false。true表示更新时不存在就插入
                .withDocument(document)
                .build();
        restTemplate.update(build, IndexCoordinates.of(indexName));

5-4、普通查询

long startTime = logSearchParam.getStartTime().getTime();
long endTime = logSearchParam.getEndTime().getTime();
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().
                    withQuery(QueryBuilders.boolQuery().must(QueryBuilders.boolQuery()
                    // 时间范围
                            .must(QueryBuilders.rangeQuery("time").from(startTime).to(endTime))
                            .must(QueryBuilders.matchQuery("deptId", logSearchParam.getDeptId()))));
SearchHits<LogShowVo> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), LogShowVo.class);

5-5、分组分页查询

PageRequest pageRequest = PageRequest.of(logSearchParam.getPage() - 1, logSearchParam.getSize());
// 分组
TermsAggregationBuilder builder = AggregationBuilders.terms("urlGroup").field("url.keyword");
NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().
                    withQuery(QueryBuilders.boolQuery().must(QueryBuilders.boolQuery()
                            .must(QueryBuilders.rangeQuery("time").from(startTime).to(endTime))
                            .must(QueryBuilders.matchQuery("deptId", logSearchParam.getDeptId()))));
// 获取分组
SearchHits<LogShowVo> searchHits =
                  elasticsearchRestTemplate.search(queryBuilder.addAggregation(builder).withPageable(pageRequest).build(), LogShowVo.class);
// 获取分组统计信息
List<LogShowVo> logShowVos = searchHits.stream().map(SearchHit::getContent).collect(Collectors.toList());

if (logShowVos != null && logShowVos.size() > 0) {
     Aggregations aggregations = searchHits.getAggregations();
     Terms terms = aggregations.get("urlGroup");

     Map<String, Integer> map = new HashMap<>();
     for (Terms.Bucket bucket : terms.getBuckets()) {
         String keyAsString = bucket.getKeyAsString();
         long docCount = bucket.getDocCount();
         map.put(keyAsString, (int) docCount);
     }

     for (LogShowVo logShowVo : logShowVos) {
         logShowVo.setCount(map.get(logShowVo.getUrl()));
     }
 }
 // 获取计数信息
 long total =0;
 CardinalityAggregationBuilder agg = AggregationBuilders.cardinality("count").field("url.keyword");
 SearchHits<LogShowVo> searchTotalHits =
                elasticsearchRestTemplate.search(queryBuilder.withCollapseField("url.keyword").addAggregation(agg).build(), LogShowVo.class);
Aggregations aggregations = searchTotalHits.getAggregations();
if (aggregations != null) {
    // 获取计数信息
    ParsedCardinality fileCount = searchTotalHits.getAggregations().get("count");
    total = NumberUtil.parseLong(fileCount.getValueAsString());
}
你可以按照以下步骤使用 Spring BootElasticsearch 实现增删改查的功能: 1. 添加依赖:在你的 Spring Boot 项目的 pom.xml 文件中,添加 Elasticsearch 相关的依赖。例如: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置 Elasticsearch:在你的 application.properties 或 application.yml 文件中,配置 Elasticsearch 的连接信息。例如: ```yaml spring.data.elasticsearch.cluster-nodes=localhost:9200 ``` 3. 创建实体类:创建一个代表你要操作的数据的实体类,并使用注解来映射到 Elasticsearch 中的索引和类型。例如: ```java import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "your_index_name", type = "your_type_name") public class YourEntity { @Id private String id; private String name; // 其他属性和方法 } ``` 4. 创建数据访问接口:创建一个继承自 ElasticsearchRepository 的数据访问接口,该接口提供了一些基本的 CRUD 方法。例如: ```java import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface YourEntityRepository extends ElasticsearchRepository<YourEntity, String> { // 可以根据需要添加自定义的查询方法 } ``` 5. 编写业务逻辑:在你的服务类中使用 YourEntityRepository 来进行相关的数据操作。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class YourService { @Autowired private YourEntityRepository repository; public YourEntity save(YourEntity entity) { return repository.save(entity); } public void delete(String id) { repository.deleteById(id); } public Iterable<YourEntity> findAll() { return repository.findAll(); } // 可以根据需要添加其他的查询方法和业务逻辑 } ``` 这样,你就可以通过调用 YourService 中的方法来实现Elasticsearch增删改查操作了。希望对你有帮助!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值