PouchDb find : why is my index not used?
Asked Answered
H

1

2

I'm using PouchDb and the plugin PouchDb-find to query my local DB in an ionic web app. In almost every use case, I get the following warning when querying whereas I've created an index:

{
    "docs": {
        ...
    },
    "warning": "no matching index found, create an index to optimize query time"
}

Starting from an example of the plugin documentation, I get this warning so I am wondering what I am doing wrong.

Here is an example:

var db = new PouchDB('test');

var docs = [];
for (var i = 0; i < 10; i++) {
  docs.push({title: 'Lorem ipsum ' + i, _id: 'doc' + (i + 1)});
}

db.bulkDocs(docs)
  .then(
    function () {
      return db.createIndex({index: {fields: ['title']}});
    })
  .then(
    function () {
      // return db.find({selector: {title: {$eq: 0}}}); // No warning
      return db.find({selector: {title: {$ne: 0}}}); // Warning
    })
  .then(
    function (res) {
      console.log(res);
    })
  .catch(console.error.bind(console));

Why the index is used when using $eq and is not with $ne ?

Then, I have a more complex case with the following query (assuming 'a.deep.property' always exists and is an Array) :

db.find(
    {
        selector: {
            $not:{
                "a.deep.property": {$size:0}
            }
        }
    }
);

I've created an index with the field 'a.deep.property'. The index is not used either. What index do I need to create ?

I also tried to create an index manually and to use query() in the previous case but this was slower than using PouchDb-find.

Any idea ?

Hussy answered 21/7, 2016 at 7:41 Comment(0)
S
3

$ne currently does not use any index. You would have to use something like $gt or $lt instead. E.g. instead of $ne: 0 you would do {$gt: 0, $lt: 0}.

Safeconduct answered 29/7, 2016 at 15:30 Comment(1)
Thank you for your answer. Using {$gt: 0, $lt: 0} is very clever. I suppose my second use case with $not, a deep property and $size doesn't use any index either right? By the way, I don't know which operators are using or not an index but i think it might be mentioned in the project readme to avoid this kind of questions. Waiting for your answer to my question in this comment to accept your initial answer.Hussy

© 2022 - 2024 — McMap. All rights reserved.