mongodb的BulkOperations,springboot批量插入数据时若数据库存在数据则更新,同时更新elasticSearch

// mongodb 的批量插入或者更新
            List> updateList = new ArrayList<>(userTagDocs.size());

            BulkOperations operations = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, TAG_COLLECTION_NAME);

            userTagDocs.forEach(data -> {

                Query query = new Query(new
                        Criteria("userId").is(data.getUserId()).and("code").is(data.getCode()).and("type").is(data.getType()));

                Update update = new Update();

                update.set("value", data.getValue());

                Pair updatePair = Pair.of(query, update);

                updateList.add(updatePair);

            });

            operations.upsert(updateList);

            BulkWriteResult result = operations.execute();
            
            portraitSearch.upsertTags(userTagBOS);
 /**
     * 批量添加标签时批量索引更新
     */
    public void upsertTags(List tagDTOS) {

        // 插入数据
        BulkRequest request = new BulkRequest();
        for (UserTagBO userTagBO :tagDTOS){
            String key = String.format("%s.%s", userTagBO.getType().name(), userTagBO.getCode());

            request.add(new IndexRequest(indexName, TYPE_NAME, userTagBO.getUserId().toString())
                    .source(XContentType.JSON, key, userTagBO.getValue()));

        }

        BulkResponse bulkResponse = null;
        try {
            bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("doc index failed, rentUnit: {}", tagDTOS, e);
            throw new RpcException("Es api error", e);
        }

    }

 

你可能感兴趣的:(springboot,mongodb,sprintboot,mongodb,elasticSearch)