In graph databases, relationships between entities are represented as edges connecting vertices (nodes). Often, we need to check if a particular connection exists before performing further operations, like updating, deleting, or analyzing data.
In Apache TinkerPop Gremlin, this can be done efficiently using the .hasNext() step. It allows you to traverse the graph and return a Boolean value (true or false) indicating whether an edge exists between two vertices.
Follow below step-by-step procedure to build the Application.
Step 1: Create student and course vertices.
// Students g.addV('student').property('name','Alice').property('id','S1') g.addV('student').property('name','Bob').property('id','S2') // Courses g.addV('course').property('name','Math').property('code','C101') g.addV('course').property('name','Science').property('code','C102') g.addV('course').property('name','History').property('code','C103')
Step 2: Create edges (Enrollments)
// Alice enrolls in Math and Science g.V().has('student','id','S1').as('s'). V().has('course','code','C101').addE('enrolled_in').from('s') g.V().has('student','id','S1').as('s'). V().has('course','code','C102').addE('enrolled_in').from('s') // Bob enrolls in Science and History g.V().has('student','id','S2').as('s'). V().has('course','code','C102').addE('enrolled_in').from('s') g.V().has('student','id','S2').as('s'). V().has('course','code','C103').addE('enrolled_in').from('s')
Step 3: Check if a student is enrolled in a course
// Check if Alice is enrolled in Math g.V().has('student','id','S1').out('enrolled_in').has('code','C101').hasNext() // Returns: true // Check if Alice is enrolled in History g.V().has('student','id','S1').out('enrolled_in').has('code','C103').hasNext() // Returns: false
gremlin> g.V().has('student','id','S1').out('enrolled_in').has('code','C101').hasNext() ==>true gremlin> gremlin> g.V().has('student','id','S1').out('enrolled_in').has('code','C103').hasNext() ==>false
Previous Next Home
No comments:
Post a Comment