androidviewcouchdbektorp

Its possible to put in @View dynamic parameters?


I'm working on an application for Android that displays events based on the user selected date. I'm using Couchdb and Ektorp. I don't know how to define a view on method findByMes that includes a variable date that I should read from the calendar instead of the "2013-10-01"... This is the code of de class EventDAO I'm working in.

I would be very grateful if someone could help me!!

public class EventDAO extends CouchDbRepositorySupport<EventVO> {

        public EventDAO(CouchDbConnector db) {
                super(EventVO.class, db);
                initStandardDesignDocument();
        }

        @GenerateView @Override
        public List<EventVO> getAll() {
                ViewQuery q = createQuery("all")
                                .includeDocs(true);
                return db.queryView(q, EventVO.class);
        }

        public List<EventVO> findByDate(String Date) {
            List<EventVO> event = queryView("by_date", Date);
            return  event;
        }

       @View( name = "by_mes", map ="function(doc) {if (doc.type == 'Event' && doc.date >= '2013-10-01' && doc.date <= '2013-10-31'  ) { emit(doc._id,doc)}}")
        public List<EventVO> findBymes() {
           ViewQuery q = createQuery("by_mes")
                   .includeDocs(true);
           return db.queryView(q, EventVO.class);

        }
}

Solution

  • It's not possible to have dynamic things within views since views build once and incrementally updates only for changed documents. You should move date bits from map function into the key:

    function(doc) {
        if (doc.type == 'Event'){ 
          var key = doc.date.split('-').map(function(i){
              return parseInt(i, 10);
          }); // .map part is optional, I prefer to have date-time arrays with int values
          key.push(doc._id);
          emit(key, doc);
        }
    }
    

    and use them (date bits) in query parameters:

    http://localhost:5984/db/_design/ddoc/_view/by_mes?startkey=[2013,10,1]&endkey=[2013,10,31, {}]
    

    This would give you a different output (I omit value's doc object):

    {
        "offset": 0,
        "rows": [
            {
                "id": "foo",
                "key": [2010, 10, 1, "foo"],
                "value": {}
            },
            {
                "id": "bar",
                "key": [2010, 10, 11, "bar"],
                "value": {}
            },
            {
                "id": "baz",
                "key": [2010, 10, 31, "baz"],
                "value": {}
            }
        ],
        "total_rows": 3
    }
    

    But with ability to change requested date range on-fly.