어휘 그래프와 벡터 검색 결합

LangChain과 Neo4j로 배우는 Graph RAG

Adam Cowley

Manager, Developer Education at Neo4j

의미 검색에서 관계 활용하기

Neo4j에서 일하는 것은 어떤가요?

Review 노드와 "Neo4j is a great place to work" 텍스트 속성이 있는 그래프 다이어그램

LangChain과 Neo4j로 배우는 Graph RAG

의미 검색에서 관계 활용하기

Neo4j에서 일하는 것은 어떤가요?

화면 이름 @emileifrem 인 Person이 리뷰를 게시함

LangChain과 Neo4j로 배우는 Graph RAG

의미 검색에서 관계 활용하기

Neo4j에서 일하는 것은 어떤가요?

Emil Eifrem이 Neo4j라는 Company 노드와 WORKS_AT 관계를 가짐

LangChain과 Neo4j로 배우는 Graph RAG

Text 속성을 임베딩으로

 

  • text 속성으로 노드 임베딩 생성

문자열 속성이 있는 Chunk 노드로 HAS_CHUNK 관계가 연결된 scene

LangChain과 Neo4j로 배우는 Graph RAG

Text 속성을 임베딩으로

 

  • text 속성으로 노드 임베딩 생성
  • 임베딩으로 벡터 검색
  • 관계를 문맥에 활용

노드의 text 속성으로 임베딩을 생성함

LangChain과 Neo4j로 배우는 Graph RAG

벡터 스토어로서의 Neo4j

from langchain_neo4j import Neo4jVector

 

  • Neo4jVector.from_documents(): Document로 노드와 인덱스 생성
  • Neo4jVector.from_existing_graph(): 기존 라벨·속성 조합에 인덱스 생성
LangChain과 Neo4j로 배우는 Graph RAG

기존 노드 속성 청킹하기

Act 노드에서 Scene 노드로 가는 HAS_SCENE 관계를 강조한 지식 그래프 다이어그램

res = graph.query("""

MATCH (s:Scene)
WHERE NOT {(s)-[:HAS_LINE]->()}
RETURN s.id AS id, s.text AS text
""")
for scene in res: # Create chunks from scene['text']
LangChain과 Neo4j로 배우는 Graph RAG

기존 노드 속성 청킹하기

  • text"\n\n"로 분할
  • 지시문은 한 줄
  • 대사는 인물명으로 시작
    • 다음 줄에 대사 내용
 Enter Sampson and Gregory armed with swords..

SAMPSON.
Gregory, on my word...
GREGORY. No, for then we should...
SAMPSON. I mean, if we be in choler, we'll draw...
LangChain과 Neo4j로 배우는 Graph RAG

기존 노드 속성 청킹하기

# 텍스트를 줄로 분할
lines = [
    line.strip() for line in text.split("\n\n")

if "\n" in line
]
for line in lines: parts = line.split("\n")
character = parts[0]
text = "\n".join(parts[1:])
LangChain과 Neo4j로 배우는 Graph RAG

기존 노드 속성 청킹하기

# ...씬에 대한 루프 계속

line_node = Node(type="Line", id=f"{scene.id}-line-{i}", properties={})
character_node = Node(type="Character", id=character, properties={})


# (:Scene)-[:HAS_LINE]->(:Line) graph_document.relationships.append( Relationship(source=scene, target=line_node, type="HAS_LINE"))
# (:Line)-[:SPOKEN_BY]->(:Character) graph_document.relationships.append(Relationship( source=line_node, target=characters[character], type="SPOKEN_BY"))
LangChain과 Neo4j로 배우는 Graph RAG

기존 그래프에 벡터 인덱스 생성

from langchain.embeddings import init_embeddings
store = Neo4jVector.from_existing_graph(

init_embeddings("openai:text-embedding-3-small"),
url=NEO4J_URI, username=NEO4J_USERNAME, password=NEO4J_PASSWORD,
node_label="Line",
text_node_properties=["text"],
embedding_node_property="embedding",
index_name="lines",
)
LangChain과 Neo4j로 배우는 Graph RAG

LCEL로 벡터 검색

# 리트리버 생성
retriever = store.as_retriever()

# 수동 호출 retriever.invoke("What does Romeo think of Juliet?") # [ Document, Document, ... ]
LangChain과 Neo4j로 배우는 Graph RAG

연습해 봅시다!

LangChain과 Neo4j로 배우는 Graph RAG

Preparing Video For Download...