代码之家  ›  专栏  ›  技术社区  ›  Half_Duplex

使用索引提示会导致MongoTemplate查询耗时更长

  •  0
  • Half_Duplex  · 技术社区  · 4 年前

    春季Mongo查询( org.springframework.data.mongodb.core.query )是基于用户输入有条件地构建的,例如,用户可以基于时间戳、状态或产品名称的任何组合进行查询。产品名称字段不需要精确(请参阅下面查询中的regex)。

    问题 在查询中包括productName,并提示 productName 索引中,查询的执行时间大约要长50%。

    示例数据

    {
        "_id" : ObjectId("55d076d80bad441ed114419d"),
        "productName" : "Windex",
        "status" : "instock",
        "timeStamp" : 00:00:00 ...
    }
    

    查询创建和执行

    final List<Criteria> criteria = new ArrayList<>();
    Query query = new Query().with(pageable);
    
    if (status != null) {
        criteria.add(Criteria.where("status").is(status));
    }
    
    if (productName != null) {
        criteria.add(Criteria.where("productName").regex("(?i).*" + productName + ".*"));
        // Using the index hint below results in longer execution times
        //query.withHint("productName_index");
    }
    
    List<Product> list = mongoTemplate.find(query, Product.class);
    

    指数

    {
        v: 2,
        key: {
            _fts: 'text',
            _ftsx: 1
        },
        name: 'productName_index',
        weights: {
            'productName': 1
        },
        default_language: 'english',
        language_override: 'language',
        textIndexVersion: 3
    }
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Alex Blex    4 年前

    productName_index ,尽管其名称具有误导性,但它是 _fts 字段和 _ftsx 领域上的权重 productName 在那里什么都不做。

    提示强制mongo使用此索引,这对regxp查询没有帮助 productName 领域因为mongo不能使用任何其他索引,所以它获取所有文档并应用正则表达式过滤器,这比COLLSCAN慢一点。

    通常,查询计划器非常好,只有当您确切知道mongo选择的索引不理想的原因时,才应该使用提示。