Elasticsearch与SpringBoot整合笔记 High-level-client-rest方式

一. 加入依赖

需要对应ES版本

        
        
            org.elasticsearch.client
            elasticsearch-rest-high-level-client
            7.1.1
        
        
            org.elasticsearch
            elasticsearch
            7.1.1
        

        
        
            com.alibaba
            fastjson
            1.2.58
        

        
        
            org.projectlombok
            lombok
        

二.配置 application.yml

es:
  host: 127.0.0.1
  port: 9200
  protocol: http
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Configuration
public class EsEnvironmentProperties{

    @Value("${es.host}")
    private String host; // ES请求地址

    @Value("${es.port}")
    private int port; //端口

    @Value("${es.protocol}")
    private String protocol; //协议
    
    // 可配置多ES
    @Bean(name = "restHighLevelClientPre")
    public RestHighLevelClient getRestHighLevelClientPre() {
        return new RestHighLevelClient(RestClient
                .builder(new HttpHost(host, port, protocol)));
    }
}

三. 封装ES操作

@Component
public class ESUtils {

    private static RestHighLevelClient restHighLevelClient;

    private static volatile ESUtils eSUtils;
    private ESUtils(){}

    public static  ESUtils getInstance(RestHighLevelClient restclient) {
        restHighLevelClient = restclient;

        if (eSUtils == null) {
            synchronized (ESUtils.class) {
                if (eSUtils == null) {
                    eSUtils = new ESUtils();
                }
            }
        }
        return eSUtils;
    }

    /** 
     * 查询
     * @param index 索引
     * @param searchSourceBuilder
     */
    public SearchResponse searchBySearchSourceBuilde(String index,
                                                     SearchSourceBuilder searchSourceBuilder) throws IOException {
        // 组装SearchRequest请求
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.source(searchSourceBuilder);
        // 同步获取SearchResponse结果
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        return searchResponse;
    }
    
    /**
     * 批量插入  批量修改删除原理相同,也可混合 只需在 bulkRequest.add 不同请求即可
     * @param jsonStrList  待插入集合 注:每个String元素需为json字符串
     * @param index 索引
     * @return
     */
    public BulkResponse bulkInsert(List jsonStrList,String index) {
        BulkRequest bulkRequest = new BulkRequest();

        for (String jsonStr : jsonStrList) {
            IndexRequest indexRequest = new IndexRequest(index);
            indexRequest.source(jsonStr, XContentType.JSON);

            bulkRequest.add(indexRequest); // 加入到批量请求bulk
        }

        BulkResponse bulkResponse = null;
        try {
            bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bulkResponse;
    }
}

具体使用

@Resource(name = "restHighLevelClientPre")
RestHighLevelClient restHighLevelClient;

//查询
public void search() {
    // user_city 完全匹配 Beijing 且 (2020-6-1 <= user_time <= 2020-6-2)
    QueryBuilder queryBuilder = QueryBuilders.boolQuery()
            .must(QueryBuilders.termQuery("user_city", "Beijing"))
            .must(QueryBuilders.rangeQuery("user_time").gte("2020-6-1 00:00:00"))
            .must(QueryBuilders.rangeQuery("user_time").lte("2020-6-2 00:00:00"));

    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(queryBuilder);
    // 按 user_time 升序排序
    searchSourceBuilder.sort("user_time", SortOrder.ASC);
    // 设置返回数量
    searchSourceBuilder.size(1000);

    SearchResponse searchResponse = null;
    try {
        searchResponse = ESUtils.getInstance(restHighLevelClient)
                .searchBySearchSourceBuilde("users", searchSourceBuilder);
    } catch (IOException e) {
        e.printStackTrace();
    }
    SearchHit[] hitsArr = searchResponse.getHits().getHits();

    List userList = new ArrayList<>();
    for (SearchHit searchHit : hitsArr) {
        User user = new User();

        JSONObject source = JSONObject.parseObject(searchHit.getSourceAsString());
        user.setUser_id(source.getString("user_id"));
        user.setUser_name(source.getString("user_name"));
        userList.add(user);
    }
}

//批量插入
public void bulkInsert(List userList) {
        List jsonList = new ArrayList<>();

        for (User user : userList) {
            // User 转为 Json字符串
            jsonList.add(JSONObject.toJSONString(user));
        }
        BulkResponse bulkResponse = ESUtils.getInstance(restHighLevelClient).bulkInsert(jsonList, "users");
    }

其他修改删除等操作类似,略......

你可能感兴趣的:(ES)