from milvus import Milvus, DataType
# Specify the hostname and port to connect to the Milvus server
_HOST = '127.0.0.1'
_PORT = '19530'
# Create a Milvus client instance
client = Milvus(_HOST, _PORT)
# Define a collection name and its schema
collection_name = 'demo_collection'
dim = 128 # Dimension of the vector
collection_schema = {
"fields": [
{
"name": "vec_field",
"type": DataType.FLOAT_VECTOR,
"params": {"dim": dim},
}
],
"segment_row_limit": 4096,
"auto_id": True
}
# Create a collection
client.create_collection(collection_name, collection_schema)
# Insert data into the collection
# Suppose we have 20 vectors with the specified dimension
vectors = [[i / float(dim) for i in range(dim)] for _ in range(20)]
insert_param = {
"collection_name": collection_name,
"records": vectors,
}
status, ids = client.insert(**insert_param)
client.flush([collection_name]) # Flush data to disk for persistence
# Create an index for the collection for efficient search
index_param = {
"collection_name": collection_name,
"field_name": "vec_field",
"index_type": "IVF_FLAT",
"params": {"nlist": 16384},
}
client.create_index(**index_param)
# Search for similar vectors
search_param = {
"collection_name": collection_name,
"query_records": vectors[0:1], # Taking the first vector as query example
"params": {
"metric_type": "L2",
"params": {"nprobe": 10},
},
"top_k": 10,
}
status, results = client.search(**search_param)
# Process search results, if status OK
if status.OK():
for result in results[0]:
print(f"ID: {result.id}, distance: {result.distance}")
# Delete the collection when it's no longer needed
client.drop_collection(collection_name)
# Close the client connection
client.close()