当前位置:   article > 正文

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

springboot elasticsearch增删改查

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

2、nacos配置

spring:
  elasticsearch:
    rest:
      username: elastic
      password: 123456
      uris: 139.196.***.**:9200
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

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);
                }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81

5、实现增删改查

5-1、新增

elasticsearchRestTemplate.save(log);
  • 1

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"));
        }
  • 1
  • 2
  • 3
  • 4

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));
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

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());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/68740
推荐阅读
相关标签
  

闽ICP备14008679号