GuruKulki
GuruKulki

Reputation: 26428

how to query on particular keys in couchbase through java client?

I am new to CouchBase. I have few simple documents as :

1. {
  "docType": "DeviceData",
  "id": "57 0F 75 00 C8 0B@2013-06-26 23:59:38.979",
  "time": 1372271378979,
  "group": "London"
}

2. {
  "docType": "DeviceData",
  "id": "57 0F 75 00 C8 0B@2013-06-27 10:02:46.197",
  "time": 1372307566197,
  "group": "Bristol"
}

3. {
  "docType": "DeviceData",
  "id": "57 0F 75 00 C8 0B@2013-06-27 10:03:36.4",
  "time": 1372307616400,
  "group": "Bristol"
}

I have requirement to query on group and time. for example I want to fetch all the documents with group = Bristol and time from 1372307616100 to 1372307616500. So i deal I should get the 2 of the 3 docs.

So i have create the view as:

function (doc, meta) {
  if(doc.docType == "DeviceData")
  emit([doc.group, doc.time], doc);
}

And in the java code setting the query as below:

String str = "[\"Bristol\", 1372307566100]";
        String end = "[\"Bristol\", 1372307616500]";
        query.setRange(str, end);
        List<DeviceData> deviceData = cbStore.getView("getDevices", DeviceData.class, query);

But getting zero documents.

Please let me know is there anything wrong I am doing? need help thanks.

*EDIT: I tried using complexkeys as well like below but no luck.

ComplexKey startKey = ComplexKey.of("Bristol", "1372307566100");
ComplexKey endKey = ComplexKey.of("Bristol", "1372307616500");

Upvotes: 1

Views: 4503

Answers (1)

pierluigi
pierluigi

Reputation: 51

The problem is that in your objects time is a long, not a String:

query.setStale(Stale.FALSE);
long firstParameter=1372307566197l;
long secondParameter=1372307616400l;
//["Bristol",1372307566197]
ComplexKey startKey = ComplexKey.of("Bristol", firstParameter);
//["Bristol",1372307616400]
ComplexKey endKey = ComplexKey.of("Bristol",  secondParameter);
query.setRange(startKey, endKey);
ViewResponse result = client.query(view, query);
Iterator<ViewRow> iter = result.iterator();
while(iter.hasNext()) {
    ViewRow row = iter.next();      
    System.out.println( row.getId()); // ID of the document
    System.out.println(row.getKey()); // Key of the view row
    System.out.println(row.getValue()); // Value of the view row
    System.out.println(row.getDocument()); // Full document if included
    }

Upvotes: 5

Related Questions