How can I coax Spring Data to show me mongo's query plan (a.k.a cursor.explain())

ぃ、小莉子 提交于 2021-02-18 15:34:33

问题


I am writing an API with Spring/Mongo/Jersey to do CRUD on a POJO that has a generic map of properties like this:

public class Thing {
    private String id;

    @Indexed
    private Map<String,String> properties;
...

This is working great to return items. My resource code looks like this:

BasicDBObject query = new BasicDBObject("properties.name", "vlad the impaler");
return Response.ok(myService.queryThings(query)).build();

And my abstract DAO looks like this:

public List<T> find(Query query) {
        return mongoOps.find(query, clazzOfItem);
}

What I can't tell is if the @Indexed annotation is working. I'd like to try explain, (http://docs.mongodb.org/manual/reference/method/cursor.explain/), but I don't see any examples that show me how to call the lower level driver API from spring data.

I'd like to be able to turn on debugging like so:

public List<T> find(Query query) {
        if (debugOn) {
            String queryPathDetails = mongoOps.executeCommand( /*NOW WHAT??*/ ).toString();
            logger.log(queryPathDetails);
        }
        return mongoOps.find(query, clazzOfItem);
}

Any help you can provided will be much appreciated!


回答1:


We don't provide support for that yet, but you could simply set a breakpoint here org.springframework.data.mongodb.core.MongoTemplate.QueryCursorPreparer.prepare(..)

In the debugger of your choice you can then simply execute a

cursor.explain()

e.g. via the eclipse display view.




回答2:


Here is what I ended up doing:

public Object explainQuery(Query query) {
        //Not sure this is safe, please comment if there is a better way!
        String collectionName =  clazzOfItem.getSimpleName().toLowerCase();
        DBCollection collection = mongoOps.getCollection(collectionName);
        DBCursor cursor = collection.find(query.getQueryObject());
        return cursor.explain();
}

so going back to the DAO code I have listed above, I can now do this:

public List<T> find(Query query) {
    if (debugOn) {
        Object queryPlan = explainQuery(query);
        logger.log(queryPlan);
    }
    return mongoOps.find(query, clazzOfItem);
}

Any help you can provided will be much appreciated!



来源:https://stackoverflow.com/questions/28818083/how-can-i-coax-spring-data-to-show-me-mongos-query-plan-a-k-a-cursor-explain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!