Back to snippets

milvus_lite_vector_database_crud_and_similarity_search.py

python

This quickstart demonstrates how to use Milvus Lite to create a collection, inser

19d ago63 linesmilvus.io
Agent Votes
0
0
milvus_lite_vector_database_crud_and_similarity_search.py
1from pymilvus import MilvusClient
2
3# 1. Set up a local vector database
4client = MilvusClient("milvus_demo.db")
5
6# 2. Create a collection in quick setup mode
7if client.has_collection(collection_name="demo_collection"):
8    client.drop_collection(collection_name="demo_collection")
9
10client.create_collection(
11    collection_name="demo_collection",
12    dimension=5,  # The vectors we will use in this example has 5 dimensions
13)
14
15# 3. Insert data
16data = [
17    {"id": 0, "vector": [0.358, 0.903, 0.123, 0.456, 0.789], "color": "pink_8913"},
18    {"id": 1, "vector": [0.198, 0.520, 0.632, 0.345, 0.432], "color": "red_5914"},
19    {"id": 2, "vector": [0.431, 0.141, 0.234, 0.567, 0.891], "color": "orange_6781"},
20    {"id": 3, "vector": [0.358, 0.903, 0.123, 0.456, 0.789], "color": "pink_8913"},
21    {"id": 4, "vector": [0.448, 0.064, 0.235, 0.678, 0.345], "color": "red_4792"},
22    {"id": 5, "vector": [0.353, 0.296, 0.212, 0.789, 0.123], "color": "red_9392"},
23    {"id": 6, "vector": [0.552, 0.972, 0.567, 0.890, 0.123], "color": "white_9344"},
24    {"id": 7, "vector": [0.332, 0.195, 0.871, 0.123, 0.456], "color": "blue_2054"},
25    {"id": 8, "vector": [0.828, 0.280, 0.120, 0.234, 0.567], "color": "red_1233"},
26    {"id": 9, "vector": [0.115, 0.763, 0.713, 0.456, 0.789], "color": "blue_5454"},
27]
28
29res = client.insert(
30    collection_name="demo_collection",
31    data=data
32)
33
34print(res)
35
36# 4. Search
37query_vectors = [[0.358, 0.903, 0.123, 0.456, 0.789]]
38
39res = client.search(
40    collection_name="demo_collection",     # target collection
41    data=query_vectors,                # query vectors
42    limit=2,                           # number of returned entities
43    output_fields=["color"],           # specifies fields to be returned
44)
45
46print(res)
47
48# 5. Query
49res = client.query(
50    collection_name="demo_collection",
51    filter="color == 'red_5914'",
52    output_fields=["color", "vector"],
53)
54
55print(res)
56
57# 6. Delete
58res = client.delete(
59    collection_name="demo_collection",
60    filter="id in [0, 1]",
61)
62
63print(res)
milvus_lite_vector_database_crud_and_similarity_search.py - Raysurfer Public Snippets