如何在 Java 中使用 $query、$hint 或 $explain [英] How to use $query, $hint or $explain from Java

查看:33
本文介绍了如何在 Java 中使用 $query、$hint 或 $explain的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 MongoDB 3.4我的方法是:-

I am using MongoDB 3.4 My methods are:-

MongoDatabase db = mongo.getDatabase(mongoDBLogs);
MongoIterable<String> allCollections = db.listCollectionNames();
str==FROM COLLECTION
MongoCollection<Document> table = db.getCollection(str);
MongoCursor<Document> cursor = table.find(queryForLogs).iterator();

问题是在旧版本我可以使用

The problem is in OLD version I can use the

DB db = mongo.getDB(mongoDBLogs);
Set<String> colls = db.getCollectionNames();
for (String s : colls) {
DBCollection table = db.getCollection(s);
cursor = table.find().explain(); <<<<---- I have this explain method
AND ALSO I have
cursor = table.find().hint(indexKeys);<<<<---- I have this hint method
}

现在在 3.4 中我无法使用这些选项

NOW in 3.4 I am not able to access these options by using

MongoCursor<Document> cursor = table.find(queryForLogs).explain() <-- this is type  FindIterable<Document>

MongoCursor<Document> cursor = table.find(queryForLogs).hint(Some value); <---This is type  FindIterable<Document>

我参考链接:-https://docs.mongodb.com/manual/reference/operator/meta/提示/https://docs.mongodb.com/manual/reference/method/cursor.explain/

所以我做了另一种方法:-

So I make another method:-

    public  BasicDBObject generateQueryForSessionIDLogs(String service_name, String node_name, Date gtDate, Date lteDate, String session_id,List<String> logLevel, String errorMsg){
        BasicDBObject andQuery = new BasicDBObject();
        List<BasicDBObject> obj = new ArrayList<BasicDBObject>();

        //Use session to search. If session is unknown, start and end date must be provided
        if(!session_id.isEmpty() && session_id != null){
            String[] sessionarray = session_id.split(",");

            if(sessionarray.length == 1){
                Long val = Long.valueOf(sessionarray[0].trim()).longValue();
                obj.add(new BasicDBObject("s", val));

            } else{ 
                ArrayList<Long> vals =  new ArrayList<Long>();
                for(String strn : sessionarray){
                    vals.add(Long.valueOf(strn.trim()).longValue());
                }

                obj.add(new BasicDBObject("s", new BasicDBObject("$in", vals )));
            }
        }else{      
            if((gtDate != null) && (lteDate != null)){
                obj.add(new BasicDBObject("d",  new BasicDBObject("$gt", gtDate).append("$lte", lteDate)));
            }
        }

        if(!node_name.isEmpty()){
            obj.add(new BasicDBObject("i", node_name));
        }
        if(!service_name.isEmpty()){
            obj.add(new BasicDBObject("n", service_name ));
        }
        if(!errorMsg.isEmpty()) {
            obj.add(new BasicDBObject("m", Pattern.compile(errorMsg)));
        }

        if(!logLevel.isEmpty()){
//          obj.add(new BasicDBObject("r", new BasicDBObject("$in", logLevel )));
            obj.add(new BasicDBObject("r", logLevel.get(0) ));
        }

        if (obj.size() > 1){ //append 'AND' if there is >1 conditions
            andQuery.put("$and", obj);
        }

        BasicDBObject andQuery2 = new BasicDBObject();
        andQuery2.put("$query", andQuery);
        List<BasicDBObject> obj2 = new ArrayList<BasicDBObject>();
        obj2.add(new BasicDBObject("i",1));
        andQuery2.put("$hint", obj2);
        andQuery2.put("$explain", 1);
        logger.debug("Query String for Logs: " + andQuery2);
        return andQuery;
    }

我的最终查询如下:-

日志的查询字符串:{ "$query" : { "$and" : [ { "d" : { "$gt" : { "$date" : "2017-06-19T04:00:00.000Z"} , "$lte" : { "$date" : "2017-06-20T04:00:00.000Z"}}} , { "i" : "WM96BEPSIT02"}]} ,"$hint" : [ { "i" : 1}] , "$explain" : 1}

有错误:-线程pool-2-thread-16"中的异常线程pool-2-thread-15"中的异常com.mongodb.MongoQueryException:查询失败,错误代码2和错误消息未知顶级运算符": $query' 在服务器上

还请建议先调用索引值的任何替代方法.就我而言,所有搜索值都未编入索引.

Please also suggest any alternative way to call the indexed values first. As in my case all search values are not indexed.

推荐答案

要将 $hint$explain 之类的内容发送到您实际使用 .modifiers() 方法来自 FindIterable.例如:

To send things like $hint or $explain to the Java driver you actually use the .modifiers() method from FindIterable. For instance:

MongoCursor<Document> iterator = collection.find()
    .modifiers(new Document("$explain",1)).iterator();

while (iterator.hasNext()) {
  System.out.println(iterator.next().toJson());
}

这将打印解释统计输出.

This will print the explain stats output.

任何 BsonDocument 类型作为参数提供是有效的.有效列表位于核心文档中的查询修饰符上.

一般来说,$query 并不是您从修饰符列表中实际使用的东西,因为您实际上是使用 .find() 的任何参数来构造它的.但是所有其他修饰符都可以在这里使用.

Generally speaking, $query is not something that you actually use from the modifiers list, since you are actually constructing that with any argument to .find(). But all the other modifiers are valid for use here.

这篇关于如何在 Java 中使用 $query、$hint 或 $explain的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆