프로그램으로 CRUD 작업 수행
애플리케이션에서 Cypher 쿼리를 실행하여 그래프 데이터를 동적으로 생성, 조회, 업데이트 및 삭제합니다.
프로그램으로 CRUD 작업 수행은(는) CoddyKit의 무료 Neo4j Graph Database Fundamentals 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Neo4j Graph Database Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Neo4j Graph Database Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
CRUD from Your Application
When building applications, you'll often need to interact with your Neo4j database programmatically. This means writing code that sends Cypher queries to create, read, update, and delete data.
These fundamental operations are often referred to as CRUD:
- Create: Adding new data (nodes, relationships).
- Read: Retrieving existing data.
- Update: Modifying existing data.
- Delete: Removing data.
Connecting to Neo4j (Review)
Before performing any CRUD operations, your application needs to connect to the Neo4j database. As we learned previously, the official Neo4j Python Driver simplifies this.
You'll use a GraphDatabase.driver object to manage connections and then create a session to execute queries.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password") # Use your credentials
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
# Your Cypher queries will go here
print("Connected to Neo4j!")
driver.close()
if __name__ == "__main__":
main()Creating New Nodes
To add new entities to your graph, you use the Cypher CREATE clause. Programmatically, you pass your Cypher query string and any parameters to the session.run() method.
Using parameters (like $name, $age) is crucial for security and prevents Cypher injection.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
query = (
"CREATE (p:Person {name: $name, age: $age}) "
"RETURN p.name AS name"
)
result = session.run(query, name="Charlie", age=25)
print(f"Created: {result.single()['name']}")
driver.close()
if __name__ == "__main__":
main()Creating Relationships
Relationships connect nodes and are essential for graph structures. To create a relationship, you first need to identify the nodes you want to connect, usually with MATCH, and then use CREATE.
The example connects 'Charlie' (created above) to 'Alice' (we'll ensure she exists for this demo).
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
# Ensure Alice exists for the demo
session.run("MERGE (:Person {name: 'Alice', age: 30})")
query = (
"MATCH (a:Person {name: $name1}), "
"(b:Person {name: $name2}) "
"CREATE (a)-[r:KNOWS]->(b) "
"RETURN type(r) AS relType"
)
result = session.run(query, name1="Charlie", name2="Alice")
print(f"Relationship created: {result.single()['relType']}")
driver.close()
if __name__ == "__main__":
main()Reading Nodes (MATCH & RETURN)
Retrieving data is done using the MATCH clause to find patterns and RETURN to specify what data you want back. You can fetch entire nodes or specific properties.
The session.run() method returns a result object you can iterate over.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
query = "MATCH (p:Person) RETURN p.name AS name, p.age AS age"
print("All People:")
for record in session.run(query):
print(f"- {record['name']} ({record['age']} years old)")
driver.close()
if __name__ == "__main__":
main()Reading Connected Patterns
Graph databases excel at querying connected data. You can match complex patterns of nodes and relationships and retrieve specific parts of that pattern.
This example finds people who know 'Alice' and returns their names.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
query = (
"MATCH (p:Person)-[:KNOWS]->(a:Person {name: $targetName}) "
"RETURN p.name AS knowsAlice"
)
result = session.run(query, targetName="Alice")
print("People who know Alice:")
for record in result:
print(f"- {record['knowsAlice']}")
driver.close()
if __name__ == "__main__":
main()Updating Node Properties
To modify existing data, you use MATCH to find the node(s) or relationship(s) and then the SET clause to change their properties.
Here, we'll update 'Charlie's age to 26.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
query = (
"MATCH (p:Person {name: $name}) "
"SET p.age = $newAge "
"RETURN p.name AS name, p.age AS newAge"
)
result = session.run(query, name="Charlie", newAge=26)
record = result.single()
print(f"Updated {record['name']}'s age to {record['newAge']}")
driver.close()
if __name__ == "__main__":
main()Updating Relationship Properties
Just like nodes, relationships can also have properties. You can update these using MATCH to find the relationship and SET to modify its properties.
Let's add a since property to the KNOWS relationship between Charlie and Alice.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
query = (
"MATCH (p1:Person {name: $name1})"
"-[r:KNOWS]->"
"(p2:Person {name: $name2}) "
"SET r.since = $year "
"RETURN p1.name, p2.name, r.since AS sinceYear"
)
result = session.run(query, name1="Charlie", name2="Alice", year=2022)
record = result.single()
print(f"{record['p1.name']} knows {record['p2.name']} since {record['sinceYear']}")
driver.close()
if __name__ == "__main__":
main()Deleting Graph Data
To remove nodes and relationships, you use the DELETE clause. If a node has relationships, you must use DETACH DELETE to remove both the node and its relationships simultaneously.
Using just DELETE on a node with relationships will result in an error.
from neo4j import GraphDatabase
URI = "bolt://localhost:7687"
AUTH = ("neo4j", "password")
def main():
driver = GraphDatabase.driver(URI, auth=AUTH)
with driver.session() as session:
query = (
"MATCH (p:Person {name: $name}) "
"DETACH DELETE p"
)
result = session.run(query, name="Charlie")
print("Charlie and related data deleted.")
driver.close()
if __name__ == "__main__":
main()Quick Check: CRUD Operations
You've learned how to perform all fundamental CRUD operations. Let's test your understanding.
Recap: Programmatic CRUD
Great job! In this lesson, you've learned how to perform essential CRUD operations on your Neo4j graph database directly from a Python application:
- Create: Use
CREATEto add nodes and relationships. - Read: Use
MATCHandRETURNto retrieve data. - Update: Use
MATCHandSETto modify properties. - Delete: Use
MATCHandDETACH DELETEto remove data.
Mastering these operations is key to building dynamic and interactive graph applications.
자주 묻는 질문
“프로그램으로 CRUD 작업 수행” 강의는 무료인가요?
네 — “프로그램으로 CRUD 작업 수행” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Neo4j Graph Database Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Neo4j Graph Database Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“프로그램으로 CRUD 작업 수행”에서 뭘 배우나요?
애플리케이션에서 Cypher 쿼리를 실행하여 그래프 데이터를 동적으로 생성, 조회, 업데이트 및 삭제합니다. 브라우저에서 직접 실행하는 실습 코드로 Neo4j Graph Database Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Neo4j Graph Database Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Neo4j Graph Database Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“프로그램으로 CRUD 작업 수행” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Neo4j Graph Database Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Neo4j Graph Database Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Python 드라이버로 연결하기
- 프로그램으로 CRUD 작업 수행
- 트랜잭션 및 세션 처리
- 연결 풀링과 오류 처리