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>

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());
}

你可能感兴趣的:(elasticsearch,spring,boot,java)