AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

MongoDB 벡터 검색 쿼리 실행

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 클래스와 모델의 문자열 표현을 정의하는 __str__() 메서드가 포함되어 있습니다. 이러한 모델 기능에 대해 학습 모델 생성 가이드 에서 모델 정의를 참조하세요.

Python 대화 셸 사용하여 코드 예제를 실행 수 있습니다. 셸 에 들어가려면 프로젝트의 루트 디렉토리 에서 다음 명령을 실행 .

python manage.py shell

Python 셸 입력한 후 다음 모델 및 모듈을 가져와야 합니다.

from <your application name>.models import MovieWithEmbeddings

모델과 Python 인터랙티브 셸 사용하여 MongoDB 문서와 상호 작용 Django 애플리케이션 만드는 방법을 Movie 학습 Django MongoDB 백엔드 시작하기 튜토리얼을 참조하세요.

중요

쿼리 요구 사항

MongoDB 벡터 검색 쿼리를 수행하려면 먼저 컬렉션 에 벡터 검색 인덱스 생성해야 합니다. 장고 MongoDB 백엔드를 사용하여 벡터 검색 인덱스 만드는 방법을 학습 인덱스 만들기 가이드 에서 벡터 검색 인덱스를 참조하세요.

장고 MongoDB 백엔드를 사용하여 시맨틱 의미를 기반으로 데이터를 쿼리 할 수 있습니다. MongoDB Vector Search 쿼리 쿼리 벡터 또는 검색 나 텀 의 의미를 나타내는 숫자 배열 기반으로 결과를 반환합니다. 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: (선택 사항) 쿼리 결과에 적용 할 필터하다 .

그런 다음 장고의 QuerySet API 에서 SearchVector 인스턴스 annotate 메서드에 전달하여 Vector Search 쿼리 실행 . 다음 코드는 벡터 검색 쿼리 수행하기 위한 구문을 보여줍니다.

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 Vector Search 쿼리 실행합니다. 쿼리 다음 조치를 수행합니다.

  • plot_embedding 벡터 필드 쿼리합니다.

  • 결과를 5 문서로 제한합니다.

  • Specifies an Approximate Nearest Neighbor (ANN) vector search that considers 150 candidates. 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,
)
)

팁

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 Vector Search 쿼리 에서 반환되는 모든 문서 에 관련성 점수를 할당합니다. 결과 집합에 포함된 문서는 관련성 점수가 가장 높은 순서에서 가장 낮은 순서로 정렬됩니다.

쿼리 결과에 이 점수를 포함하려면 장고의 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 Vector Search에 대해 자세히 학습 MongoDB Atlas 설명서에서 다음 리소스를 참조하세요.