Bulk Inserts and Collection Constraints
I don't think I'm using indexes correclty.
When merging 10,000+ records from a remote database into a local database, I have to use the id (not the $loki id) to make sure the document is not already there. (if its there I want to merge instead of update). To do this effeciently, I'm trying to use Loki indices:
let loki = new Loki('testdb');
myCollection = loki.addCollection('myCollection', {indices:['id']})
Then on each insert I do
localRecord = myCollection.findOne({id: remoteRecord.id})
if( localRecord ) {
// Merge code
} else {
myCollection.insert( remoteRecord );
}
When I disable the localRecord check and just insert, things are smoking fast! Only slowed by data fetching/paging.
- http://screencast.com/t/H3wsetchhQ
When I enable the findOne check, things slow down a bit:
- http://screencast.com/t/gBJQ49yBJwW
When I hack an index to the side that is a big hash of ids mapped to $loki I get really fast again.
- http://screencast.com/t/V5R0g7hPt
I think there must be something I don't understand about indexes.
Please advise :)
Interesting... what you are describing is not so much an index but a constraint.
Yea the problem being that on every insert you are invalidating the index and it needs to be rebuilt for the findOne.
Maybe @seriousme (who is exploring similar value hash lookups) can look into a unique constraint functionality using an approach similar to what you described. This might be something you can define on the collection and let loki handle that for you or just a checkConstraint(indexName, value) type test function.
Our current indexes are designed for optimal search speeds when the ratio of insert/read is either above or below 50%. if you do a lot of inserts and one search it rebuilts index once. if you do a single insert and a lot of finds it also rebuilts once. insert/find/insert/find is worse case scenario we might alleviate with a check constraint functionality.
@jrhicks @obeliskos @seriousme this is a discussion we have been having through email and it's good to see that real-life scenarios are highlighting the necessity for optimization in the indexing system. In the case of @jrhicks 's app, a unique index is ideal. As pointed out by @seriousme , even on sorted data, hashmap lookups will always be faster than binary search. From this I draw two conclusions:
- the need to support the "unique" type of index, much like any major DBMS around
- the need to let the user choose the best index for their application, so to achieve the best performance.
A unique index is a relatively trivial piece of work to implement, my first and obvious idea is to create a hashmap whose keys are the values of the property to be indexed and the values are their position in the data array. I am open to suggestions!
Sounds good. Do we also keep $loki id or do we trust user would not have changed the constrained property?
i'd say we keep it. get(int) will work with $loki, and we could extend get to work like get(var, indexName) => gets a record by index name. Opinions?
Sounds good to me!
@techfort You rock! I was able to ditch my hack index, and just check-before-insert a little differently with much better results http://screencast.com/t/JLOAJLPTfj
Basically the only delay is the data fetching/paging!
So given a batch of 1000 data. I first find all the ones that are already in my db
for (let d of data) {
localRec = db[collectionName].findOne({id: d.id})
if (localRec) {
localRecords[localRec.id] = localRec;
}
}
Then, when I loop over the inserts I just check the disposable localRecords.
if (localRec[remoteRec.id]) {
console.log("TODO: Merge");
} else {
let r = db[collectionName].insert(remoteRec);
localRec[r.id] = r;
loadJob.data.shift();
}
@jrhicks woah that's fast :) so how do we go about making this a LokiJS facility for everybody?
@techfort I think your on to something with constraints!
In lieu of constraints, maybe a bulkInsert function that returns the records that failed the constraint???
notInsertedRecords = myCollection.bulkInsert(records, {uniqueConstraint: ['id']})
@techfort - I think your correct. The best thing would be to be able to create a constraint, but also have a bulk insert routine that respected the constraint. I guess its getting kinda late there - no reply necessary.
@jrhicks this sounds good to me, have you got a PR for that or do you want us to tackle this? (just wondering seeing you seem to have it working). @obeliskos you good with that?
Sounds good, @seriousme recently optimized the 'inserts' so its likely this is hitting optimization on two fronts (query and inserts). I sure you guys can coordinate this as long as you leave the existing path optimizations. If others don't I may add more elaborate benchmark cases soon to gauge varied usages.
@techfort I'm timid to update core code. Maybe after I've been using the product longer. I do feel interested in helping to contribute to documentation though. As time permits, I can start a conversation about that in a diferent thread.
@jrhicks no problem, I'll take a look at your implementation on the github project you referenced in the post and credit you in logs/commits/etc. This all looks great, the post /video is impressive!
As already discussed by mail there are various options to deal with indices. (e.g. exact unique, exact non-unique, ordered (which is the current default) etc).
As shown by the initial posting its rather surprising to users that the first query after insert/update takes so long. So I'd try to fix that as well by doing binary index updates instead of full index rebuild. The only place to do full index rebuild might be on bulk updates where it is explainable that updating the index a record at the time might be suboptimal compared to updating the index only once per bulk update. (but even then.. ;-))
I think that the additional feature proposed by @jrhicks to have:
notInsertedRecords = myCollection.bulkInsert(records, {uniqueConstraint: ['id']})
is a nice addition to that. However as with traditional databases I'd rather define a uniqueIndex on the DB upfront and then reject the inserts that would break uniqueness.
e.g. something like:
myCollection = loki.addCollection('myCollection', {indices:[{ 'id': 'uniqueIndex' }]})
notInsertedRecords = myCollection.bulkInsert(records)
Where notInserted records would be a list of records with an indication why they were rejected. (e.g. " 'id' not unique" etc..)
When doing all this its important to keep in mind that all additional functionality comes at a price of adding complexity and code size. @jrhicks already showed that there is a workaround :-)
Its up to @techfort to decide which direction he wants to take Loki :-)
I agree with @seriousme, define the constraint upfront and do not offer the option on the bulkInsert. I think we all agree on this. @techfort @obeliskos
As a matter of preference, I kinda like this api. Is this more backwards compatible?
myCollection = loki.addCollection('myCollection', {indices:['name'], uniqueIndices: ['id']});
And maybe the returned results is better considered as errors as apposed to notInsertedRecords.
errors = myCollection.bulkInsert(records)
Yes, upfront index declaration is my preferred way too. Also the addition of a property in the options property is the most backward compatible. As for errors, I'm all for returning results, let's not forget that Collection emits 'error' events, that's also an option to manage errors.
@seriousme @obeliskos @jrhicks index update (as @seriousme points out) is the way to go on binary indexes. Funnily enough, I implemented a (quite hidden) Key Value store class in Loki ( * ), and I used a binary search to establish the position at which a new element should slot into an existing sorted structure/array. What makes this Binary Search interesting is that it returns whether a value was found or not, and the index at which the value is or should be if it were to be inserted. So from there you would simply apply a splice at the specified position and off you go, no need to rebuild the index. You can see that BS function here: https://github.com/techfort/LokiJS/blob/master/src/lokijs.js#L3434 This should save us a bit of time when doing inserts/updates.
Bottom line we're good to go with the upfront declaration as far as I'm concerned.
( * ) the key-value store class is only there because keys can be complex structures such as objects or arrays. This is because I thought maybe at some stage you may want to use Loki objects as keys for values.
this is good. Strange though, this message didn't turn up on github..
On Wed, Mar 25, 2015 at 4:15 PM, Jeffrey Hicks [email protected] wrote:
To be most backwards compatible, I think the default
insert
save
Should throw and error if a constrain was violated. So we may need a pattern to have methods that return errors as apposed to throwing an error. Ruby uses an exclamation point to distinguish between the two. Maybe the soft (return errors on failure). Might be???
tryInsert
trySave
That doesn't. This communicates clearly that the action may fail and return an error. Just an idea.
— Reply to this email directly or view it on GitHub https://github.com/techfort/LokiJS/issues/119#issuecomment-86101189.
great post @seriousme... i think you have great understanding of what can be done with this.
Yes @techfort's function sounds like it should do the trick. The 'unique' part of this should make it simpler (single position).
I'm sure as this is being implemented we will be able to tell if providing a batch method could offer performance boost.
@jrhicks @seriousme @obeliskos I'm going ahead on the development of exact and unique constraints, stay tuned and happy Easter!
@techfort Awesome! Happy Easter :)