PouchDb 通过 Id 匹配正则表达式获取所有文档

PouchDb fetch all documents by Id matching regex

我想获取 ID 与正则表达式匹配的所有文档。

例如,我有以下文档 ID:

p0
p0/e0
p1
p1/e0

我怎样才能只得到 p0 和 p1 ?正则表达式为 /^p[0-9]+$/

目前我可以执行两个请求,但我只想使用一个:

This.db.allDocs({
    include_docs: false
}).then(function(result){

    // Find all ids matching /^p[0-9]+$/
    var iDoc = result.rows.length;
    while(iDoc--){
        if(result.rows[iDoc].id.match(/^p[0-9]+$/)){
            projectsIds.push(result.rows[iDoc].id);
        }
    }

    // Get all documents with ids matching /^p[0-9]+$/
    This.db.allDocs({
        include_docs: true,
        keys: projectsIds
    }).then(function(result) {
        var iProject = result.rows.length;
        var docs = [];
        while (iProject--) {
            docs[iProject] = result.rows[iProject].doc;
        }
        projects.resolve(docs);

    });

});

这可以通过前缀获取文档,因为 例子

localDB.allDocs({
            include_docs: true,
            startkey: "p0",
            endkey: "p0\uffff"
        },...);

以上代码为您提供了_id 以 p0 开头的所有文档。

参考link https://github.com/nolanlawson/pouchdb-quick-search#autosuggestions-and-prefix-search

您需要使用 allDocs() 获取所有文档,然后使用 JavaScript 在内存中过滤。

这需要将整个数据库读入内存,但 PouchDB 无法在正则表达式上建立索引,所以这是您必须做的!否则,您可以设计您的 ID,以便更容易按照其他评论者的描述进行前缀搜索。

几年后,看起来 pouchdb-find 插件可能有所帮助(我认为由上面的 @nlawson 编写)。这是 Pouch 文档谈论用它查询...https://pouchdb.com/api.html#query_index

你会怎么做:

async test()
  let result = await This.db.find({
    selector: {_id: {$regex: '^p[0-9]+$'}}
  });
  let docs = result.rows.map( row => row.doc )
  console.dir(docs)
}

(我将其设为异步只是为了让您不必费心处理回调)

您可以在 pouchdb-find 插件的 site.

上自行尝试

虽然性能可能很糟糕,但我还没有尝试过。 @nlawson 似乎认为索引上的正则表达式无法快速完成,而且他肯定比大多数人都清楚。

编辑:我刚刚检查了上面提到的 Pouch 文档,在查找过程中肯定使用了索引,所以性能可能还可以。