.net 在C#中在MongoDB上执行向量搜索

wfypjpf4  于 2023-11-20  发布在  .NET
关注(0)|答案(1)|浏览(167)

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

  1. public class TextChunk
  2. {
  3. public string Id {get; set;} = null!;
  4. public float[]? TextVectors { get; internal set; }
  5. }

字符串
我使用this Microsoft tutorial创建了向量索引,但所有示例都是针对JavaScript的,而我想使用C#/.Net执行向量搜索。
我试过使用collection.Aggregate().VectorSearch,但我得到错误:

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


Vector Search管道阶段可能仅在使用MongoDB Atlas时可用?
我的问题是,我如何在我的设置中执行向量搜索?也就是说,基本上,我如何将上述教程中的JavaScript示例转换为C# MongoDB库?
(.Net 7、MongoDb.驱动程序版本2.22.0)

dwthyt8l

dwthyt8l1#

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

  1. BsonDocument bson = BsonDocument.Parse(json);
  2. PipelineDefinition<TextChunk, TextChunk> pipeline = new BsonDocument[]
  3. {
  4. bson
  5. };
  6. return collection.Aggregate(pipeline);

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

  1. var json =
  2. "{" +
  3. "\"$search\": {" +
  4. "\"cosmosSearch\": {" +
  5. "\"vector\": " + searchVectorString +"," +
  6. "\"path\": \"" + "TextVectors" + "\"," +
  7. "\"k\": 2" +
  8. "}," +
  9. "\"returnStoredSource\": true }" +
  10. "}";


其中searchVectorString是格式为[0.00, 0.00, ...]的查询向量

展开查看全部

相关问题