Indexing Pouch db multi dimensional documents

空扰寡人 提交于 2019-12-19 10:16:38

问题


Looking for a way to index pouchDB

Can't find a way to index when i have multiple dimensions

Here is my document client example

Note that client may have a few invoice

{
    clientId : 2
    clientName : 'toto'
    phoneNumber : '2342342'
    invoices : [
        {
            invoiceNumber : '12312313' , 
            Amount : 234242, 
            barCode : '1234324', 
        },  
        {
            invoiceNumber : '12312313' , 
            Amount : 234242, 
            barCode : '1234324', 
        }
    ]
}
{
    clientId : 3
    clientName : 'tata'
    phoneNumber : '2342342'
    invoices : [
        {
            invoiceNumber : '3542435' , 
            Amount : 234242, 
            barCode : '1234324', 
        },  
        {
            invoiceNumber : '235423' , 
            Amount : 234242, 
            barCode : '23454235', 
        }
    ]
}

I want to be able to find clients by invoice number and barCode number

So indexing those are important

Thanks for your help

I have looked at https://pouchdb.com/api.html#create_index and https://pouchdb.com/2014/05/01/secondary-indexes-have-landed-in-pouchdb.html

So far not much luck


回答1:


As mentioned on CouchDB documentation:

... the emit() function can be called multiple times in the map function to create multiple entries in the view results from a single document...


Now we are going to use emit() multiple times in the map function. Also we are going to emit arrays to have both invoiceNumber and barCode as the index, like this:

var myIndex = {
    _id: '_design/my_index',
    views: {
        'my_index': {
            map: function (doc) {
                for(var i=0, length=doc.invoices.length; i<length; i++){
                    emit(
                        // emit array of invoiceNumber and barCode as key:
                        [doc.invoices[i].invoiceNumber, doc.invoices[i].barCode],
                        // emit array of clientId and clientName as value
                        // Actually, value can be whatever you want:
                        [doc.clientId, doc.clientName]
                    );
                }
            }.toString()
        }
    }
};

Now lets PUT our above design document and query it with PouchDB:

pouch.put(myIndex).then(() => {
  // query the index
  return pouch.query('my_index', {key: ['12312313','1234324']});
}).then(result => {
  // found docs with invoiceNumber === '12312313' and barCode === '1234324'
  console.log('Result: ', result)
});

Also take a look at this similar answer.



来源:https://stackoverflow.com/questions/49575033/indexing-pouch-db-multi-dimensional-documents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!