문서 관리
문서 관리 (Document Management)
대부분의 LlamaIndex 인덱스 구조는 삽입(insertion), 삭제(deletion), 업데이트(update), 새로고침(refresh) 연산을 지원해요.
출처: 문서
본문
삽입 (Insertion)
인덱스를 처음 만든 후에는 어떤 인덱스 데이터 구조에도 새 Document를 "삽입"할 수 있어요. 이 문서는 노드로 분해되어 인덱스로 들어가요.
삽입의 기본 메커니즘은 인덱스 구조에 따라 달라요. 예를 들어 서머리(summary) 인덱스의 경우 새 Document가 리스트에 추가 노드로 삽입되고, 벡터 스토어 인덱스의 경우 새 Document(와 임베딩)가 기본 문서/임베딩 스토어에 삽입돼요.
코드 스니펫 예시:
from llama_index.core import SummaryIndex, Document
index = SummaryIndex([])
text_chunks = ["text_chunk_1", "text_chunk_2", "text_chunk_3"]
doc_chunks = []
for i, text in enumerate(text_chunks):
doc = Document(text=text, id_=f"doc_id_{i}")
doc_chunks.append(doc)
# insert
for doc_chunk in doc_chunks:
index.insert(doc_chunk)
삭제 (Deletion)
대부분의 인덱스 데이터 구조에서 document_id를 지정해 Document를 "삭제"할 수 있어요. (참고: 트리 인덱스는 현재 삭제를 지원하지 않아요). 해당 문서에 대응하는 모든 노드가 삭제돼요.
index.delete_ref_doc("doc_id_0", delete_from_docstore=True)
동일한 docstore를 사용해 여러 인덱스가 노드를 공유하는 경우 delete_from_docstore는 기본값이 False예요. 하지만 이 값이 False여도 쿼리 가능한 노드를 추적하는 인덱스의 index_struct에서 이 노드들이 삭제되므로, 쿼리에는 사용되지 않아요.
업데이트 (Update)
Document가 이미 인덱스 안에 있다면 동일한 doc id_로 Document를 "업데이트"할 수 있어요(예: 문서의 정보가 변경된 경우).
# NOTE: the document has a `doc_id` specified
doc_chunks[0].text = "Brand new document text"
index.update_ref_doc(doc_chunks[0])
새로고침 (Refresh)
데이터를 로딩할 때 각 문서의 id_를 설정했다면 인덱스를 자동으로 새로고침할 수도 있어요.
refresh() 함수는 동일한 doc id_를 가지면서 텍스트 내용이 다른 문서만 업데이트해요. 인덱스에 전혀 없는 문서들도 새로 삽입돼요.
또한 refresh()는 입력 중 어떤 문서가 인덱스에서 새로고침되었는지를 나타내는 불리언 리스트를 반환해요.
# modify first document, with the same doc_id
doc_chunks[0] = Document(text="Super new document text", id_="doc_id_0")
# add a new document
doc_chunks.append(
Document(
text="This isn't in the index yet, but it will be soon!",
id_="doc_id_3",
)
)
# refresh the index
refreshed_docs = index.refresh_ref_docs(doc_chunks)
# refreshed_docs[0] and refreshed_docs[-1] should be true
여기서도 docstore에서 문서가 삭제되도록 몇 가지 추가 kwargs를 전달했어요. 물론 이것은 선택사항이에요.
refresh()의 출력을 print()하면 어떤 입력 문서가 새로고침되었는지 볼 수 있어요:
print(refreshed_docs)
# > [True, False, False, True]
이 기능은 새로운 정보가 지속적으로 업데이트되는 디렉토리를 읽을 때 가장 유용해요.
SimpleDirectoryReader를 사용할 때 doc id_를 자동으로 설정하려면 filename_as_id 플래그를 설정하면 돼요. Documents 커스터마이징에 대해 더 알아볼 수 있어요.
문서 추적 (Document Tracking)
docstore를 사용하는 인덱스(즉, 대부분의 벡터 스토어 통합을 제외한 모든 인덱스)에서는 docstore에 어떤 문서를 삽입했는지도 확인할 수 있어요.
print(index.ref_doc_info)
"""
> {'doc_id_1': RefDocInfo(node_ids=['071a66a8-3c47-49ad-84fa-7010c6277479'], metadata={}),
'doc_id_2': RefDocInfo(node_ids=['9563e84b-f934-41c3-acfd-22e88492c869'], metadata={}),
'doc_id_0': RefDocInfo(node_ids=['b53e6c2f-16f7-4024-af4c-42890e945f36'], metadata={}),
'doc_id_3': RefDocInfo(node_ids=['6bedb29f-15db-4c7c-9885-7490e10aa33f'], metadata={})}
"""
출력의 각 항목은 들어온 doc id_를 키로, 그리고 그들이 분할된 노드들의 연관 node_ids를 보여줘요.
마지막으로 각 입력 문서의 원본 metadata 딕셔너리도 추적돼요. metadata 속성에 대해 더 알아보려면 Documents 커스터마이징을 읽어보세요.