MongoDB java驱动程序批量更新与常规更新性能

时间:2015-12-18 16:00:20

标签: java performance mongodb mongodb-query mongodb-java

我在我的应用程序中使用MongoDB java驱动程序。

在特定用例中,我不得不更新集合中的大量记录。我发现使用MongoDb Java驱动程序BulkUpdate API的性能远远低于常规更新。这真的很奇怪,我认为批量更新方法应该会提高性能。

以下是具体细节 - 收集有270k records。有大约17k update个语句要执行。数据库是本地安装的。

批量更新代码

public void scramble(String collectionName, String fieldName) {
    final List<String> distinctValues = getDistinctValues(collectionName, fieldName);
    final BulkWriteOperation bulk = mongoDb.getCollection(collectionName).initializeUnorderedBulkOperation();
    for (final String actualValue : distinctValues) {
        if (!StringUtils.isEmpty(actualValue)) {
            final String scrambledValue = getScrambledValue(actualValue);
            update(fieldName, actualValue, scrambledValue, bulk);
        }
    }
    bulk.execute();
}

protected void update(String fieldName, String actualValue, String scrambledValue, BulkWriteOperation bulk) {
    final DBObject searchQuery = new BasicDBObject(fieldName, actualValue);
    final DBObject updateQuery = new BasicDBObject("$set", new BasicDBObject(fieldName, scrambledValue));
    bulk.find(searchQuery).update(updateQuery);
}

常规更新代码

public void scramble(String collectionName, String fieldName) {
    final List<String> distinctValues = getDistinctValues(collectionName, fieldName);
    for (final String actualValue : distinctValues) {
        if (!StringUtils.isEmpty(actualValue)) {
            final String scrambledValue = getScrambledValue(actualValue);
            update(collectionName, fieldName, actualValue, scrambledValue);
        }
    }
}

protected void update(String collectionName, String fieldName, String actualValue, String scrambledValue) {
    final DBObject searchQuery = new BasicDBObject(fieldName, actualValue);
    final DBObject updateQuery = new BasicDBObject("$set", new BasicDBObject(fieldName, scrambledValue));
    mongoDb.getCollection(collectionName).update(searchQuery, updateQuery);
}

批量更新API代码耗尽1.5 hrs,定期更新耗尽2-3 mins。 有人可以解释一下这种行为。

0 个答案:

没有答案