11.. _csharp-atlas-vector-search:
22
3- ===================
4- Atlas Vector Search
5- ===================
3+ ================================
4+ Run an Atlas Vector Search Query
5+ ================================
66
77.. facet::
88 :name: genre
99 :values: reference
1010
1111.. meta::
12- :keywords: semantic
12+ :keywords: .NET, search, semantic, AI, RAG
1313
1414.. contents:: On this page
1515 :local:
1616 :backlinks: none
1717 :depth: 2
1818 :class: singlecol
1919
20- Sample Class
21- ------------
20+ Overview
21+ --------
2222
23- The code examples in this guide demonstrate how you can use builders to
24- create types to interact with documents in the sample collection ``plants.flowers``.
25- Documents in this collection are modeled by the following ``Flower`` class:
23+ You can use {+avs+} to perform vector search on your data stored in
24+ Atlas. Vector search allows you to query your data based on semantic meaning
25+ rather than just keyword matches, which helps you retrieve more relevant search
26+ results. It enables your AI-powered applications to support use cases such as
27+ semantic search, hybrid search, and generative search, including
28+ Retrieval-Augmented Generation (RAG).
2629
27- .. literalinclude:: /includes/fundamentals/code-examples/builders.cs
30+ By using Atlas as a vector database, you can seamlessly index vector data along
31+ with your other data in Atlas. This allows you to filter on fields in your
32+ collection and perform vector search queries against vector data. You can also
33+ combine vector search with full-text search queries to return the most relevant
34+ results for your use case. You can integrate {+avs+} with popular AI
35+ frameworks and services to easily implement vector search in your applications.
36+
37+ To learn more about {+avs+}, see the :atlas:`{+avs+}
38+ </atlas-vector-search/vector-search-overview/>` guide in the MongoDB Atlas
39+ documentation.
40+
41+ Sample Data
42+ ~~~~~~~~~~~
43+
44+ The examples in this guide use the ``sample_mflix.embedded_movies`` collection
45+ in the ``sample_mflix`` database. To obtain the sample dataset for this collection,
46+ see :ref:`csharp-get-started`.
47+
48+ The examples in this guide use the following sample class to model documents in the
49+ ``sample_mflix.embedded_movies`` collection:
50+
51+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs
2852 :language: csharp
29- :dedent:
30- :start-after: start-model
31- :end-before: end-model
53+ :start-after: start-sample-class
54+ :end-before: end-sample-class
55+
56+ .. _csharp-supported-vector-types:
3257
33- Each builder class takes a generic type parameter
34- ``TDocument`` which represents the type of document that you are working
35- with. In this guide, the ``Flower`` class is the document type used in
36- each builder class example.
58+ Supported Vector Embedding Types
59+ --------------------------------
3760
38- Perform an Atlas Vector Search
39- ------------------------------
61+ :atlas:`Vector embeddings
62+ </atlas-vector-search/vector-search-overview/#std-term-vector-embeddings>`
63+ are vectors you use to represent your data. These embeddings
64+ capture meaningful relationships in your data and enable tasks like semantic
65+ search and retrieval.
4066
41- You can use builders to create a ``$vectorSearch`` aggregation pipeline stage to perform an
42- approximate nearest neighbor search on a vector in the specified field. Your collection *must*
43- have a defined Atlas Vector Search index before you can perform a vector search on your data.
67+ The {+driver-short+} supports vector embeddings of several types. The following
68+ sections describe the supported vector embedding types.
69+
70+ .. _csharp-vector-array-representation:
71+
72+ Array Representations
73+ ~~~~~~~~~~~~~~~~~~~~~
74+
75+ The {+driver-short+} supports the following representations of the array
76+ type in vector embeddings:
77+
78+ - ``BsonArray``
79+ - ``Memory``
80+ - ``ReadOnlyMemory``
81+ - ``float[]`` and ``double[]``
82+
83+ The following example shows a class with properties of the preceding types:
84+
85+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs
86+ :language: csharp
87+ :start-after: start-bson-arrays
88+ :end-before: end-bson-arrays
89+
90+ .. tip::
91+
92+ To learn more about using the ``Memory`` and ``ReadOnlyMemory``
93+ types, see the :ref:`csharp-array-serialization` section of the
94+ Serialization guide.
95+
96+ .. _csharp-binary-vector-representation:
97+
98+ Binary Vector Representations
99+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
100+
101+ The {+driver-short+} supports the following binary vector representations in
102+ vector embeddings:
103+
104+ - ``BinaryVectorFloat32`` (not supported on big-endian architectures)
105+ - ``BinaryVectorInt8``
106+ - ``BinaryVectorPackedBit``
107+ - ``Memory<float>``, ``Memory<byte>``, ``Memory<sbyte>``
108+ - ``ReadOnlyMemory<float>``, ``ReadOnlyMemory<byte>``, ``ReadOnlyMemory<sbyte>``
109+ - ``float[]``, ``byte[]``, ``sbyte[]``
110+
111+ .. note::
112+
113+ You must use the ``BinaryVector`` attribute when specifying binary vector
114+ representations of the ``Memory<T>``, ``ReadOnlyMemory<T>``, or array
115+ types.
116+
117+ The following example shows a class with properties of the preceding types:
118+
119+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs
120+ :language: csharp
121+ :start-after: start-binary-vectors
122+ :end-before: end-binary-vectors
123+
124+ Binary Vector Data Serialization
125+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
126+
127+ You can serialize ``Int8`` binary vector typed data as ``byte`` or ``sbyte``.
128+ You can also serialize ``Float32`` binary vector typed data as ``float``. The
129+ following example serializes ``Int8`` and ``Float32`` binary vector data:
130+
131+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs
132+ :language: csharp
133+ :start-after: start-binary-int-float-serialize
134+ :end-before: end-binary-int-float-serialize
135+
136+ You can deserialize ``PackedBit`` vector data to a :ref:`binary vector
137+ represented <csharp-binary-vector-representation>` ``byte`` data type only if the
138+ vector data has a padding value of ``0``. If the vector data has a padding value not
139+ equal to ``0``, you can deserialize it only to a ``BsonVectorPackedBit``.
140+
141+ Vector Search Query Example
142+ ---------------------------
143+
144+ You can perform a vector search query by calling the ``VectorSearch()`` method.
145+ To perform a vector search on a collection, you must first have a collection with a field that contains
146+ vector data and a vector search index that covers that field.
147+
148+ To learn more about configuring a collection for vector search, see the :atlas:`{+avs+}
149+ </atlas-vector-search/vector-search-overview/>` guide in the MongoDB Atlas
150+ documentation.
151+
152+ You can convert ``BinaryVectorFloat32``, ``BinaryVectorInt8``, and
153+ ``BinaryVectorPackedBit`` data to the ``BsonBinaryData`` type to use in a vector
154+ search query by using the ``ToQueryVector()`` method. The following example
155+ converts ``BinaryVectorInt8`` into a ``BsonBinaryData`` object:
156+
157+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs
158+ :language: csharp
159+ :start-after: start-to-query-vector
160+ :end-before: end-to-query-vector
161+
162+ You can specify your :ref:`array-represented
163+ <csharp-vector-array-representation>` vector data as an instance of the
164+ ``QueryVector`` class to use in a vector search query. The following example
165+ creates an array of ``ReadOnlyMemory<float>`` values as a ``QueryVector`` object
166+ to use in a vector search query:
167+
168+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchExamples.cs
169+ :language: csharp
170+ :start-after: start-array-query-vector
171+ :end-before: end-array-query-vector
172+
173+ Consider the ``embedded_movies`` collection in the ``sample_mflix`` database. You
174+ can use a ``$vectorSearch`` stage to perform a semantic search on the ``plot_embedding``
175+ field of the documents in the collection.
176+ The following sections describe different methods for performing Atlas Vector Search operations
177+ on this collection.
44178
45179.. tip::
46180
@@ -49,15 +183,20 @@ have a defined Atlas Vector Search index before you can perform a vector search
49183 :atlas:`Create an Atlas Vector Search Index </atlas-vector-search/create-index>` in the
50184 Atlas manual.
51185
52- Consider the ``embedded_movies`` collection in the ``sample_mflix`` database. You
53- can use a ``$vectorSearch`` stage to perform a semantic search on the ``plot_embedding``
54- field of the documents in the collection.
186+ Aggregation Pipeline Example
187+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
55188
56- The following example shows how to use builders to generate an aggregation pipeline to
57- perform the following operations :
189+ This example performs the following steps to run an {+avs+} query on a collection that
190+ contains vector data and a vector search index on the ``PlotEmbedding`` field :
58191
59- - Performs a vector search on the Atlas Vector Search index of the ``plot_embedding`` field using vector embeddings for the string ``"time travel"``
60- - Fetches the ``Title`` and ``Plot`` fields from documents found in the vector search
192+ 1. Creates an array that contains the :ref:`array-represented
193+ <csharp-vector-array-representation>` vector data to search for
194+ #. Specifies a ``VectorSearchOptions`` object that contains the name of the index
195+ and the number of nearest neighbors to use during the search
196+ #. Creates an aggregation pipeline that uses the ``VectorSearch()`` stage to
197+ perform the vector search query and a ``Project()`` stage to display only
198+ the ``Title``, ``Plot``, and ``Score`` fields
199+ #. Prints the results of the query
61200
62201.. code-block:: csharp
63202
@@ -75,7 +214,7 @@ perform the following operations:
75214 // Builds aggregation pipeline and specifies that the $vectorSearch stage
76215 // returns 10 results
77216 var pipeline = new EmptyPipelineDefinition<EmbeddedMovie>()
78- .VectorSearch(m => m.Embedding , vector, 10, options)
217+ .VectorSearch(m => m.PlotEmbedding , vector, 10, options)
79218 .Project(Builders<EmbeddedMovie>.Projection
80219 .Include(m => m.Title)
81220 .Include(m => m.Plot)
@@ -96,5 +235,40 @@ The results of the preceding example contain the following documents:
96235 { "_id" : { "$oid" : "573a13b6f29313caabd477fa" }, "plot" : "With the help of his uncle, a man travels to the future to try and bring his girlfriend back to life.", "title" : "Love Story 2050", "score" : 0. 917755126953125 }
97236 { "_id" : { "$oid" : "573a13b3f29313caabd3ebd4" }, "plot" : "A romantic drama about a Chicago librarian with a gene that causes him to involuntarily time travel, and the complications it creates for his marriage.", "title" : "The Time Traveler's Wife", "score" : 0.9172210693359375 }
98237
99- To learn more about Atlas Vector Search, see :atlas:`Atlas Vector Search Overview </atlas-vector-search/vector-search-overview/>`
100- in the Atlas manual.
238+ LINQ Example
239+ ~~~~~~~~~~~~
240+
241+ The following code sample performs the same vector search query as the preceding example, but uses
242+ the LINQ syntax instead of the aggregation pipeline syntax:
243+
244+ .. literalinclude:: /includes/fundamentals/code-examples/atlas-vector-search/VectorSearchQueryExample.cs
245+ :language: csharp
246+ :start-after: start-linq-example
247+ :end-before: end-linq-example
248+ :dedent:
249+ :emphasize-lines: 2
250+
251+ Additional Information
252+ ----------------------
253+
254+ To learn more about {+avs+}, see the :atlas:`{+avs+}
255+ </atlas-vector-search/vector-search-overview/>` guide in the MongoDB Atlas
256+ documentation.
257+
258+ API Documentation
259+ ~~~~~~~~~~~~~~~~~
260+
261+ To learn more about any of the functions or types discussed in this
262+ guide, see the following API Documentation:
263+
264+ - `BinaryVectorFloat32 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorFloat32.html>`__
265+ - `BinaryVectorInt8 <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorInt8.html>`__
266+ - `BinaryVectorPackedBit <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.BinaryVectorPackedBit.html>`__
267+ - `QueryVector <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.QueryVector.html>`__
268+ - `ToQueryVector() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.BinaryVectorDriverExtensions.ToQueryVector.html>`__
269+ - `IAggregateFluentExtensions.VectorSearch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAggregateFluentExtensions.VectorSearch.html>`__
270+ - `Aggregate()
271+ <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Aggregate.html>`__
272+ - `MongoQueryable.VectorSearch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.Linq.MongoQueryable.VectorSearch.html>`__
273+ - `PipelineStageDefinitionBuilder.VectorSearch()
274+ <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.PipelineStageDefinitionBuilder.VectorSearch.html>`__
0 commit comments