Chroma 빠른 시작 — 첫 컬렉션 만들기

Chroma 빠른 시작 — 첫 컬렉션 만들기

Chroma의 첫 걸음은 간단해요. 패키지를 설치하고 클라이언트를 만든 뒤 컬렉션을 하나 생성하면, 문서를 넣고 검색하는 전체 흐름이 끝납니다.

출처: https://docs.trychroma.com/docs/overview/getting-started

설치와 클라이언트

chromadb만 설치하면 끝입니다. 이 예시는 인메모리 클라이언트로, 프로그램이 끝나면 저장된 데이터가 사라져요. 편하게 테스트할 때 적합합니다.

import chromadb
chroma_client = chromadb.Client()

컬렉션 만들고 문서 넣기

컬렉션은 임베딩·문서·메타데이터를 함께 보관하는 저장 단위예요. 문서 아이디는 고유한 문자열이어야 합니다.

collection = chroma_client.create_collection(name="my_collection")

collection.add(
    ids=["id1", "id2"],
    documents=[
        "This is a document about pineapple",
        "This is a document about oranges"
    ]
)

질의하기

질의 문장을 넘기면 n_results만큼 가장 유사한 결과를 돌려줍니다. 값이 없으면 기본적으로 10건을 반환해요.

results = collection.query(
    query_texts=["This is a query document about hawaii"], # Chroma will embed this for you
    n_results=2 # how many results to return
)
print(results)

보시면 파인애플 문서가 하와이 질의와 의미적으로 가장 가깝다고 나옵니다.

{
  'documents': [[
      'This is a document about pineapple',
      'This is a document about oranges'
  ]],
  'ids': [['id1', 'id2']],
  'distances': [[1.0404009819030762, 1.243080496788025]],
  'uris': None,
  'data': None,
  'metadatas': [[None, None]],
  'embeddings': None,
}

직접 해보기

프로그램을 반복 실행해도 중복없이 쓸려면 create_collection 대신 get_or_create_collection을, add 대신 upsert를 쓰면 돼요. 처음으로 컬렉션을 만들고, 이후에는 기존 데이터를 갱신하는 방식이죠.

import chromadb
chroma_client = chromadb.Client()

# switch `create_collection` to `get_or_create_collection` to avoid creating a new collection every time
collection = chroma_client.get_or_create_collection(name="my_collection")

# switch `add` to `upsert` to avoid adding the same documents every time
collection.upsert(
    documents=[
        "This is a document about pineapple",
        "This is a document about oranges"
    ],
    ids=["id1", "id2"]
)

results = collection.query(
    query_texts=["This is a query document about florida"], # Chroma will embed this for you
    n_results=2 # how many results to return
)

print(results)

인메모리 클라이언트 대신 데이터를 오래 보관하고 싶으면 영속 클라이언트(persistent client) 를 쓰거나 Chroma를 client-server 모드로 띄우면 됩니다.

더 알아보기