ElasticSearch组件--RestHighLevelClient工具类

扶誉
2023-12-01

添加文档  source是要保存的数据  把实体转成json就行了   

String source = JSONObject.toJSONString(xxxVO)
 public static void addBatchMember(RestHighLevelClient restHighLevelClient,String index, String source) {

        BulkRequest request = new BulkRequest();
        request.add(new IndexRequest(index).source(source, XContentType.JSON));
        esBatchAdd(restHighLevelClient,request, index);
    }

    /**
     * 批量插入数据
     *
     * @param bulkRequest
     * @param index
     */
    private static void esBatchAdd(RestHighLevelClient restHighLevelClient, BulkRequest bulkRequest, String index) {
        try {
            restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (Exception e) {
        }
        log.info("插入数据----------------------{}", bulkRequest.requests().size());
    }

根据条件修改文档

public static void main(String[] args) {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("10.10.10.10", 9208, "http")));


        UpdateByQueryRequest updateByQueryRequest = new UpdateByQueryRequest();
        //如果索引有多个  updateByQueryRequest.indices("index1","index2","index3");

        //如果索引有多个并且以集合的方式传过来  List<String> indexList
         String[] objects = indexList.toArray(new String[indexList.size()]);
        //写法一:
          updateByQueryRequest.indices("index1","index2","index3");
        //写法二:
        updateByQueryRequest.indices(objects );

        //只有一个条件,直接写就行了
        // updateByQueryRequest.setQuery(new TermQueryBuilder("tall", 180.0));
        //有多个查询条件
        //must代表and   should代表or
        BoolQueryBuilder boolQueryBuilder =  QueryBuilders.boolQuery()
                .must(QueryBuilders.termQuery("name","wangXX"))
                .must(QueryBuilders.termQuery("tall","180.0"));
        updateByQueryRequest.setQuery(boolQueryBuilder);

        updateByQueryRequest.setScript(new Script(ScriptType.INLINE,
                "painless",
                "ctx._source.name='修改后的name';ctx._source.idcard='修改后的idcard'", Collections.emptyMap()));
        //数据为存储而不是更新
        try {
            client.updateByQuery(updateByQueryRequest, RequestOptions.DEFAULT);
            log.info("修改成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 类似资料: