I'm having trouble dealing with what I thought would be a simple problem. Basically, I need a java.util.Map<String, String>
, where ids end up being the map keys, and someField
of my document ends up in the values.
I'm really really stuck on this, which greatly surprises me. I've tried writing a separate view:
@View(map="function(d) { if (d.someField) { emit(d.someField, null); } }", name = "someField")
and then use the following Java:
public Map<String, String> getSomeFields() throws JsonParseException, JsonMappingException, IOException {
ViewQuery q = new ViewQuery().designDocId("_design/" + entity.getSimpleName()).viewName("someField");
String result = StreamUtils.inputStreamAsString(db.queryForStream(q), false);
TypeReference<Map<String, String>> mapTypeRef = new TypeReference<Map<String,String>>() {};
// mapper is a Jackson ObjectMapper
return mapper.readValue(result, mapTypeRef);
}
This is already really ugly, but it also doesn't actually work, as it seems the JSON results that queryForStream
returns includes random other stuff, rather than just the result of the query. This causes the readValue
call to throw an IOException
.
I've also tried using reduce
to generate a single object containing all these values, but the result of that is that Couch complains the reduce doesn't reduce enough...
I would do something like this:
ViewQuery query = ...
Map<String, String> map = new HashMap<String, String>();
for (ViewResult.Row row : db.queryView(query)) {
map.put(row.getId(), row.getKey());
}
return map;