morphia icon indicating copy to clipboard operation
morphia copied to clipboard

Batch insert performance issue

Open rahimalizada opened this issue 13 years ago • 7 comments

Performace for inserting 150_000 objects (with duplicate (or existing in collection) ids and WriteConcern UNACKNOWLEDGED or ERRORS_IGNORED):

Native DB batch insert: 2-3 seconds via Morphia's AdvancedDatastore insert(object): 15+ seconds via Morphia's AdvancedDatastore insert(Iterable): 400+ seconds

v. 0.105

More at http://stackoverflow.com/questions/20048983/morphia-stops-when-inserting-objects-with-predefined-ids

rahimalizada avatar Nov 18 '13 15:11 rahimalizada

Using version 0.107 of Morphia, I ran into the same performance issue when trying to bulk insert a few thousand documents into a collection.

I looked into the source code for DatastoreImpl.java (with relevant parts reproduced below for convenience), and discovered that the culprit is in the involvedObjects map in the insert method. Assuming that we are bulk inserting N documents, and each call to toDbObject adds O(1) entries into involvedObjects, then the final state of involvedObjects will contain O(N) entries. For each document being added, the code calls postSaveGetKey which in turn calls postSaveOperations. Each call to the postSaveOperations method iterates through the involvedObjects map once, so postSaveOperations takes at least O(N) time. Therefore, the insert method is an at least O(N^2) operation. This seems like the performance bottleneck in the bulk insert.

I have not cloned the latest source codes to test, but from looking at this code I observed that mc.callLifecycleMethods will also be called O(N^2) times as well. When I added a @PostPersist method into my Morphia model and perform a bulk insert with version 0.107 of Morphia, I noticed that the @PostPersist method gets called O(N^2) times instead of the expected N times. This seems like a bug and I think it exists in the latest codes as well.

The current code creates one copy of involvedObjects for the entire set of documents to be inserted. I don't understand the Morphia codebase very well, but I believe the solution might be instead to create one instance of involvedObjects for each document. However, I have not tested this proposed solution.

    private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) {
        final List<DBObject> list = entities instanceof List
                                    ? new ArrayList<DBObject>(((List<T>) entities).size())
                                    : new ArrayList<DBObject>();

        final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
        for (final T ent : entities) {
            list.add(toDbObject(involvedObjects, ent));
        }

        dbColl.insert(list.toArray(new DBObject[list.size()]), wc);

        final List<Key<T>> savedKeys = new ArrayList<Key<T>>();
        final Iterator<T> entitiesIT = entities.iterator();
        final Iterator<DBObject> dbObjectsIT = list.iterator();

        while (entitiesIT.hasNext()) {
            final T entity = entitiesIT.next();
            final DBObject dbObj = dbObjectsIT.next();
            savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
        }

        return savedKeys;
    }

    protected <T> Key<T> postSaveGetKey(final T entity, final DBObject dbObj, final DBCollection dbColl,
                                        final Map<Object, DBObject> involvedObjects) {
        // ... snip ...
        postSaveOperations(entity, dbObj, involvedObjects);
        // ... snip ...
    }

    private <T> void postSaveOperations(final Object entity, final DBObject dbObj, final Map<Object, DBObject> involvedObjects) {
        mapper.updateKeyInfo(entity, dbObj, createCache());

        //call PostPersist on all involved entities (including the entity)
        for (final Map.Entry<Object, DBObject> e : involvedObjects.entrySet()) {
            final Object ent = e.getKey();
            final DBObject dbO = e.getValue();
            final MappedClass mc = mapper.getMappedClass(ent);
            mc.callLifecycleMethods(PostPersist.class, ent, dbO, mapper);
        }
    }

yeefan avatar Apr 07 '14 04:04 yeefan

That method will likely be rewritten on top of 2.12's bulk write API but I will definitely take a look and make sure this gets cleaned up either way. Thanks for the hard work you've done here.

evanchooly avatar Apr 07 '14 12:04 evanchooly

I just reworked that method and can now create and insert 1.5M objects in just over 50s.

evanchooly avatar Apr 09 '14 19:04 evanchooly

Thanks! Interesting thing is, when I briefly looked at the updated code, it seems that what was originally a bulk insert is no longer a bulk insert, because you are now inserting documents one by one.

yeefan avatar Apr 10 '14 12:04 yeefan

Would you want to consider the following idea for implementing the bulk insert method?

WARNING: The following code proposal is most likely wrong. Most likely wrong because it might call the @PrePersist and @PreSave methods twice (not tested). Also, I don't fully understand the side effects of calling toDbObject twice per entity. However, it's lighting fast for both UNACKNOWLEDGED and ACKNOWLEDGED write concerns.

    private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) {
        final List<DBObject> dbObjs = (entities instanceof Collection)
                ? new ArrayList<DBObject>(((Collection) entities).size())
                : new ArrayList<DBObject>();
        for (final T entity : entities) {
            final DBObject dbObj = toDbObject(entity, null);
            dbObjs.add(dbObj);
        }

        dbColl.insert(dbObjs, wc);

        List<Key<T>> savedKeys = new ArrayList<Key<T>>(dbObjs.size());
        for (final T entity : entities) {
            final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();
            final DBObject dbObj = toDbObject(entity, involvedObjects);
            savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
        }

        return savedKeys;
    }

yeefan avatar Apr 11 '14 20:04 yeefan

I've been looking at a similar approach, actually. I've just been busy with other things and haven't had a chance to dig in to just now.

On Fri, Apr 11, 2014 at 4:16 PM, Yee Fan Tan [email protected]:

Would you want to consider the following approach?

WARNING: The following code proposal is most likely wrong. Most likely wrong because it might call the @PrePersist and @PreSavemethods twice (not tested). However, it's lighting fast for both UNACKNOWLEDGED and ACKNOWLEDGED write concerns.

private <T> Iterable<Key<T>> insert(final DBCollection dbColl, final Iterable<T> entities, final WriteConcern wc) {

    final List<DBObject> dbObjs = (entities instanceof Collection)
            ? new ArrayList<DBObject>(((Collection) entities).size())
            : new ArrayList<DBObject>();
    for (final T entity : entities) {
        final DBObject dbObj = toDbObject(entity, null);
        dbObjs.add(dbObj);
    }

    dbColl.insert(dbObjs, wc);

    List<Key<T>> savedKeys = new ArrayList<Key<T>>(dbObjs.size());
    for (final T entity : entities) {

        final Map<Object, DBObject> involvedObjects = new LinkedHashMap<Object, DBObject>();

        final DBObject dbObj = toDbObject(entity, involvedObjects);

        savedKeys.add(postSaveGetKey(entity, dbObj, dbColl, involvedObjects));
    }

    return savedKeys;
}

Reply to this email directly or view it on GitHubhttps://github.com/mongodb/morphia/issues/554#issuecomment-40248753 .

evanchooly avatar Apr 11 '14 20:04 evanchooly

I see, thanks.

yeefan avatar Apr 11 '14 20:04 yeefan