Android query couchdb field with arraylist

greetings! I would like to find out how to query a couch db document that looks like this

 {
    type : "customer",
    name: "customerX",
    states: [ "IL" , "IO" , "NY" , "CA" ]
}

so that i can query the view and display the results if states contains the arraylist item CA

my code looks like this:

com.couchbase.lite.View viewItemsByDate = databasez.getView(String.format("%s/%s", designDocNamez, byDateViewNamez));

        viewItemsByDate.setMap(new Mapper() {
            @Override
            public void map(Map<String, Object> document, Emitter emitter) {
                Object createdAt = document.get("states");
                String nulla = null;        
                    if(createdAt.equals("CA") && !createdAt.equals(nulla) )
                    {
                        emitter.emit(createdAt.toString(), null);
                    }
                }
            
        }, "1.0");

thanks

So, the way you design views is to identify what you’re going to search for – states – and then emit those as the keys in the index. In this case each doc contains multiple states, so you’d loop over the “states” array and emit each string as a key.

Then in the query you are looking for the rows with a specific key – “CA” – so you set that as both the startKey and endKey. Alternatively you could set the query’s keys property to an array containing only “CA”.

You almost never stick a specific query value like “CA” into the map function, because then you have a view that’s only good for that one query, which is a waste.

Hope this helps clear up how views work…

hi @jens thanks for taking the time to reply, i tried to do what you said, although i am still getting an error at the for loop, here is my code

viewItemsByDate.setMap(new Mapper() {
            @Override
            public void map(Map<String, Object> document, Emitter emitter) {
                Object createdAt = document.get("states");     
                String nulla = null;
                    ArrayList al1 = (ArrayList) createdAt;
                    for (int i = 0; i < al1.size(); i++) {                         
                        emitter.emit(al1.get(i).toString(), null);
                    }
            }
        }, "1.0"); 

and in my query i put

            query.setStartKey("CA");
            query.setEndKey("CA");

What’s the error message, then?

The code looks ok to me, except that you’re not checking for createdAt being null. Maybe that’s what’s going wrong.

yep finally solved it, thanks @jens the createdAt was the issue.

Hi @jens implementation above is clear and it works…but I have another question for this topic…Is it possible to return more that one key in map function? Actually I want to achieve "LIKE " query from SQL… for example if user type “cu” it should search type and name from example above…