GraphRAG와 Neo4j 연결 레이어층 만들기

jiyoon·2024년 9월 2일

KG 지식그래프

목록 보기
3/6

MS사의 GraphRAG와 Neo4j를 직접적으로 연결하는 공식적인 방법은 현재 없다. 그러나 두 시스템을 통합하여 자연스럽게 작동하게 만들 수 있는 몇 가지 방법을 알려주겠다:

1. API 기반 통합

GraphRAG는 REST API를 통해 접근할 수 있다. Neo4j 또한 HTTP API를 제공하기 때문에, 이를 활용하여 중간 레이어를 만들어 두 시스템을 연결할 수 있다.

from flask import Flask, request, jsonify
import requests
import py2neo

app = Flask(__name__)

# GraphRAG API 엔드포인트
GRAPHRAG_API = "http://graphrag-endpoint/api"

# Neo4j 연결
graph = py2neo.Graph("bolt://localhost:7687", auth=("neo4j", "password"))

@app.route('/query', methods=['POST'])
def process_query():
    query = request.json['query']
    
    # GraphRAG에 쿼리 전송
    graphrag_response = requests.post(f"{GRAPHRAG_API}/query", json={'query': query})
    graphrag_result = graphrag_response.json()
    
    # GraphRAG 결과를 Neo4j에 저장
    for item in graphrag_result['items']:
        graph.run("CREATE (n:GraphRAGResult {content: $content})", content=item['content'])
    
    # Neo4j에서 추가 정보 검색
    neo4j_result = graph.run("MATCH (n:GraphRAGResult) RETURN n").data()
    
    # 결과 통합
    combined_result = {
        'graphrag': graphrag_result,
        'neo4j': neo4j_result
    }
    
    return jsonify(combined_result)

if __name__ == '__main__':
    app.run(debug=True)



2. 이벤트 기반 통합

Apache Kafka나 RabbitMQ와 같은 메시지 큐 시스템을 사용하여 GraphRAG와 Neo4j 사이의 이벤트 기반 통신을 구현할 수 있다.

from kafka import KafkaConsumer, KafkaProducer
from py2neo import Graph

# Kafka 설정
consumer = KafkaConsumer('graphrag_results', bootstrap_servers=['localhost:9092'])
producer = KafkaProducer(bootstrap_servers=['localhost:9092'])

# Neo4j 연결
graph = Graph("bolt://localhost:7687", auth=("neo4j", "password"))

for message in consumer:
    graphrag_result = message.value.decode()
    
    # GraphRAG 결과를 Neo4j에 저장
    graph.run("CREATE (n:GraphRAGResult {content: $content})", content=graphrag_result)
    
    # Neo4j에서 추가 정보 검색
    neo4j_result = graph.run("MATCH (n:GraphRAGResult) RETURN n").data()
    
    # 결과를 다른 Kafka 토픽으로 전송
    producer.send('combined_results', str(neo4j_result).encode())



3. 데이터베이스 동기화

GraphRAG의 결과를 주기적으로 Neo4j로 동기화하는 스크립트를 만들어 실행할 수 있다.

import schedule
import time
import requests
from py2neo import Graph

def sync_graphrag_to_neo4j():
    # GraphRAG API 엔드포인트
    GRAPHRAG_API = "http://graphrag-endpoint/api"
    
    # Neo4j 연결
    graph = Graph("bolt://localhost:7687", auth=("neo4j", "password"))
    
    # GraphRAG에서 최신 결과 가져오기
    response = requests.get(f"{GRAPHRAG_API}/latest_results")
    graphrag_results = response.json()
    
    # Neo4j에 결과 저장 또는 업데이트
    for result in graphrag_results:
        graph.run("""
        MERGE (n:GraphRAGResult {id: $id})
        SET n.content = $content, n.updated_at = datetime()
        """, id=result['id'], content=result['content'])

# 매 시간마다 동기화 실행
schedule.every().hour.do(sync_graphrag_to_neo4j)

while True:
    schedule.run_pending()
    time.sleep(1)

이러한 방법들을 통해 GraphRAG와 Neo4j를 더 자연스럽게 연결할 수 있다. 선택한 방법은 사용 사례, 데이터 볼륨, 실시간 요구 사항 등에 따라 달라질 수 있다. 각 방법은 장단점이 있으므로, 프로젝트의 요구 사항에 가장 적합한 접근 방식을 선택하시기 바란다.

profile
주니어 개발자

0개의 댓글