Overview
In this guide, you can learn how to use Django MongoDB Backend to perform MongoDB Vector Search queries. This feature allows you to perform a semantic search on your documents. A semantic search is a type of search that locates information that is similar in meaning, but not necessarily identical, to your provided search term or phrase.
サンプル データ
The examples in this guide use the MovieWithEmbeddings model, which represents the sample_mflix.embedded_movies collection from the Atlas sample datasets. The MovieWithEmbeddings model class has the following definition:
from django.db import models from django_mongodb_backend.fields import ArrayField class MovieWithEmbeddings(models.Model): title = models.CharField(max_length=200) runtime = models.IntegerField(default=0) plot_embedding = ArrayField(models.FloatField(), size=1536, null=True, blank=True) class Meta: db_table = "embedded_movies" managed = False def __str__(self): return self.title
MovieWithEmbeddings モデルには、モデルメタデータを指定する内部 Metaクラスと、モデルの string 表現を定義する __str__() メソッドが含まれています。 これらのモデル機能の詳細については、「 モデルの作成ガイドの モデルの定義 」を参照してください。
コード例の実行
Pythonインタラクティブシェル を使用してコード例を実行できます。 シェルを入力するには、プロジェクトの ルートディレクトリから次のコマンドを実行します。
python manage.py shell
Python シェルを入力したら、次のモデルとモジュールをインポートしていることを確認します。
from <your application name>.models import MovieWithEmbeddings
モデルとPython対話型シェルMovie を使用してMongoDBドキュメントを操作する Dlangoアプリケーションを作成する方法については、「 Diango MongoDBバックエンドを使い始める 」チュートリアルをご覧ください。
ベクトル検索の実行
重要
クエリ要件
MongoDB ベクトル検索の検索クエリを実行する前に、コレクションにベクトル検索インデックスを作成する必要があります。Django MongoDBバックエンドを使用してベクトル検索インデックスを作成する方法については、インデックスの作成ガイドのベクトル検索インデックスを参照してください。
Django MongoDBバックエンドを使用すると、セマンティック意味に基づいてデータをクエリできます。MongoDB ベクトル検索クエリは、クエリベクトル、または検索する期間やフレーズの意味を表す数値の配列に基づいて結果を返します。MongoDB は、このクエリベクトルをドキュメントのベクトルフィールドに保存されているベクトルと比較します。
To specify your Vector Search criteria, create an instance of the SearchVector expression class provided by the django_mongodb_backend.expressions module. This expression corresponds to the $vectorSearch MongoDB pipeline stage. Pass the following arguments to the SearchVector() constructor:
path: クエリするフィールド。query_vector: 検索条件を表す数値の配列。クエリ ベクトルの詳細については、 MongoDB Atlasドキュメントの「 ベクトル 」を参照してください。limit: 返される結果の最大数。num_candidates: (任意)クエリで考慮するドキュメントの数。exact: (任意) 完全近傍(enn)検索を実行するかどうかを示すブール値値。デフォルト値はFalseです。厳密最近傍探索の詳細については、MongoDB Atlasドキュメントの厳密最近傍探索を参照してください。filter: (任意)クエリ結果に適用するフィルター。
次に、SearchVectorインスタンスをDjangoのQuerySet APIからannotateメソッドに渡して、ベクトル検索クエリを実行する。次のコードは、ベクトル検索クエリを実行するための構文を示しています。
from django_mongodb_backend.expressions import SearchVector Model.objects.annotate( score=SearchVector( path="<field name>", query_vector=[<vector values>], limit=<number>, num_candidates=<number>, exact=<boolean>, filter=<filter expression> ) )
基本的なベクトル検索の例
この例では、sample_mflix.embedded_moviesコレクションに対してMongoDBベクトル検索クエリを実行します。クエリは、次のアクションを実行します。
plot_embeddingベクトルフィールドをクエリします。結果を
5ドキュメントに制限します。Specifies an Approximate Nearest Neighbor (ANN) vector search that considers
150candidates. To learn more about ANN searches, see ANN Search in the MongoDB Atlas documentation.
vector_values = [float(i % 10) * 0.1 for i in range(1536)] MovieWithEmbeddings.objects.annotate( score=SearchVector( path="plot_embedding", query_vector=vector_values, limit=5, num_candidates=150, exact=False, ) )
Tip
The preceding code example passes an arbitrary vector to the query_vector argument. To learn how to generate a vector that represents the meaning of a search term or phrase, see How to Create Vector Embeddings Manually in the MongoDB Atlas documentation.
ベクトル検索のスコアの例
MongoDB は、ベクトル検索クエリで返されるすべてのドキュメントに関連性スコアを割り当てます。結果セットに含まれるドキュメントは、関連性スコアの高いものから低いものの順に並べられます。
このスコアをクエリ結果に含めるには、Diango の QuerySet APIの values() メソッドを使用できます。scoreフィールドをvalues() メソッドの引数として渡します。
次の例は、前の例と同じベクトル検索クエリーを実行し、ドキュメントのベクトル検索関連性スコアを出力する方法を示しています。
vector_values = [float(i % 10) * 0.1 for i in range(1536)] MovieWithEmbeddings.objects.annotate( score=SearchVector( path="plot_embedding", query_vector=vector_values, limit=5, num_candidates=150, exact=False, ) ).values("title", "score")
詳細情報
MongoDB ベクトル検索の詳細については、MongoDB Atlasドキュメントの次のリソースを参照してください。