elasticsearchTemplate 根据id主键进行操作

这段代码展示了如何使用 ElasticsearchTemplate 进行数据操作。包括根据 ID 批量查询和分页查询文档,通过主数据 ID 删除记录,以及按条件批量删除。同时,还演示了如何更新文档的特定字段,如增加视图计数。所有操作都确保了事务的正确处理。
摘要由CSDN通过智能技术生成

1. 主要代码

1.1 查询
    /**
     * 根据ID批量查询数据
     *
     * @param index 数据所在索引
     * @param ids   id清单
     * @author: leiming5
     */
    @Override
    public List<ProcessEsVo> queryBatch(String index, List<String> ids) {

        Client client = elasticsearchTemplate.getClient();

        //新建查询
        SearchRequestBuilder searchRequestBuilder = client.prepareSearch(index);
        TermsQueryBuilder termsQuery = QueryBuilders.termsQuery("_id", ids);
        searchRequestBuilder.setQuery(termsQuery);
        SearchResponse response = searchRequestBuilder.get();

        // 返回搜索结果
        SearchHits searchHits = response.getHits();
        return getProcessHitList(searchHits);
    }

	/**
	 * 分页查询
	 */
    public List<QesDocumentVo> getDocumentByIdList(List<String> docIdList) {
        List<QesDocumentVo> qesDocumentVoList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(docIdList)) {
            return qesDocumentVoList;
        }
        SearchRequestBuilder searchRequestBuilder = initBaseRequestBuilder();
        searchRequestBuilder.setFrom(0).setSize(1000);
        searchRequestBuilder.setQuery(QueryBuilders.termsQuery("_id", docIdList));
        SearchResponse response = searchRequestBuilder.get();
        // 返回搜索结果
        SearchHits hits = response.getHits();
        if (hits.getTotalHits() <= 0) {
            return qesDocumentVoList;
        }
        return getHitList(hits);
    }
1.2 删除
    
    /**
     * 通过主数据id,删除es中的数据
     *
     * @param index 主数据索引
     * @param id    主数据id
     * @author: leiming5
     */
    @Override
    public void deleteByIndexAndSubjectId(String index, Long id) {

        List<String> list = Arrays.asList("question", "quality_college", "definition", "bms");
        if (!list.contains(index)) {
            return;
        }

        EsEnum esEnum = EsEnum.getByIndexName(index);

        elasticsearchTemplate.delete(index, esEnum.getType(), String.valueOf(id));
    }
    /**
     * 根据ID批量删除指定索引数据
     *
     * @param index   删除数据所在索引
     * @param docType 删除数据文档类型
     * @param ids     待删除id清单
     */
    @Override
    public void batchDelete(String index, String docType, List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        Client client = elasticsearchTemplate.getClient();
        BulkRequestBuilder bulkRequestBuilder = elasticsearchTemplate.getClient().prepareBulk();
        for (String docId : ids) {
            bulkRequestBuilder.add(client.prepareDelete(index, docType, docId));
        }
        BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();
        if (bulkResponse.hasFailures()) {
            log.error(bulkResponse.buildFailureMessage());
        }
    }

    /**
     * 按指定Query条件删除ES数据。
     *
     * @param index   删除数据所在索引
     * @param docType 删除数据文档类型
     * @param field   字段名称
     * @param value   匹配的值
     */
    @Override
    public void deleteByQuery(String index, String docType, String field, List<String> value) {
        DeleteQuery deleteQuery = new DeleteQuery();
        deleteQuery.setIndex(index);
        deleteQuery.setType(docType);
        deleteQuery.setQuery(QueryBuilders.termsQuery(field, value));

        elasticsearchTemplate.delete(deleteQuery);
    }
1.3 修改
    @SneakyThrows
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer updateFieldByLLCenter(Long id, Long viewCount) {
        //根据 任务id分组进行求和
        Client client = elasticsearchTemplate.getClient();
        //对应的es的索引库
        String index = "ll_center";
        String type = "center";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("viewcount", viewCount + 1L);
        UpdateRequest updateRequest = new UpdateRequest();
        updateRequest.index(index);
        updateRequest.type(type);
        updateRequest.id(id.toString());
        updateRequest.doc(jsonBuilder().startObject().field("viewcount", viewCount + 1L).endObject());
        RestStatus status = client.update(updateRequest).actionGet().status();
        return status.getStatus();
    }

2 相关代码

    private List<ProcessEsVo> getProcessHitList(SearchHits hits) {
        List<ProcessEsVo> list = Lists.newArrayList();
        if (hits != null || hits.getTotalHits() != 0) {
            for (SearchHit searchHit : hits) {
                list.add(convertSearchHit2Vo(searchHit, ProcessEsVo.class));
            }
        }
        return list;
    }

    private <T extends BaseESVo> T convertSearchHit2Vo(SearchHit searchHit, Class<T> clazz) {
        JSONObject jsonObject = JSON.parseObject(searchHit.getSourceAsString());
        jsonObject.put("id", searchHit.getId());
        if (MapUtils.isNotEmpty(searchHit.getHighlightFields())) {
            searchHit.getHighlightFields().forEach((k, v) -> {
                String hight = "";
                for (Text text : v.getFragments()) hight += text.string();
                setJsonProperty(jsonObject, v.getName(), hight);
            });
        }
        return JSONObject.toJavaObject(jsonObject, clazz);
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值