

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# \$1vectorSearch
<a name="vectorSearch"></a>

버전 8.0의 새로운 기능

Elastic 클러스터에서는 지원되지 않습니다.

Amazon DocumentDB의 `$vectorSearch` 연산자를 사용하면 기계 학습에 사용되는 메서드인 벡터 검색을 수행하여 거리 또는 유사성 지표를 사용하여 벡터 표현을 비교하여 유사한 데이터 포인트를 찾을 수 있습니다. 이 기능은 JSON 기반 문서 데이터베이스의 유연성과 풍부한 쿼리를 벡터 검색의 기능과 결합하여 의미 체계 검색, 제품 권장 사항 등과 같은 기계 학습 및 생성형 AI 사용 사례를 구축할 수 있습니다.

**파라미터**
+ `<exact>` (선택 사항): 정확히 가장 가까운 이웃(ENN) 또는 대략적인 가장 가까운 이웃(ANN) 검색을 실행할지 여부를 지정하는 플래그입니다. 값은 다음 중 하나일 수 있습니다.
+ false - ANN 검색을 실행하려면
+ true - ENN 검색을 실행하려면

생략하거나 false로 설정하면 `numCandidates`가 필요합니다.

```
- `<index>` : Name of the Vector Search index to use.
- `<limit>` : Number of documents to return in the results.
- `<numCandidates>` (optional): This field is required if 'exact' is false or omitted. Number of nearest neighbors to use during the search. Value must be less than or equal to (<=) 10000. You can't specify a number less than the number of documents to return ('limit').
- `<path>` : Indexed vector type field to search.
- `<queryVector>` : Array of numbers that represent the query vector.
```

## 예제(MongoDB 쉘)
<a name="vectorSearch-examples"></a>

다음 예제에서는 `$vectorSearch` 연산자를 사용하여 벡터 표현을 기반으로 유사한 제품 설명을 찾는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.products.insertMany([
  {
    _id: 1,
    name: "Product A",
    description: "A high-quality, eco-friendly product for your home.",
    description_vector: [ 0.2, 0.5, 0.8 ]
  },
  {
    _id: 2,
    name: "Product B",
    description: "An innovative and modern kitchen appliance.",
    description_vector: [0.7, 0.3, 0.9]
  },
  {
    _id: 3,
    name: "Product C",
    description: "A comfortable and stylish piece of furniture.",
    description_vector: [0.1, 0.2, 0.4]
  }
]);
```

**벡터 검색 인덱스 생성**

```
db.runCommand(
    {
        createIndexes: "products",
        indexes: [{
            key: {
                "description_vector": "vector"
            },
            vectorOptions: {
                type: "hnsw",
                dimensions: 3,
                similarity: "cosine",
                m: 16,
                efConstruction: 64
            },
            name: "description_index"
        }]
    }
);
```

**쿼리 예제**

```
db.products.aggregate([
  { $vectorSearch: {
      index: "description_index",
      limit: 2,
      numCandidates: 10,
      path: "description_vector",
      queryVector: [0.1, 0.2, 0.3]
    }
  }
]);
```

**출력**

```
[
  {
    "_id": 1,
    "name": "Product A",
    "description": "A high-quality, eco-friendly product for your home.",
    "description_vector": [ 0.2, 0.5, 0.8 ]
  },
  {
    "_id": 3,
    "name": "Product C",
    "description": "A comfortable and stylish piece of furniture.",
    "description_vector": [ 0.1, 0.2, 0.4 ]
  }
]
```

## 코드 예제
<a name="vectorSearch-code"></a>

`$vectorSearch` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function findSimilarProducts(queryVector) {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('products');

  const result = await collection.aggregate([
    { $vectorSearch: {
        index: "description_index",
        limit: 2,
        numCandidates: 10,
        path: "description_vector",
        queryVector: queryVector
      }
    }
  ]).toArray();

  console.log(result);
  client.close();
}

findSimilarProducts([0.1, 0.2, 0.3]);
```

------
#### [ Python ]

```
from pymongo import MongoClient


def find_similar_products(query_vector):
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.test
    collection = db.products

    result = list(collection.aggregate([
        {
            '$vectorSearch': {
                'index': "description_index",
                'limit': 2,
                'numCandidates': 10,
                'path': "description_vector",
                'queryVector': query_vector
            }
        }
    ]))

    print(result)
    client.close()

find_similar_products([0.1, 0.2, 0.3])
```

------