Couchdb view, which searches for an array field for values ​​passed as an array of keys

I have some documents in couchdb that have fields that are id arrays for different related documents:

{ associatedAssets: ["4c67f6241f4a0efb7dc2abc24a004dfe", "270fd4508a1222a1e2a27cbe7f002d9z"] } 

I would like to write a view that allows me to pass a key, which itself is an array of identifiers, and then return documents whose associated Assets fields contain one or more identifiers that passed through the key array, for example

 $.ajax({ url: "/db/_design/design_doc/_view/summaryByAssociatedAssets", type: "post", data: JSON.stringify({keys: ["4c67f6241f4a0efb7dc2abc24a004dfe", "6c67f6241f4a0efb7dc2abc24a004dfd"]}), dataType: "json", contentType: "application/json", }) .done(function(resp){ console.log(resp[0]); }); 

will return documents for which the associated asset array contains one or more keys "4c67f6241f4a0efb7dc2abc24a004dfe", "6c67f6241f4a0efb7dc2abc24a004dfd".

I cannot access the keys in my view, so I'm not sure if I can do this? Is there a better way to do this?

Thanks!

+6
source share
2 answers

Your view just needs to create an output line for the associatedAssets element, something like this:

 function(doc) { if( doc.associatedAssets ) { for( var i=0, l=doc.associatedAssets.length; i<l; i++) { emit( doc.associatedAssets[i], doc ); } } } 

Then you need to configure your call so that it finishes passing this keys array as a query string parameter, which will only return rows from the view that match the keys in this array.

In general - adopting the recent version of CouchDB, it would be best practice to replace doc with emit with { _id: doc._id } and then use include_docs=true in your request so that your view index is not populated (without need) with full documents.

+11
source

In the view code, you can access something in the document itself, but there is no way to access any parameters that you pass.

You can use temporary views created for the specific request you are making.

Instead, you can use ElasticSearch. ElasticSearch has a much richer DSL query because the whole point is ElasticSearch. CouchDB Reserve allows you to automatically index all documents from CouchDB.

Using ElasticSearch, you can simply search for any document associated with it containing any item from the list that you submit.

0
source

Source: https://habr.com/ru/post/918816/


All Articles