Home Knowledge Graphs for RAG
Post
Cancel

Knowledge Graphs for RAG

참고 자료: https://learn.deeplearning.ai/courses/knowledge-graphs-rag/lesson/1/introduction

What is Knowledge Graph?

A Database that stores information in nodes and relationships

  • provides way to sort and organize data
  • emphasizes the relationship between things
  • uses graph based structure:
    • nodes: represents entity
    • edges: represents relationship between nodes

Fundamentals

Nodes and Edges

Representation: (Person) - [Knows] - (Person)

Nodes are “in” relationship, relation with properties

Representation: (Person) - [TEACHES] → (Course) ← [INTRODUCES] - (Person)

  • Like node, Edges also has key/value structure

Knowledge Graph Overview:

  • Knowledge Graph: Stores information in nodes and relationships
  • Nodes and Relationships: Both can have properties
  • Nodes: Can be labeled to group them together
  • Relationships: Always have a type and direction

Querying Knowledge Graphs

  • Knowledge Graph used: Neo4jGraph
1
2
3
4
5
from langchain_community.graphs import Neo4jGraph

kg = Neo4jGraph(
    url=NEO4J_URI, username=NEO4J_USERNAME, password=NEO4J_PASSWORD, database=NEO4J_DATABASE
)

(Person) - [ACTED_IN] → (Movie)

Node properties

Edges-Relationships between a Person and a Movie

  • enables description of perplex situations when a person acted in AND directed a movie

Cypher

  • Neo4j’s query language
  • uses pattern matching to find thins inside of the grass

Basic

1
2
3
4
5
# number of all the nodes
cypher = """
  MATCH (n) 
  RETURN count(n)
  """
1
2
result = kg.query(cypher)
result
1
[{'count(n)': 171}]

Alias

1
2
3
4
5
6
cypher = """
  MATCH (n) 
  RETURN count(n) AS numberOfNodes
  """
result = kg.query(cypher)
result
1
[{'numberOfNodes': 171}]
1
print(f"There are {result[0]['numberOfNodes']} nodes in this graph.")
1
There are 171 nodes in this graph.

Match

1
2
3
4
5
cypher = """
  MATCH (n:Movie) 
  RETURN count(n) AS numberOfMovies
  """
kg.query(cypher)
1
[{'numberOfMovies': 38}]
1
2
3
4
5
cypher = """
  MATCH (tom:Person {name:"Tom Hanks"}) 
  RETURN tom
  """
kg.query(cypher)
1
[{'tom': {'born': 1956, 'name': 'Tom Hanks'}}]
This post is licensed under CC BY 4.0 by the author.

Chainlit

Podly Github Readme