AI

[AI] Milvus 사용방법

usingsystem 2025. 6. 25. 09:37
728x90

1. Milvus 다운로드

Milvus는 vectordb로 리눅스 환경에서 동작한다.

https://milvus.io/docs/ko/install_standalone-docker-compose.md

 

Docker Compose로 Milvus 실행하기(Linux) | Milvus 문서화

Docker Compose를 사용하여 Milvus를 독립형으로 설치하는 방법을 알아보세요. | v2.6.x

milvus.io

 

Docker Compose를 다운로드하기 위해 https://github.com/milvus-io/milvus/releases/ 에 접속해서 원하는 버전의 Docker Compose 파일을 다운로드한다.

docker-compose.yaml은 Milvus를 실행시키기 위해 필요한 3개의 서비스 컨테이너 서비스를 포함한다. (etcd, minio, milvus-standalone)

# docker-compose.yaml
version: '3.5'

services:
  etcd:
    container_name: milvus-etcd
    image: quay.io/coreos/etcd:v3.5.5
    environment:
      - ETCD_AUTO_COMPACTION_MODE=revision
      - ETCD_AUTO_COMPACTION_RETENTION=1000
      - ETCD_QUOTA_BACKEND_BYTES=4294967296
      - ETCD_SNAPSHOT_COUNT=50000
    volumes:
      - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/etcd:/etcd
    command: etcd -advertise-client-urls=http://127.0.0.1:2379 -listen-client-urls http://0.0.0.0:2379 --data-dir /etcd
    healthcheck:
      test: ["CMD", "etcdctl", "endpoint", "health"]
      interval: 30s
      timeout: 20s
      retries: 3

  minio:
    container_name: milvus-minio
    image: minio/minio:RELEASE.2023-03-20T20-16-18Z
    environment:
      MINIO_ACCESS_KEY: minioadmin
      MINIO_SECRET_KEY: minioadmin
    ports:
      - "9001:9001"
      - "9000:9000"
    volumes:
      - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/minio:/minio_data
    command: minio server /minio_data --console-address ":9001"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
      interval: 30s
      timeout: 20s
      retries: 3

  standalone:
    container_name: milvus-standalone
    image: milvusdb/milvus:v2.3.1
    command: ["milvus", "run", "standalone"]
    environment:
      ETCD_ENDPOINTS: etcd:2379
      MINIO_ADDRESS: minio:9000
    volumes:
      - ${DOCKER_VOLUME_DIRECTORY:-.}/volumes/milvus:/var/lib/milvus
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:9091/healthz"]
      interval: 30s
      start_period: 90s
      timeout: 20s
      retries: 3
    ports:
      - "19530:19530"
      - "9091:9091"
    depends_on:
      - "etcd"
      - "minio"

networks:
  default:
    name: milvus

2. Milvus 실행

아래 명령어로 다운로드한. yml 파일을 실행시킨다. (다운로드한 compose가 존재하는 폴더 경로에서 실행해야 함.)

docker-compose -f milvus-standalone-docker-compose.yml up -d

이후 docker compose 명령어를 통해 각 컨테이너 서비스들의 실행결과를 확인할 수 있습니다.

 

컴포즈가 정상적으로 실행 됐다면 http://localhost:9091/webui/를 사용하여 webui로 db, collection 등을 확인할 수 있다.

3. 사용방법

  • pip install
!pip install pymilvus
  • 사용하는 package
from pymilvus import Collection, MilvusException, connections, db, utility
from langchain_milvus import  Milvus
  • db연결
connections.connect(host="localhost", port=19530)
  • db 정보 명령어
db.using_database("사용할 db이름")
collection = Collection("컬랙션 이름")  # 존재하는 컬렉션명
collection.load() # 컬렉션 load

connections.has_connection('db 이름') # db 존재 connection 확인

# 현재 DB 설정 확인
print(db.list_database()) # 모든 db명 조회
print(connections.list_connections())
print(utility.list_collections()) # 현재 연결된 db 컬렉션 목록
  • db 생성
db_name = "디비이름"
try:
    existing_databases = db.list_database()
    if db_name in existing_databases:
        print(f"Database '{db_name}' already exists.")

        # Use the database context
        db.using_database(db_name)

        # Drop all collections in the database
        collections = utility.list_collections()
        for collection_name in collections:
            collection = Collection(name=collection_name)
            collection.drop()
            print(f"Collection '{collection_name}' has been dropped.")

        db.drop_database(db_name)
        print(f"Database '{db_name}' has been deleted.")
    else:
        print(f"Database '{db_name}' does not exist.")
        database = db.create_database(db_name)
        print(f"Database '{db_name}' created successfully.")
except MilvusException as e:
    print(f"An error occurred: {e}")
  • collection 삭제
#특정 collection삭제
if utility.has_collection("langchain_example"):
     utility.drop_collection("langchain_example")

#collection 모두삭제
collections = utility.list_collections()
for c in collections:
    utility.drop_collection(c)
  • collection 생성과 문서저장
URI = "http://localhost:19530"
vector_store_saved = Milvus.from_documents(
    docs, # 저장할 문서
    embeddings, # 임베딩 모델델
    collection_name="collection 이름",
    connection_args={"uri": URI, "token": "root:Milvus", "db_name": "디비이름"},
    drop_old=False,
)
  • 컬렉션 load
URI = "http://localhost:19530"
vectorstore = Milvus(
    embedding_function=embeddings,
    collection_name="collection 이름",
    connection_args={"uri": URI, "token": "root:Milvus", "db_name": "db이름"},
    index_params={"index_type": "FLAT", "metric_type": "L2"},
    consistency_level="Strong",
    drop_old=False,
)
  • load 한 collection을 retriever
retriever = vectorstore.as_retriever(search_type="mmr", search_kwargs={"k": 10})
retriever.invoke("검색할 내용")
  • collection 조건 select 
# 전체 데이터 조회 (limit 필수)
results = collections['collection 이름'].query(
    expr='조건컬럼 == "찾을 컬럼 내용"',  # ''로하면 조건 없이 모두 조회
    output_fields=["", ""],  # 조회할 필드명
    limit=1000  # 필수: 한번에 가져올 최대 레코드 수
)

# 출력
for r in results:
    print(r)
728x90