1
votes

I have documents that set up like this:

{ _id: 1, name: "A", timestamp: 1478115739, type: "report" }
{ _id: 2, name: "B", timestamp: 1478103721, type: "transmission" }
{ _id: 3, name: "C", timestamp: 1473114714, type: "report" }

I am trying to create a view that only returns the documents within a specific timestamp range. And I would love to be able to filter by type as well.

Here is my javascript call for the the data:

db.query('filters/timestamp_type', { startKey: 1378115739, endKey: 1478115740  })
.then(function(resp) {
    //do stuff
})

I only know where to put the starting and ending timestamps. I'm having a hard time figuring out where I would say I only want the report's returned.

In addition, this is my map function for my filter, which is obviously not even close to being complete. I'm not sure how I even access the start and end key.

function (doc) {
  if(type == "report" && startKey >= doc.timestamp && endKey <= doc.timestamp)
    emit(doc._id, doc.name);
}

My question remains:

  • Where do I retrieve the start and end key's in my map function?
  • How can I add an addition type filter for only getting a specific type of report.

I know I might need to use a reduce function but it's going over my head. Here is the default reduce function but I'm not sure how it would work with the map function.

function (keys, values, rereduce) {
  if (rereduce) {
    return sum(values);
  } else {
    return values.length;
  }
}

Thank you, any help or guidance would be appreciated.

1

1 Answers

0
votes

Use a map function to get reports by a specific type-

function(doc) {
   if(doc.type == "report") {
     emit(doc.timestamp, doc);
   }
}

when the view is queried, only documents with the type 'report' will be returned. If you need to support multiple types, you will have to create a new view for each type.

To query this view and specify the start & end timestamps, just add them to your query-

curl -XGET http://localhost:5984/<your-database>/_design/docs/_view/<your-view-name>?startkey="1478115739"&endkey="1478103721"

Reference