語彙グラフとベクトル検索の統合

Graph RAG with LangChain and Neo4j

Adam Cowley

Manager, Developer Education at Neo4j

セマンティック検索で関係を活用する

Neo4j で働くのはどんな感じですか?

Review ノードと、text プロパティ「Neo4j is a great place to work」を示すグラフ図

Graph RAG with LangChain and Neo4j

セマンティック検索で関係を活用する

Neo4j で働くのはどんな感じですか?

投稿者はスクリーンネーム @emileifrem の Person ノード

Graph RAG with LangChain and Neo4j

セマンティック検索で関係を活用する

Neo4j で働くのはどんな感じですか?

Emil Eifrem が Company ノード Neo4j に WORKS_AT でつながっている図

Graph RAG with LangChain and Neo4j

テキストから埋め込みへ

 

  • text プロパティからノード埋め込みを作成

Scene が HAS_CHUNK で文字列プロパティを持つ Chunk に接続された図

Graph RAG with LangChain and Neo4j

テキストから埋め込みへ

 

  • text プロパティからノード埋め込みを作成
  • 埋め込みでベクトル検索
  • 関係を文脈に活用

ノードの text プロパティから埋め込みを作成する図

Graph RAG with LangChain and Neo4j

ベクトルストアとしての Neo4j

from langchain_neo4j import Neo4jVector

 

  • Neo4jVector.from_documents(): Document からノードとインデックスを作成
  • Neo4jVector.from_existing_graph(): 既存のラベル/プロパティにインデックスを作成
Graph RAG with LangChain and Neo4j

既存ノードのプロパティを分割(チャンク化)

知識グラフで 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']
Graph RAG with LangChain and Neo4j

既存ノードのプロパティを分割(チャンク化)

  • "\n\n"text を分割
  • ト書きは1行
  • セリフは登場人物名で始まる
    • 続きに発話内容が入る
 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...
Graph RAG with LangChain and Neo4j

既存ノードのプロパティを分割(チャンク化)

# Split text into lines
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:])
Graph RAG with LangChain and Neo4j

既存ノードのプロパティを分割(チャンク化)

# ...Continuing loop over scenes

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"))
Graph RAG with LangChain and Neo4j

既存グラフにベクトル索引を作成

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",
)
Graph RAG with LangChain and Neo4j

LCEL でのベクトル検索

# Create retriever
retriever = store.as_retriever()

# Invoke manually retriever.invoke("What does Romeo think of Juliet?") # [ Document, Document, ... ]
Graph RAG with LangChain and Neo4j

Passons à la pratique !

Graph RAG with LangChain and Neo4j

Preparing Video For Download...