1

Hello I am building a reservation app using database as couchDb. I have several reservation documents and each of them has roomId, start date and end date.

Now when user creates a meeting request with roomId, start date and end date, I need to search for overlaps time ranges between the start time and endtime in the existing reservations and create a reservations only when there is no conflict. Along with this I also need to check for roomid.

The requirement is similar to Determine Whether Two Date Ranges Overlap.

I had created a view on my couch db emitting three keys:

function (doc) {  
    if (doc.type == "reservation") {  
         emit([doc.roomid, doc.startTime, doc.endTime], doc);  
    }
} 

I did try creating something like

?startkey=["1970-01-01T00:00:00Z", ""]&endkey=["\ufff0", "1971-01-01T00:00:00Z"]

However I am not really getting how to compound query the view to find range of date along with the roomid.

Any help would be appreciated.

Community
  • 1
  • 1

1 Answers1

2

You could use Cloudant Query and specify the (StartA <= EndB) and (EndA >= StartB) search condition that's outlined in the referenced answer.

Create an index

Send a POST request to the _index endpoint, passing the following JSON data structure as payload.

  POST https://$USERNAME:$PASSWORD@$HOST/$DATABASE/_index HTTP/1.1

 {
  "index": {
   "fields": [
     { "name":"startTime",
       "type":"string"
     }, 
     { 
       "name":"endTime",
       "type":"string"
     }, 
     { 
       "name":"roomid",
       "type":"string"
     } 
   ]
  },
  "type": "text"
 }

Query the index

Send a POST request to the _find endpoint, passing the following JSON data structure as payload.

  POST https://$USERNAME:$PASSWORD@$HOST/$DATABASE/_find HTTP/1.1

  {
   "selector": {
    "startTime": {
      "$lte": "2017-03-06T15:00:00Z"
    },
    "endTime": {
      "$gte": "2017-03-06T14:00:00Z"
    },
    "roomid": {
      "$eq": "room 123"
    }
   }
  }

Replace the timestamp and room identifier values as needed. If the query returns at least one document you've encountered a booking conflict.

Community
  • 1
  • 1
ptitzler
  • 923
  • 4
  • 8
  • Thank you pointing me to this. I will try this one out and reach out if I need anything else. – user1401443 Mar 07 '17 at 17:57
  • This should also be available in couchdb 2.0+. I can't think of a way to arrive at the same operating using a single map-reduce, so thanks Mango! – sarwar Mar 07 '17 at 20:00