Search code examples
javacouchbase-lite

Couchbase Lite Java: Creating View & Query with Exact Keys


I am trying to query base on my own custom view, but it did not turn out what I expected.

I would like to query with keys example like ["2017", "5", "26"], endDateTime is the column in my Json Data which storing millisecond.

I have emitted with List to store date.

When I ran my query by today date (database do have data for the date that I am searching), I have debugged with breakpoint to check the List that stored the date in view and query both is identical.

I can't find the reason why queryEnumerator return no row.

Please help my issue, I have been tried many ways but still no luck.

Appreciate for the help.

public View getViewTransactionByEndDate() {
    View view = this.getDatabase().getView("Transaction");

    if (view.getMap() == null) {
        view.setMap(new Mapper() {
            @Override
            public void map(Map<String, Object> document, Emitter emitter) {
                if (document.get("type") != null) {
                    if (document.get("type").equals("Transaction")) {
                        Calendar dataCalendar = Calendar.getInstance(); 

                        /* due to too long the code, */ 
                        /* I have break it to 2 lines */
                        Long endDateTime = 
                        Long.parseLong(document.get("endDatetime"));

                        dataCalendar.setTimeInMillis(endDateTime);

                        List<Object> key = new ArrayList<>();
                        key.add(dataCalendar.get(Calendar.YEAR));
                        key.add(dataCalendar.get(Calendar.MONTH) + 1);
                        key.add(dataCalendar.get(Calendar.DAY_OF_MONTH));

                        HashMap<String, Object> value = new HashMap<>();
                        value.put("_id", document.get("_id"));

                        emitter.emit(key, value);
                    }
                }
            }
       }, "1");
    }

    return view;
}


/* The query part */
Query query = getViewTransactionByEndDate().createQuery();

Calendar todayCalendar = Calendar.getInstance();
todayCalendar.setTime(new Date());

List<Object> key = new ArrayList<>();
key.add(todayCalendar.get(Calendar.YEAR));
key.add(todayCalendar.get(Calendar.MONTH) + 1);
key.add(todayCalendar.get(Calendar.DAY_OF_MONTH));

query.setKeys(key);

QueryEnumerator queryEnumerator = query.run();

Solution

  • I managed to find the answer myself:

    For those who looking the solution for the similar question, please refer below:

    Query multiple keys in couchbase lite view