Я успешно создал коллекцию Milvus и вставил данные напрямую без каких-либо заметных проблем. Теперь я хочу создать коллекцию Milvus, используя RESTful API, как подробно описано в документации по созданию коллекции.
Я использовал следующий код, который я адаптировал. предоставленную ссылку, чтобы создать коллекцию, настроить ее, вставить данные и затем создать индекс.
import time
import requests
import json
import numpy as np
def generate_random_vector():
float_array = np.random.uniform(-1, 1, 512)
normalized_array = float_array / np.linalg.norm(float_array, ord=2)
return normalized_array
def create_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/create"
payload = json.dumps({
"collectionName": collection_name,
"dimension": 512,
"metricType": "COSINE",
"vectorFieldName": "Embedding_Features",
"primaryFieldName": "IDs_Features",
"idType": "Int64",
"indexType": "HNSW",
"primaryKey": {"name": "IDs_Features", "type": "INT64", "primaryKey": True},
"vectorField": {
"name": "Embedding_Features",
"type": "FLOAT_VECTOR",
"primaryKey": False,
},
"indexes": [{
"fieldName": "Embedding_Features",
"indexName": "Embedding_Features",
"metricType": "COSINE",
}],
"auto_index": False,
})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def validate_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/describe"
payload = json.dumps({"collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def drop_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/drop"
payload = json.dumps({"collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def insert_data_into_collection(
collection_name: str,
start_id: int,
n: int,
ids_name: str,
features_name: str,
server_address: str,
):
url = f"{server_address}/v2/vectordb/entities/insert"
data = [{"IDs_Features": start_id + i + 1, "Embedding_Features": list(generate_random_vector())} for i in range(n)]
payload = json.dumps({"data": data, "collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def describe_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/describe"
payload = json.dumps({"collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def describe_index(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/indexes/describe"
payload = json.dumps({"indexName": "Embedding_Features", "collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def create_index(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/indexes/create"
payload = json.dumps({
"collectionName": collection_name,
"indexParams": [{
"metricType": "COSINE",
"index_type": "HNSW",
"fieldName": "Embedding_Features",
"params": {"M": 128, "efConstruction": 256},
}],
})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
Когда я попытался создать коллекцию, используя:
create_collection(collection_name=collection_name, server_address=server_address)
Я получил следующее сообщение:
{'code': 0, 'data': {}}
Впоследствии, когда я описывал коллекцию:
describe_collection(collection_name=collection_name, server_address=server_address)
Я получил такой ответ:
{'code': 0,
'data': {'aliases': [],
'autoId': False,
'collectionID': 454176377651168636,
'collectionName': 'collection1',
'consistencyLevel': 'Bounded',
'description': '',
'enableDynamicField': True,
'fields': [{'autoId': False,
'clusteringKey': False,
'description': '',
'id': 100,
'name': 'IDs_Features',
'nullable': False,
'partitionKey': False,
'primaryKey': True,
'type': 'Int64'},
{'autoId': False,
'clusteringKey': False,
'description': '',
'id': 101,
'name': 'Embedding_Features',
'nullable': False,
'params': [{'key': 'dim', 'value': '512'}],
'partitionKey': False,
'primaryKey': False,
'type': 'FloatVector'}],
'functions': None,
'indexes': [{'fieldName': 'Embedding_Features',
'indexName': 'Embedding_Features',
'metricType': 'COSINE'}],
'load': 'LoadStateLoading',
'partitionsNum': 1,
'properties': [],
'shardsNum': 1},
'message': ''}
Когда я описывал индекс коллекции:
describe_index(collection_name=collection_name, server_address=server_address)
Я получил это сообщение:
{'code': 0,
'data': [{'failReason': '',
'fieldName': 'Embedding_Features',
'indexName': 'Embedding_Features',
'indexState': 'Finished',
'indexType': 'AUTOINDEX',
'indexedRows': 0,
'metricType': 'COSINE',
'pendingRows': 0,
'totalRows': 0}]}
Это указывало на то, что для типа индекса было установлено значение AUTOINDEX, несмотря на то, что в моей конфигурации указан HNSW, что вызывало проблемы с индексированием.
p>
После этого я вставил в коллекцию 10 000 строк:
number_vectors = 10000
for i in range(0, number_vectors, 500):
response = insert_data_into_collection(
collection_name=collection_name,
start_id=i,
n=500,
ids_name="IDs_Features",
features_name="Embedding_Features",
server_address=server_address,
)
if response["data"]["insertCount"] == 500:
print(f"Great! inserted ids {i} to {i+500} successfully")
else:
print(f"There are some errors for {i}")
time.sleep(1)
Наконец, когда я попытался создать индекс:
create_index(collection_name=collection_name, server_address=server_address)
Я обнаружил следующую ошибку:
{'code': 65535, 'message': 'only metric type can be passed when use AutoIndex'}
Можно ли мне установить для indexType значение HNSW и игнорировать или удалить AutoIndex по умолчанию > значение?
Путем настройки функции create_index:
def create_index(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/indexes/create"
payload = json.dumps(
{
"collectionName": collection_name,
"indexParams": [
{
"metricType": "COSINE",
"fieldName": "Embedding_Features",
"params": {"M": 128, "efConstruction": 256, "index_type": "HNSW"},
}
],
}
)
# Example: {'metric_type': 'IP', 'index_type': 'HNSW', 'params': {'nlist': 1024, 'efConstruction': 40, 'M': 1024}}
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
response = json.loads(response.text)
return response
Я обнаружил следующую ошибку:
{'code': 65535,
'message': 'CreateIndex failed: at most one distinct index is allowed per field'}
Подробнее здесь: https://stackoverflow.com/questions/792 ... ng-an-inde
Невозможно изменить indexType по умолчанию с AutoIndex на HNSW при создании индекса в коллекции Milvus через RESTful API ⇐ Python
Программы на Python
1734211087
Anonymous
Я успешно создал коллекцию Milvus и вставил данные [b]напрямую[/b] без каких-либо заметных проблем. Теперь я хочу создать коллекцию Milvus, используя [b]RESTful API[/b], как подробно описано в документации по созданию коллекции.
Я использовал следующий код, который я адаптировал. предоставленную ссылку, чтобы создать коллекцию, настроить ее, вставить данные и затем создать индекс.
import time
import requests
import json
import numpy as np
def generate_random_vector():
float_array = np.random.uniform(-1, 1, 512)
normalized_array = float_array / np.linalg.norm(float_array, ord=2)
return normalized_array
def create_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/create"
payload = json.dumps({
"collectionName": collection_name,
"dimension": 512,
"metricType": "COSINE",
"vectorFieldName": "Embedding_Features",
"primaryFieldName": "IDs_Features",
"idType": "Int64",
"indexType": "HNSW",
"primaryKey": {"name": "IDs_Features", "type": "INT64", "primaryKey": True},
"vectorField": {
"name": "Embedding_Features",
"type": "FLOAT_VECTOR",
"primaryKey": False,
},
"indexes": [{
"fieldName": "Embedding_Features",
"indexName": "Embedding_Features",
"metricType": "COSINE",
}],
"auto_index": False,
})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def validate_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/describe"
payload = json.dumps({"collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def drop_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/drop"
payload = json.dumps({"collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def insert_data_into_collection(
collection_name: str,
start_id: int,
n: int,
ids_name: str,
features_name: str,
server_address: str,
):
url = f"{server_address}/v2/vectordb/entities/insert"
data = [{"IDs_Features": start_id + i + 1, "Embedding_Features": list(generate_random_vector())} for i in range(n)]
payload = json.dumps({"data": data, "collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def describe_collection(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/collections/describe"
payload = json.dumps({"collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def describe_index(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/indexes/describe"
payload = json.dumps({"indexName": "Embedding_Features", "collectionName": collection_name})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
def create_index(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/indexes/create"
payload = json.dumps({
"collectionName": collection_name,
"indexParams": [{
"metricType": "COSINE",
"index_type": "HNSW",
"fieldName": "Embedding_Features",
"params": {"M": 128, "efConstruction": 256},
}],
})
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
return response.json()
Когда я попытался создать коллекцию, используя:
create_collection(collection_name=collection_name, server_address=server_address)
Я получил следующее сообщение:
{'code': 0, 'data': {}}
Впоследствии, когда я описывал коллекцию:
describe_collection(collection_name=collection_name, server_address=server_address)
Я получил такой ответ:
{'code': 0,
'data': {'aliases': [],
'autoId': False,
'collectionID': 454176377651168636,
'collectionName': 'collection1',
'consistencyLevel': 'Bounded',
'description': '',
'enableDynamicField': True,
'fields': [{'autoId': False,
'clusteringKey': False,
'description': '',
'id': 100,
'name': 'IDs_Features',
'nullable': False,
'partitionKey': False,
'primaryKey': True,
'type': 'Int64'},
{'autoId': False,
'clusteringKey': False,
'description': '',
'id': 101,
'name': 'Embedding_Features',
'nullable': False,
'params': [{'key': 'dim', 'value': '512'}],
'partitionKey': False,
'primaryKey': False,
'type': 'FloatVector'}],
'functions': None,
'indexes': [{'fieldName': 'Embedding_Features',
'indexName': 'Embedding_Features',
'metricType': 'COSINE'}],
'load': 'LoadStateLoading',
'partitionsNum': 1,
'properties': [],
'shardsNum': 1},
'message': ''}
Когда я описывал индекс коллекции:
describe_index(collection_name=collection_name, server_address=server_address)
Я получил это сообщение:
{'code': 0,
'data': [{'failReason': '',
'fieldName': 'Embedding_Features',
'indexName': 'Embedding_Features',
'indexState': 'Finished',
'indexType': 'AUTOINDEX',
'indexedRows': 0,
'metricType': 'COSINE',
'pendingRows': 0,
'totalRows': 0}]}
Это указывало на то, что для типа индекса было установлено значение [b]AUTOINDEX[/b], несмотря на то, что в моей конфигурации указан [b]HNSW[/b], что вызывало проблемы с индексированием.
p>
После этого я вставил в коллекцию 10 000 строк:
number_vectors = 10000
for i in range(0, number_vectors, 500):
response = insert_data_into_collection(
collection_name=collection_name,
start_id=i,
n=500,
ids_name="IDs_Features",
features_name="Embedding_Features",
server_address=server_address,
)
if response["data"]["insertCount"] == 500:
print(f"Great! inserted ids {i} to {i+500} successfully")
else:
print(f"There are some errors for {i}")
time.sleep(1)
Наконец, когда я попытался создать индекс:
create_index(collection_name=collection_name, server_address=server_address)
Я обнаружил следующую ошибку:
{'code': 65535, 'message': 'only metric type can be passed when use AutoIndex'}
Можно ли мне установить для [b]indexType[/b] значение [b]HNSW[/b] и игнорировать или удалить [b]AutoIndex[/b] по умолчанию > значение?
Путем настройки функции create_index:
def create_index(collection_name: str, server_address: str):
url = f"{server_address}/v2/vectordb/indexes/create"
payload = json.dumps(
{
"collectionName": collection_name,
"indexParams": [
{
"metricType": "COSINE",
"fieldName": "Embedding_Features",
"params": {"M": 128, "efConstruction": 256, "index_type": "HNSW"},
}
],
}
)
# Example: {'metric_type': 'IP', 'index_type': 'HNSW', 'params': {'nlist': 1024, 'efConstruction': 40, 'M': 1024}}
headers = {
"x-api-key": "YOUR_API_KEY",
"Content-Type": "application/json",
}
response = requests.post(url, headers=headers, data=payload)
response = json.loads(response.text)
return response
Я обнаружил следующую ошибку:
{'code': 65535,
'message': 'CreateIndex failed: at most one distinct index is allowed per field'}
Подробнее здесь: [url]https://stackoverflow.com/questions/79281225/cannot-change-the-default-indextype-from-autoindex-to-hnsw-when-creating-an-inde[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия