sonya
sonya

Reputation: 239

Couchbase Function to query view: send parameter from Java

I have some Couchbase data in the following format

{
   "id": "12343",
   "transaction": {
        "2018-01-11": 10,
        "2017-12-01" : 20
    },
  "_type": "TransactionData"
}

I would like to get the ids whose transaction list contains key older than a given date ( for example, this object would not be retrieved for a value of "2017-11-01", but it does for "2017-12-12".

I made a view, but I would like to parameterise the date String:

function (doc, meta) {
  if (doc._type == 'TransactionData') {   

      for (var key in doc.transaction) {
         //I want to send the String value from java
         if (key < "2018-02-21") {
             emit(doc.id, null);
             break;
         }
      }
   }  
 }

I tried writing some N1QL query, but my server doesn't allow that, I can't change this configuration. I don't think I can use the startKey, because I return a map of (id, null) pairs. How can I filter the ids that have transactions older than a configurable date?

Thanks.

Upvotes: 0

Views: 306

Answers (2)

Chinh Nguyen
Chinh Nguyen

Reputation: 653

You can do like this:

function (doc, meta) {
  if (doc._type == 'TransactionData') {   
      for (var key in doc.transaction) {
         emit(doc.id, null);
      }
   }  
 }

user _count for Reduce function, then you can query using

query.range("2018-02-21", {}).reduce(true)

then you can take the value to see how many rows there are

Upvotes: 1

Hod
Hod

Reputation: 2276

Views are static indexes. Documents are processed once after each change, and any emitted results put into the index. You can't parameterize your function because it isn't rerun for every query. So you can't solve the problem the way you're approaching it. (You can do that with N1QL.)

Typically you solve this by adding a key range filter to your query. Look at the documentation for querying views. There are examples on how to select by date. You'll have to decide how you want to structure the index (view) you create.

Upvotes: 0

Related Questions