

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

Baru dari versi 8.0

Tidak didukung oleh cluster elastis.

`$vectorSearch`Operator di Amazon DocumentDB memungkinkan Anda melakukan pencarian vektor, metode yang digunakan dalam pembelajaran mesin untuk menemukan titik data serupa dengan membandingkan representasi vektornya menggunakan metrik jarak atau kesamaan. Kemampuan ini menggabungkan fleksibilitas dan kueri yang kaya dari database dokumen berbasis JSON dengan kekuatan pencarian vektor, memungkinkan Anda untuk membangun pembelajaran mesin dan kasus penggunaan AI generatif seperti pencarian semantik, rekomendasi produk, dan banyak lagi.

**Parameter**
+ `<exact>`(opsional): Bendera yang menentukan apakah akan menjalankan pencarian Exact Nearest Neighbor (ENN) atau Perkiraan Tetangga Terdekat (ANN). Nilai dapat menjadi salah satu dari berikut ini:
+ false - untuk menjalankan pencarian ANN
+ true - untuk menjalankan pencarian ENN

Jika dihilangkan atau disetel ke false, `numCandidates` diperlukan.

```
- `<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.
```

## Contoh (MongoDB Shell)
<a name="vectorSearch-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan `$vectorSearch` operator untuk menemukan deskripsi produk serupa berdasarkan representasi vektor mereka.

**Buat dokumen sampel**

```
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]
  }
]);
```

**Buat indeks pencarian vektor**

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

**Contoh kueri**

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

**Keluaran**

```
[
  {
    "_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 ]
  }
]
```

## Contoh kode
<a name="vectorSearch-code"></a>

Untuk melihat contoh kode untuk menggunakan `$vectorSearch` perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

------
#### [ 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])
```

------