Search code examples
couchdbcloudantnosql

querying part of array key in couchDB view


I currently have a document called beacon_logs, and it logs every time I walk into range of a beacon. The data looks similar to this:

{
  "_id": "00198cd8f0fc510dbad06bf24e93f55b",
  "_rev": "1-e90f025935847b0412923e4ba472cf2a",
  "device": "gwen",
  "beaconUUID": "123",
  "distance": "0.0",
  "timestamp": 1487443924
},
{
  "_id": "00198cd8f0fc510dbad06bf24e93f55c",
  "_rev": "1-e90f025935847b0412923e4ba472cf2a",
  "device": "gwen",
  "beaconUUID": "123",
  "distance": "0.1",
  "timestamp": 1487443925
},
{
  "_id": "01ab15fd3a1c7c37ba147be8c56fe389",
  "_rev": "1-587035fb7a71962c21f91b86aca56a77",
  "device": "gwen",
  "beaconUUID": "456",
  "distance": "0.87",
  "timestamp": 1487031602
},
{
  "_id": "01ab15fd3a1c7c37ba147be8c56fe388",
  "_rev": "1-587035fb7a71962c21f91b86aca56a77",
  "device": "gwen",
  "beaconUUID": "456",
  "distance": "0.87",
  "timestamp": 1487031603
}

And this view:

function (doc) {
  emit([doc.beaconUUID,doc.timestamp], doc);
}

What I want is to get only get all of a certain beaconuuid (i.e.123) and have it also sort by timestamp. This is the query I wrote:

*DB_NAME*/_design/*DDOC_NAME*/_view/*VIEW_NAME*?descending=false&startkey=["123",999999999]&endkey=["123",0]

however this returns me pretty random results that includes other beaconUUIDs as well.

My question to this very long winded explanation is: given that the key is an array, is there any way to query against 1 of the array's value, e.g.

*DB_NAME*/_design/*DDOC_NAME*/_view/*VIEW_NAME*?descending=false&key[0]="123"

and if not, would anyone be able to recommend a work around?


Solution

  • using this view

    function (doc) {
      if (doc.beaconUUID) {
        emit([doc.beaconUUID,doc.timestamp], doc);
      }
    }
    

    i was able to get the correct responses with these queries:

    chronological timestamp order:
    *DB_NAME*/_design/*DDOC_NAME*/_view/*VIEW_NAME*?startkey=["123",0]&endkey=["123",{}]

    reverse chronological timestamp order:
    *DB_NAME*/_design/*DDOC_NAME*/_view/*VIEW_NAME*?startkey=["123",{}]&endkey=["123",0]&descending=true