문서 스토어 (Document Store)
문서 스토어 (Document Store)
Document Store는 데이터를 저장하고, 쿼리 시점에 Retriever에게 그 데이터를 내어주는 데이터베이스라고 생각하면 돼요. 파이프라인에서 Document Store를 어떻게 쓰는지, 또는 나만의 Document Store를 어떻게 만드는지를 알아볼게요.
Document Store는 문서(document)를 저장하는 객체예요. Haystack에서 Document Store는 컴포넌트와는 달라요. run() 메서드가 없거든요. 데이터베이스에 대한 인터페이스라고 보면 돼요 — 정보를 넣어 두거나, 그 안을 들춰볼 수 있죠. 다시 말해 Document Store는 파이프라인의 한 조각이 아니라, 파이프라인을 이루는 컴포넌트들이 접근해서 상호작용할 수 있는 도구예요.
Retriever와 함께 쓰기
Haystack에서 Document Store를 가장 흔하게 쓰는 방법은 Retriever로 문서를 가져오는 거예요. Document Store마다 특정 기술을 최대한 활용할 수 있도록 대응하는 Retriever가 있는 경우가 많죠. 자세한 내용은 Retriever 문서에서 볼 수 있어요.
어떤 Document Store를 고를까?
다양한 종류의 Document Store와, 각각의 장점과 단점을 알아보려면 Choosing a Document Store 페이지를 확인해 보세요.
Document Store는 프로토콜의 일부로 다음 메서드들을 사용하도록 설계되어 있어요.
count_documents는 해당 스토어에 저장된 문서 수를 정수로 반환해요.filter_documents는 주어진 필터와 일치하는 문서 목록을 반환해요.write_documents는 해당 스토어에 문서를 쓰거나 덮어쓰고, 작성된 문서 수를 정수로 반환해요.delete_documents는 주어진document_ids에 해당하는 모든 문서를 Document Store에서 삭제해요.
파이프라인에서 Document Store를 쓰려면 먼저 초기화해야 해요. 각 Document Store의 설치 및 초기화 방법은 왼쪽 내비게이션 패널의 "Document Stores" 섹션에서 확인할 수 있어요.
데이터를 Document Store에 쓰기 전에, 그 데이터를 Document 객체 — 메타데이터와 문서 ID를 함께 담은 객체 — 로 변환해야 해요.
ID 필드는 필수예요. 그래서 직접 특정 ID를 정하지 않으면, Haystack이 문서의 정보에 기반해 고유한 ID를 만들고 자동으로 할당해 줘요. 그런데 주의할 점이 하나 있어요. Haystack은 문서 내용을 바탕으로 ID를 만들기 때문에, 완전히 똑같은 두 문서는 같은 ID를 가질 수 있어요. 문서를 업데이트할 때 이 점을 유의하세요 — ID는 자동으로 업데이트되지 않거든요.
document_store = ChromaDocumentStore()
documents = [
Document(
meta={"name": DOCUMENT_NAME}, id="document_unique_id", content="this is content"
),
...,
]
document_store.write_documents(documents)
InMemoryDocumentStore에 문서를 쓰려면 .write_documents() 함수를 호출하면 돼요.
document_store.write_documents(
[
Document(content="My name is Jean and I live in Paris."),
Document(content="My name is Mark and I live in Berlin."),
Document(content="My name is Giorgio and I live in Rome."),
],
)
DocumentWriter
파이프라인에서 Document Store에 문서를 쓰려면 DocumentWriter 컴포넌트를 써요. 자세한 내용은 DocumentWriter 문서를 확인하세요.
DuplicatePolicy는 DocumentStore에서 같은 ID를 가진 문서를 어떻게 처리할지 정하는 옵션을 정의한 클래스예요. 네 가지 값이 있어요.
- NONE:
DocumentWriter가 쓰는 기본값이에요.DocumentStore설정에 맡겨서, 각 스토어가 자체 정책을 적용해요. - OVERWRITE: 같은 ID의 문서가
DocumentStore에 이미 있으면 새 문서로 덮어써요. - SKIP: 같은 ID의 문서가 이미 있으면 새 문서는 건너뛰고 추가하지 않아요.
- FAIL: 같은 ID의 문서가 이미 있으면 오류를 발생시켜요. 중복 문서가 추가되는 것을 막아 주죠.
기존 문서를 건너뛰도록 정책을 적용하는 예시는 이렇게 생겼어요.
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.writers import DocumentWriter
from haystack.document_stores.types import DuplicatePolicy
document_store = InMemoryDocumentStore()
document_writer = DocumentWriter(
document_store=document_store,
policy=DuplicatePolicy.SKIP,
)
커스텀 Document Store를 직접 만든다면, 네 가지 필수 메서드 count_documents, filter_documents, write_documents, delete_documents를 포함한 프로토콜을 구현해야 해요.
init 함수는 선택한 데이터베이스나 벡터 스토어의 세부 사항을 모두 나타내야 하며, 우리는 특정 Document Store를 최대한 활용하기 위해 대응하는 커스텀 Retriever도 함께 마련할 것을 권장해요.
더 자세한 내용은 Creating Custom Document Stores 페이지를 참고하세요.