Skip to content

Hướng dẫn truy cập Database Milvus

Vector Database Milvus

Milvus là một cơ sở dữ liệu mã nguồn mở https://github.com/milvus-io/milvus tối ưu hóa cho quản lý và tìm kiếm dữ liệu vector, được thiết kế đặc biệt cho các ứng dụng trí tuệ nhân tạo và học máy. Với khả năng tìm kiếm gần nhất (nearest neighbor search) hiệu suất cao, Milvus cho phép xử lý và truy vấn dữ liệu vector lớn nhanh chóng và chính xác. Hệ thống này sử dụng các kỹ thuật như FAISS và HNSW để tăng tốc độ truy vấn và đảm bảo khả năng mở rộng linh hoạt, phù hợp với nhu cầu xử lý dữ liệu khổng lồ. Milvus cũng hỗ trợ tích hợp dễ dàng với các framework AI/ML phổ biến như TensorFlow và PyTorch, mang đến giải pháp toàn diện cho các ứng dụng nhận dạng hình ảnh, xử lý ngôn ngữ tự nhiên, và tìm kiếm dựa trên nội dung.

Tiền điều kiện

Cài đặt thư viện Python SDK cho Milvus:

pip install pymilvus
pip install langchain 

Kết nối với Milvus

Code kết nối mẫu (MILVUS_HOST sử dụng localhost (nếu codebase đặt tại server), MILVUS_PORT mặc định là 19530).

from pymilvus import utility
from pymilvus import connections


connections.connect(host=MILVUS_HOST, port=MILVUS_PORT)

Tạo Schema trong Milvus (Tương tự như tạo cấu trúc table của MySQL). Thường thì ta cần hai cột idembedding là đủ, nhưng ta cũng có thể lưu dữ liệu dạng văn bản để tiết kiệm thời gian lookup/mapping với id. Ví dụ sau đây lần lượt tạo cột id, cột text để lưu lại nội dung văn bản gốc, cột embedding lưu lại vector sau khi dùng word embedding, có kích thước size là 384. (Nếu không thì có thể điều chỉnh sang số khác).

from pymilvus import FieldSchema, CollectionSchema, DataType, Collection
# Create collection which includes the id, title, and embedding.
fields = [
    FieldSchema(name='id', dtype=DataType.INT64, is_primary=True, auto_id=True),
    FieldSchema(name='text', dtype=DataType.VARCHAR, max_length=300),  # VARCHARS need a maximum length, so for this example they are set to 300 characters
    FieldSchema(name='embedding', dtype=DataType.FLOAT_VECTOR, dim=384)
]
schema = CollectionSchema(fields=fields)

Tạo collection với schema nêu trên. COLLECTION_NAME là tên của bộ collection (tương tự với database trong CSDL MySQL) hiện tại sử dụng, nếu đổi tên collection thì Milvus sẽ tạo bộ collection mới.

#Tên để phân biệt với các collection khác
COLLECTION_NAME= "LangChainCollection-QA-LLaMA2" 
collection = Collection(name=COLLECTION_NAME, schema=schema)

Tạo mới một Indexing cho collection. Có thể hiểu đơn giản đây là bước cài đặt thuật toán tìm kiếm giữa các vector để Milvus chuẩn bị dữ liệu và làm việc sẵn. Để chọn loại index, xem thêm tại đây: https://milvus.io/docs/v2.0.x/index.md

# Create an IVF_FLAT index for collection
index_params = {
    'metric_type':'L2',
    'index_type':"IVF_FLAT",
    'params':{'nlist': 1536}
}
collection.create_index(field_name="embedding", index_params=index_params)
collection.load()

Kết nối với Milvus (đã có dữ liệu schema): không tạo mới, sử dụng tiếp tục dữ liệu

Không cần tạo lại collection, schema - chỉ cần chọn lại COLLECTION_NAME và load lên.

from pymilvus import Collection, utility
COLLECTION_NAME= "LangChainCollection-QA-LLaMA2" 
collection = Collection(COLLECTION_NAME)      
collection.load()

utility.loading_progress(COLLECTION_NAME)

Sử dụng Milvus bằng API của langchain

Sử dụng langchain, load dữ liệu vào mô hình vector_store của langchain, giả sử dữ liệu đầu vào là một danh sách gồm các đoạn văn bản (lst_str).

vector_store = Milvus.from_texts(
    lst_str,
    embedding=embed_model,
    # metadatas=metadatas,
    collection_name=COLLECTION_NAME,
    drop_old=True,
    connection_args={"host": MILVUS_HOST, "port": MILVUS_PORT}
)

Kiểm tra dữ liệu đã được lưu trữ và đánh chỉ mục bởi Milvus hay chưa bằng cách thử tìm kiếm một câu tương đương trong Milvus. Nếu kiểm tra thấy kết quả trả về tương đồng với câu truy vấn thì ta có thể xác định Milvus đang hoạt động đúng.

query = "Who can get  Basedow's disease?"
docs = vector_store.similarity_search(query)

print(docs)

Kết quả:

[(Document(page_content="How is Basedow's disease transmitted? Basedow is not an infectious disease so it is not transmitted through respiratory or contact. The cause of the disease comes from genetic factors. If either parent has thyrotoxicosis, the child is at risk of having the disease. Therefore, patients and family members can live together with peace of mind.\n", metadata={}), 0.5683361291885376), (Document(page_content="What is Basedow's disease? Basedow's disease is an autoimmune disease of the thyroid gland. Basedow's disease is the most common cause of hyperthyroidism, typical manifestations include: diffuse goiter, proptosis, and pretibial myxedema. The disease is associated with the presence of thyroid-stimulating antibodies.\nWomen get the disease 5-10 times more often than men. The disease can occur at any age but is most common between the ages of 20 and 40.\n", metadata={}), 0.6777578592300415), (Document(page_content="Complications of Basedow's disease Besides common complications related to the eyes and skin, other complications of Basedow's disease include:\nHowever, these complications often develop in people who do not receive proper treatment or have a severe medical condition.\nPeople with Basedow's disease also face the risk of developing other autoimmune conditions including:\nCeliac disease (genetic immune-mediated disease in humans due to gluten intolerance, causing mucosal inflammation and villous atrophy, leading to malabsorption).\nVitiligo (is a loss of skin pigment cells that causes the affected skin area to have a lighter skin color than other skin areas on the body).\nAdditionally, any type of untreated hyperthyroidism can lead to an acute condition called thyrotoxic crisis characterized by dehydration, severe tachycardia or arrhythmia, and heart failure. heart, ventilation disorders and impaired consciousness.\nMaybe you don't know: Can Basedow's disease be cured?\n", metadata={}), 0.7859023809432983), (Document(page_content="People susceptible to Basedow's disease Anyone can get Basedow's disease, including young children and other genders. However, factors that increase the risk of developing Graves' disease include:\nHave another autoimmune disease.\n", metadata={}), 0.813946545124054)]
0.5683361291885376