Sorting and querying documents in couchbase-lite

What I want to do is finding all records that match some id and sorted by a name. The data looks something like:

{
    type:"receiving",
    saleName:"Harshitha",
    penId:"7aac88118420858d62f5ea55e22"
}
{
    type:"receiving",
    saleName:"Tom",
    penId:"81fb1a79526f4e2bdc77aa7d73d"
}
{
    type:"receiving",
    saleName:"James",
    penId:"81fb1a79526f4e2bdc77aa7d73d"
}

I want to get documents with some specific penID sorted by saleName.
Ex:- I want to get documents with this penId ‘81fb1a79526f4e2bdc77aa7d73d’ and sort them by saleName. Like this order:-

{
    type:"receiving",
    saleName:"James",
    penId:"81fb1a79526f4e2bdc77aa7d73d"
}
{
    type:"receiving",
    saleName:"Tom",
    penId:"81fb1a79526f4e2bdc77aa7d73d"
}

My view like this,

      View view = database.getView("receiving_view");
      if (view.getMap() == null) {
          view.setMap(new Mapper() {
              @Override
              public void map(Map<String, Object> document, Emitter emitter) {
                  if (document.get("type").equals("receiving") ) {

                      List<Object> keys = new ArrayList<Object>();
                      keys.add(document.get("penId"));
                      keys.add(document.get("saleName"));

                      emitter.emit(keys, document);
                  }
              }
          }, "1.1");
      }
      return view;

Then I tried to get data like this,

    View view = getView("receiving_view");
    Query query = view.createQuery();

    List<Object> keys = new ArrayList<Object>();
    keys.add("81fb1a79526f4e2bdc77aa7d73d");

    List<Object> allKeys = new ArrayList<Object>();
    allKeys.add(keys);
    query.setKeys(allKeys);
    query.run();

It’s not working because I passed one key, but their are two keys in the view… But I can’t pass the ‘saleName’ as a key because I want only to sort by ‘saleName’. What is the best way to do this?

You don’t want to use setKeys here; you want a range of keys, not a specific set of keys.

Set startKey to [penID] and endKey to [penID, {}]. The empty map sorts after any other value, so this key range includes all keys that start with penID, which is what you want.

The view and query docs online describe how to do this kind of thing.

1 Like

Thanks jens. It works… Now this is what my query looks like :-

    View view = getView("receiving_view");
    Query query = view.createQuery();

    query.setStartKey(Arrays.asList("81fb1a79526f4e2bdc77aa7d73d"));
    query.setEndKey(Arrays.asList("81fb1a79526f4e2bdc77aa7d73d", new HashMap<String, Object>()));
    query.run();