การดำเนินการ CRUD ด้วยโปรแกรม
เรียกใช้คำสั่งสอบถาม Cypher จากแอปพลิเคชันเพื่อสร้าง อ่าน อัปเดต และลบข้อมูลกราฟแบบไดนามิก
การดำเนินการ CRUD ด้วยโปรแกรม เป็นบทเรียน Neo4j Graph Database Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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.
เรียนรู้ Neo4j Graph Database Fundamentals ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 12
- บทเรียน
- 48
คำถามที่พบบ่อย
บทเรียน “การดำเนินการ CRUD ด้วยโปรแกรม” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การดำเนินการ CRUD ด้วยโปรแกรม” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Neo4j Graph Database Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Neo4j Graph Database Fundamentals มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การดำเนินการ CRUD ด้วยโปรแกรม”
เรียกใช้คำสั่งสอบถาม Cypher จากแอปพลิเคชันเพื่อสร้าง อ่าน อัปเดต และลบข้อมูลกราฟแบบไดนามิก คุณปฏิบัติ Neo4j Graph Database Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Neo4j Graph Database Fundamentals หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Neo4j Graph Database Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การดำเนินการ CRUD ด้วยโปรแกรม” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Neo4j Graph Database Fundamentals นี้ได้ไหม
ได้ บทเรียน Neo4j Graph Database Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การเชื่อมต่อด้วยไดรเวอร์ Python
- การดำเนินการ CRUD ด้วยโปรแกรม
- การจัดการธุรกรรมและเซสชัน
- การใช้พูลการเชื่อมต่อและการจัดการข้อผิดพลาด