Momento Vector Index APIを使う
Momento Vector Index(MVI)は、AIを活用したアプリケーションで使用するベクトルデータをリアルタイムで保存・検索するために設計された、スケーラブルで開発者に優しいベクトルインデックスサービスです。
Vector Index Client
Momento Vector Indexes を操作するには、VectorIndexClient を使用する必要があります。
- JavaScript
- Python
new PreviewVectorIndexClient({
credentialProvider: CredentialProvider.fromEnvironmentVariable({
environmentVariableName: 'MOMENTO_API_KEY',
}),
configuration: VectorIndexConfigurations.Laptop.latest(),
});
PreviewVectorIndexClientAsync(
VectorIndexConfigurations.Default.latest(), CredentialProvider.from_environment_variable("MOMENTO_API_KEY")
)
Vector Index methods
Create Index
vector indexを作成
名前 | タイプ | 詳細 |
---|---|---|
indexName | String | vector indexの名前 |
numDimensions | String | Number of dimensions per vector. |
similarityMetric | String | Metric used to quantify the distance between vectors. Can be cosine similarity, inner product, or euclidean similarity. Defaults to cosine similarity. |
Method response object
- Success
- AlreadyExists
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.createIndex('test-index', 2);
if (result instanceof CreateVectorIndex.Success) {
console.log("Index 'test-index' created");
} else if (result instanceof CreateVectorIndex.AlreadyExists) {
console.log("Index 'test-index' already exists");
} else if (result instanceof CreateVectorIndex.Error) {
throw new Error(
`An error occurred while attempting to create index 'test-index': ${result.errorCode()}: ${result.toString()}`
);
}
response = await vector_client.create_index("test-index", 2)
match response:
case CreateIndex.Success():
print("Index 'test-index' created")
case CreateIndex.IndexAlreadyExists():
print("Index 'test-index' already exists")
case CreateIndex.Error() as error:
print(f"Error creating index 'test-index': {error.message}")
Delete Index
vector indexの削除
名前 | タイプ | 詳細 |
---|---|---|
indexName | String | vector indexの名前 |
Method response object
- Success
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.deleteIndex('test-index');
if (result instanceof DeleteVectorIndex.Success) {
console.log("Index 'test-index' deleted");
} else if (result instanceof DeleteVectorIndex.Error) {
throw new Error(
`An error occurred while attempting to delete index 'test-index': ${result.errorCode()}: ${result.toString()}`
);
}
response = await vector_client.delete_index("test-index")
match response:
case DeleteIndex.Success():
print("Index 'test-index' deleted")
case DeleteIndex.Error() as error:
print(f"Error deleting index 'test-index': {error.message}")
List Indexes
vector indexesの全てのリスト
Method response object
- Success
- getIndexes(): VectorIndexInfo[]
- VectorIndexInfo:
- name: String
- numDimensions: number
- similarityMetric: String
- VectorIndexInfo:
- getIndexes(): VectorIndexInfo[]
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.listIndexes();
if (result instanceof ListVectorIndexes.Success) {
console.log(
`Indexes:\n${result
.getIndexes()
.map(index => index.toString())
.join('\n')}\n\n`
);
} else if (result instanceof ListVectorIndexes.Error) {
throw new Error(`An error occurred while attempting to list caches: ${result.errorCode()}: ${result.toString()}`);
}
response = await vector_client.list_indexes()
match response:
case ListIndexes.Success() as success:
print(f"Indexes:\n{success.indexes}")
case CreateIndex.Error() as error:
print(f"Error listing indexes: {error.message}")
Upsert Item Batch
アイテムを一括でvector indexにUpsertsします。
名前 | タイプ | 詳細 |
---|---|---|
indexName | String | vector indexの名前 |
items | VectorIndexItem | indexにアップサートする項目。 |
Method response object
- Success
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.upsertItemBatch('test-index', [
{
id: 'example_item_1',
vector: [1.0, 2.0],
metadata: {key1: 'value1'},
},
{
id: 'example_item_2',
vector: [3.0, 4.0],
metadata: {key2: 'value2'},
},
]);
if (result instanceof VectorUpsertItemBatch.Success) {
console.log('Successfully added items');
} else if (result instanceof VectorUpsertItemBatch.Error) {
throw new Error(`An error occurred while adding items to index: ${result.errorCode()}: ${result.toString()}`);
}
response = await vector_client.upsert_item_batch(
"test-index",
[
Item(id="example_item_1", vector=[1.0, 2.0], metadata={"key1": "value1"}),
Item(id="example_item_2", vector=[3.0, 4.0], metadata={"key2": "value2"}),
],
)
match response:
case UpsertItemBatch.Success():
print("Successfully added items to index 'test-index'")
case UpsertItemBatch.Error() as error:
print(f"Error adding items to index 'test-index': {error.message}")
Search
クエリのベクトルに最も近いベクトルを持つアイテムを検索する。
名前 | タイプ | 詳細 |
---|---|---|
indexName | String | vector indexの名前 |
queryVector | number[] | 検索するベクトル |
topK | number | 返す結果の数。デフォルトは10 |
metadataFields | String[] or ALL_VECTOR_METADATA | 各結果とともに返すメタデータ・フィールドのリスト、またはすべてのメタデータを返すことを示す値です。指定しない場合は、メタデータは返されません。デフォルトは None |
Method response object
- Success
- hits(): SearchHit[]
- SearchHit:
- id: string
- score: number
- metadata: Map<string, string>
- SearchHit:
- hits(): SearchHit[]
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.search('test-index', [1.0, 2.0], {topK: 3, metadataFields: ALL_VECTOR_METADATA});
if (result instanceof VectorSearch.Success) {
console.log(`Found ${result.hits().length} matches`);
} else if (result instanceof VectorSearch.Error) {
throw new Error(`An error occurred searching index test-index: ${result.errorCode()}: ${result.toString()}`);
}
response = await vector_client.search("test-index", [1.0, 2.0], top_k=3, metadata_fields=ALL_METADATA)
match response:
case Search.Success() as success:
print(f"Found {len(success.hits)} matches")
case Search.Error() as error:
print(f"Error searching index 'test-index': {error.message}")
Search And Fetch Vectors
クエリのベクトルに最も近いベクトルを持つアイテムを検索します。検索ヒットしたベクトルに対応するベクトルも返します。
名前 | タイプ | 詳細 |
---|---|---|
indexName | String | vector indexの名前 |
queryVector | number[] | 検索するベクトル |
topK | number | 返す結果の数。デフォルトは10。 |
metadataFields | String[] or ALL_VECTOR_METADATA | 各結果とともに返すメタデータ・フィールドのリスト、またはすべてのメタデータを返すことを示す値です。指定しない場合は、メタデータは返されません。デフォルトは None |
Method response object
- Success
- hits(): SearchAndFetchVectorsHit[]
- SearchAndFetchVectorsHit:
- id: string
- score: number
- metadata: Map<string, string>
- vector: number[]
- SearchAndFetchVectorsHit:
- hits(): SearchAndFetchVectorsHit[]
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.searchAndFetchVectors('test-index', [1.0, 2.0], {
topK: 3,
metadataFields: ALL_VECTOR_METADATA,
});
if (result instanceof VectorSearchAndFetchVectors.Success) {
console.log(`Found ${result.hits().length} matches`);
} else if (result instanceof VectorSearchAndFetchVectors.Error) {
throw new Error(`An error occurred searching index test-index: ${result.errorCode()}: ${result.toString()}`);
}
response = await vector_client.search_and_fetch_vectors(
"test-index", [1.0, 2.0], top_k=3, metadata_fields=ALL_METADATA
)
match response:
case SearchAndFetchVectors.Success() as success:
print(f"Found {len(success.hits)} matches")
case SearchAndFetchVectors.Error() as error:
print(f"Error searching index 'test-index': {error.message}")
Delete Item Batch
vector indexから項目を一括削除します。
名前 | タイプ | 詳細 |
---|---|---|
indexName | String | vector indexの名前 |
items | String[] | IDs of the items to be deleted. |
Method response object
- Success
- Error
詳しくはレスポンスオブジェクトを参照してください。
- JavaScript
- Python
const result = await vectorClient.deleteItemBatch('test-index', ['example_item_1', 'example_item_2']);
if (result instanceof VectorUpsertItemBatch.Success) {
console.log('Successfully deleted items');
} else if (result instanceof VectorUpsertItemBatch.Error) {
throw new Error(`An error occurred while deleting items: ${result.errorCode()}: ${result.toString()}`);
}
response = await vector_client.delete_item_batch("test-index", ["example_item_1", "example_item_2"])
match response:
case DeleteItemBatch.Success():
print("Successfully deleted items from index 'test-index'")
case DeleteItemBatch.Error() as error:
print(f"Error deleting items from index 'test-index': {error.message}")