C# MongoDB 驱动程序在文本搜索上非常慢

本文关键字:非常 搜索 文本 MongoDB 驱动程序 | 更新日期: 2023-09-27 18:33:39

我对包含一百万个文档的集合进行了通配符文本搜索。

我可以直接从MongoDB控制台使用我的全文索引:

 db.oneMillionDocumentsIndexed.find({$text: { $search: "raven" } } )

这会在一分钟后返回文档。

但是,当我在单元测试中尝试同样的事情时,测试运行了半个多小时而不返回任何文档:

[Test]
public void SearchTextFullText()
{
    var credential = MongoCredential.CreateCredential("test", "readonlyUser", "password");
    var settings = new MongoClientSettings
                   {
                       Credentials = new[] { credential },
                       Server = new MongoServerAddress("localhost")
                   };
    var mongoClient = new MongoClient(settings);
    var database = mongoClient.GetDatabase("test");
    var collection = database.GetCollection<BsonDocument>("oneMillionDocumentsIndexed");
    var searchWord = "raven";
    var filter = Builders<BsonDocument>.Filter.Text(searchWord);

    var documentCount = 0;

    var stopwatch = new Stopwatch();
    stopwatch.Start();
    using (var cursor = collection.FindAsync(filter).Result)
    {
        while (cursor.MoveNext())  // <-- We never get past this point
        {
            var batch = cursor.Current;
            foreach (var document in batch)
            {
                Console.WriteLine(document["_id"].AsObjectId.ToString());
                Assert.That(document, Is.Not.Null);
                documentCount++;
            }
        }
    }
    stopwatch.Stop();
    Console.WriteLine($"Found {documentCount} documents.  Total time {stopwatch.ElapsedMilliseconds}ms.  Avg. {stopwatch.ElapsedMilliseconds / documentCount}");
}

它终于完成了:找到了158791文件。 总时间 1670368ms。 平均 10

做27分50秒。

C# MongoDB 驱动程序在文本搜索上非常慢

Task.Result 是一个阻塞调用(在本例中为集合。FindAsync(filter).结果),它将等到计算完整结果集,然后返回。

您可以尝试此代码,我相信它会表现得更好(尽管未经测试)

using(var cursor = await collection.Find(filter).ToCursorAsync())
{
    while(await cursor.MoveNextAsync())
    {
        //rest of logic ....

不确定您使用的 mongoDb 驱动程序版本,但您可以尝试一下吗

 while (cursor.MoveNextAsync().Result)