在 C# 中对 MongoDB 执行向量搜索

问题描述 投票:0回答:1

我正在使用适用于 MongoDB 的 Azure Cosmos DB 和新功能来为集合创建矢量索引。我的部分数据结构如下所示:

public class TextChunk
    {
        public string Id {get; set;} = null!;
        public float[]? TextVectors { get; internal set; }
    }
}

我按照 这个 Microsoft 教程 创建向量索引,但是所有示例都是针对 JavaScript,而我想使用 C#/.Net 来执行向量搜索。

我尝试使用

collection.Aggregate().VectorSearch
但出现错误:

An exception of type 'MongoDB.Driver.MongoCommandException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'Command aggregate failed: Unrecognized pipeline stage name: $vectorSearch.'

矢量搜索管道阶段可能仅在使用 MongoDB Atlas 时可用?

我的问题是,如何在我的设置中执行矢量搜索? IE。基本上,如何将上述教程中的 JavaScript 示例转换为 C# MongoDB 库?

(.Net 7,MongoDb.Driver版本2.22.0)

c# .net mongodb-.net-driver azure-cosmosdb-mongoapi vector-search
1个回答
0
投票

我找到了一种方法来做我想做的事。我正在使用我在问题中链接的教程中提供的(部分)JSON。然后,我将其解析为 BSON 文档,从中创建管道定义,并按以下方式执行它:

BsonDocument bson = BsonDocument.Parse(json);
    
PipelineDefinition<TextChunk, TextChunk> pipeline = new BsonDocument[] 
{
    bson
};

return collection.Aggregate(pipeline);

如果有人好奇,这是 json 字符串:

var json =
   "{" + 
     "\"$search\": {" +
       "\"cosmosSearch\": {" +
         "\"vector\": " + searchVectorString +"," +
         "\"path\": \"" + "TextVectors" + "\"," +
         "\"k\": 2" +
        "}," +
       "\"returnStoredSource\": true }" +
   "}";

其中

searchVectorString
是格式为
[0.00, 0.00, ...]

的查询向量
© www.soinside.com 2019 - 2024. All rights reserved.