码迷,mamicode.com
首页 > 编程语言 > 详细

springBoot2.x集成es7.x实现常见操作(增、删、该、查、分组)

时间:2020-12-18 12:50:29      阅读:2      评论:0      收藏:0      [点我收藏+]

标签:upd   shm   out   ant   rms   false   tom   let   date   

集成es

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>

配置

在properties中增加下面配置

spring.elasticsearch.rest.uris=http://localhost:9200
spring.elasticsearch.rest.username=
spring.elasticsearch.rest.password=
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig {

    private String host;

    private Integer port;

    @Bean(destroyMethod = "close")
    public RestHighLevelClient client() {
        return new RestHighLevelClient(RestClient.builder(
                new HttpHost(host, port, "http")
        ));
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }
}

这样就可以了

基本操作前提

需要的类

public class ObjectToMapUtils {

    /**
     * 将对象转换成Map
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if(beanMap.get(key) != null)
                    map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }
}
@Data
public class DocBean {

    private String id;

    private String firstCode;

    private String secordCode;

    private String content;

    private Integer type;

    private Date createdAt;

    private Long startAt;

    public DocBean(String id, String firstCode, String secordCode, String content, Integer type) {
        this.id = id;
        this.firstCode = firstCode;
        this.secordCode = secordCode;
        this.content = content;
        this.type = type;
        this.createdAt = new Date();
        this.startAt = System.currentTimeMillis();
    }

    public DocBean() {

    }
}

新增

public interface IElasticService {

    void save(DocBean docBean) throws IOException;
}
@Service
public class IElasticServiceImpl implements IElasticService {

    @Resource
    private RestHighLevelClient client;

    private static final String NBA_INDEX = "record_traffic-2020-12-10";

/**
     * 新增操作
     * @param docBean
     * @throws IOException
     */
    @Override
    public void save(DocBean docBean) throws IOException {
        IndexRequest request = new IndexRequest(NBA_INDEX).id(String.valueOf(docBean.getId())).source(ObjectToMapUtils.beanToMap(docBean));
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.out.println(JSONObject.toJSON(response));
    }
}

修改

/**
     * 更新数据
     * @param docBean
     * @throws IOException
     */
    @Override
    public void update(DocBean docBean) throws IOException {
        UpdateRequest request = new UpdateRequest(NBA_INDEX, docBean.getId()).doc(ObjectToMapUtils.beanToMap(docBean));
        client.update(request, RequestOptions.DEFAULT);
    }

删除

根据单个id删除

  @Override
    public void deleteById(String id) throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest(NBA_INDEX, id);
        client.delete(deleteRequest, RequestOptions.DEFAULT);
    }

根据id批量删除

/***
     * 删除操作。批量删除通过ids
     * @param ids
     * @throws IOException
     */
    @Override
    public void deleteByIds(String[] ids) throws IOException {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest(NBA_INDEX);
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder.must(QueryBuilders.idsQuery().addIds(ids));
        deleteByQueryRequest.setQuery(boolQueryBuilder);
        client.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
    }

查询

根据id进行查询

   @Override
    public Map<String,Object> getEs(String id) throws IOException {
        GetRequest getRequest = new GetRequest(NBA_INDEX,id);
        GetResponse response = client.get(getRequest,RequestOptions.DEFAULT);
        return response.getSource();
    }

... 后面会继续扩展

分组和统计数量

@Override
    public Map<String, Long> getTypeGroupBy() throws IOException {
        Map<String, Long> map = new LinkedHashMap<>();
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("record_traffic*");
        //指定分组字段,terms指定别名,field指定字段名
        TermsAggregationBuilder aggregation = AggregationBuilders.terms("content")
                //聚合字段名
                .field("content.keyword")
                .size(100)
                // 降序
                .order(BucketOrder.count(false));
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.aggregation(aggregation);
        //执行查询
        searchRequest.source(searchSourceBuilder);
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        Terms byAgeAggregation = response.getAggregations().get("content");
        List<? extends Terms.Bucket> buckets = byAgeAggregation.getBuckets();
        for (Terms.Bucket buck: buckets) {
            map.put(buck.getKeyAsString(), buck.getDocCount());
        }
        return map;
    }

springBoot2.x集成es7.x实现常见操作(增、删、该、查、分组)

标签:upd   shm   out   ant   rms   false   tom   let   date   

原文地址:https://www.cnblogs.com/liufei2/p/14129437.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!