javanosqlcouchdbektorp

How to get doc from couchdb without some fields? using Ektorp if possible


At first I misunderstood my problem and posted this question : Can someone explain me Cascading and FetchType lazy in Ektorp?

What I need to do: I need to save an Entity in couchdb and then have way to read it and potentially ignore some fields. So I came up with this solution: I create a show function that delete fields from an object and then send it back.

function(doc, req) {
    var result = doc;
    var ignore = JSON.parse(decodeURIComponent(req.query.ignore)); //this is an array of field names
    for (var i = 0, j = ignore.length; i < j; i++) {
        if (result[ignore[i]]) {
            delete result[ignore[i]];
        }
    }
    return {
        body : JSON.stringify(result),
        headers : {
            "Content-Type" : "application/json"
        }
    };
}

I have the same function but reversed in which the object keeps the fields I tell the function to keep.

Is there a better way to do this?

I also want to use Ektorp to call this but it allows me to only call Views. Right now I am forced to manage the http request myself. Is there a way to avoid this?

Right now this is the code I must use, but I would like to use Ektorp to do this.

    HttpClient httpClient = new StdHttpClient.Builder().url("http://localhost:5984").build();
    CouchDbInstance dbInstance = new StdCouchDbInstance(httpClient);
    CouchDbConnector db = new StdCouchDbConnector("mydatabase", dbInstance);
    db.createDatabaseIfNotExists();

    String[] forget = new String[] { "field_to_ignore" };
    String uri = "/mydatabase/_design/mydesigndoc/_show/ignorefields/mydocid?ignore=" + URLEncoder.encode(Json.stringify(Json.toJson(forget)), "UTF-8");
    System.out.println(uri);
    HttpResponse r = db.getConnection().get(uri);
    String stuff = new Scanner(r.getContent()).useDelimiter("\\A").next();
    System.out.println(stuff);

Solution

  • A show function isn't a terrible idea, from a CouchDB point of view. Ektorp may not support them, presumably because they're not hugely used, but Ektorp's open-source and on Github; you could easily just add this functionality, especially since you already have the basics of a working implementation of it.

    Alternatively you could just build a view that does this for a given set of fields. You can't really parameterize this though, so you'd need well-defined sets of fields you know beforehand.

    Finally I'd suggest either pulling the whole document and not worrying about it (unless you're in an extremely hugely bandwidth-limited situation it's probably not going to matter), or splitting the document into the constituent parts you're querying for and requesting them independently, if that's definitely the unusual case.