Skip to content

Instantly share code, notes, and snippets.

@adyshimony
Last active February 15, 2018 05:13
Show Gist options
  • Save adyshimony/d158f4aa02edb24bca0c6df87a8fe9bf to your computer and use it in GitHub Desktop.
Save adyshimony/d158f4aa02edb24bca0c6df87a8fe9bf to your computer and use it in GitHub Desktop.
Couchdb views
DB have one document kind - a transaction.
{
"_id": "0x0000000c72452d9599cf6c51bfbe009acdda360a5aec907a1a9dc62cf5abaa99",
"_rev": "1-86090328861b5ef615e4795d1284a5d5",
"blockNumber": 3892484,
..
..
"from": "0x003b177cB2365bA31434BE52f308FF3eA5b999eE",
"to": "0x7eD1E469fCb3EE19C0366D829e291451bE638E59",
"value": "201990651324420384",
"contractAddress": null
}
Queries needed:
1. all docs that "from" or "to" fields are equal to x.
2. all docs that "from" == x and "contractAddress" == y.
DB have 3 views, design doc for each view
to view:
map: function(doc) {
if (doc.to) {
emit(doc.to, {_id: doc._id});
}
}
from view:
map: function(doc) {
if (doc.from) {
emit(doc.from, {_id: doc._id});
}
}
contract view: (
map: function(doc) {
if (doc.contractAddress) {
emit([doc.from, doc.to, doc.contractAddress], {_id: doc._id}); // doc.to is always null.
}
}
@jo
Copy link

jo commented Feb 14, 2018

It is possible to combine all views into a single one:

function (doc) {
  if (doc.from) {
   emit([doc.from, null], null)
  }
  if (doc.to) {
   emit([doc.to, doc.contractAddress], null)
 }
}

Query with startkey=[x] and endkey=[x, {}] to get all rows with either to or from matching x (query 1).
Query with key=[x, y] to get contracts (query 2).

@adyshimony
Copy link
Author

Thanks. I will check it.
I can do the queries with this one view:

emit([doc.from, doc.to, doc.contractAddress])
But I thought 3 simple views are better than one heavy view?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment