【问题标题】:How to use $query, $hint or $explain from Java如何在 Java 中使用 $query、$hint 或 $explain
【发布时间】:2017-11-23 20:12:44
【问题描述】:

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

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();

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

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 中我无法通过使用访问这些选项

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/hint/ https://docs.mongodb.com/manual/reference/method/cursor.explain/

所以我另做一个方法:-

    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 String for Logs: { "$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}

有错误:- Exception in thread "pool-2-thread-16" Exception in thread "pool-2-thread-15" com.mongodb.MongoQueryException: Query failed with error code 2 and error message 'unknown top level operator: $query' on server

还请提出任何替代方法来首先调用索引值。在我的情况下,所有搜索值都没有被索引。

【问题讨论】:

    标签: java mongodb mongodb-query


    【解决方案1】:

    要将$hint$explain 之类的内容发送到Java 驱动程序,您实际上是使用FindIterable 中的.modifiers() 方法。例如:

    MongoCursor<Document> iterator = collection.find()
        .modifiers(new Document("$explain",1)).iterator();
    
    while (iterator.hasNext()) {
      System.out.println(iterator.next().toJson());
    }
    

    这将打印解释统计输出。

    任何BsonDocument 类型都可以作为参数提供。 有效列表位于核心文档中的Query Modifiers

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 2014-01-09
      • 2015-10-16
      • 2013-12-12
      • 2016-03-07
      • 2012-06-05
      • 2012-05-04
      相关资源
      最近更新 更多