Monday, 31 January 2022

JanusGraph: Add properties to a vertex property

In JanusGraph, you can attach properties to a vertex property object.

 

Syntax

public default <V> VertexProperty<V> property(final String key, final V value, final Object... keyValues)

Set the provided key to the provided value using default VertexProperty.Cardinality for that key. The default cardinality can be vendor defined and is usually tied to the graph schema. The provided key/values are the properties of the newly created VertexProperty.

 

public <V> VertexProperty<V> property(final VertexProperty.Cardinality cardinality, final String key, final V value, final Object... keyValues)

Create a new vertex property. If the cardinality is VertexProperty.Cardinality#single, then set the key to the value. If the cardinality is VertexProperty.Cardinality#list, then add a new value to the key. If the cardinality is VertexProperty.Cardinality#set, then only add a new value if that value doesn't already exist for the key. If the value already exists for the key, add the provided key value vertex property properties to it.

 

Example

janusGraphVertex.property("experience", 10.7, "ABC Corp", 3.5, "Delta Inc", 7.2);

 

Find the below working application.

 

AddPropertiesToAVertexProperty.java

package com.sample.app.vertex;

import java.util.Set;

import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

public class AddPropertiesToAVertexProperty {

	public static void main(String args[]) {
		JanusGraph janusGraph = null;
		try {
			janusGraph = JanusGraphFactory.open("/Users/Shared/janus.properties");

			// Create a person vertex
			JanusGraphVertex janusGraphVertex = janusGraph.addVertex("employee");

			// Add properties to the vertex
			janusGraphVertex.property("name", "Krishna");
			janusGraphVertex.property("age", 31);
			janusGraphVertex.property("gender", 'M');

			janusGraphVertex.property("experience", 10.7, "ABC Corp", 3.5, "Delta Inc", 7.2);

			janusGraph.tx().commit();

			JanusGraphVertex persistedVertex = (JanusGraphVertex) janusGraph.vertices(janusGraphVertex.id()).next();
			VertexProperty<? extends Object> experienceProperty = persistedVertex.property("experience");

			String key = experienceProperty.key();
			String value = experienceProperty.value().toString();
			System.out.println(key + " : " + value);

			Set<String> propertiesAssociaetd = experienceProperty.keys();
			for (String property : propertiesAssociaetd) {
				System.out.println("\t" + property + " --> " + experienceProperty.value(property).toString());
			}

		} finally {

			if (janusGraph != null)
				janusGraph.close();
			System.out.println("Done!!!");
		}

	}

}

Output

experience : 10.7
	ABC Corp --> 3.5
	Delta Inc --> 7.2
Done!!!

 

 

Previous                                                 Next                                                 Home

FastAPI: response_model_include and response_model_exclude: Exclude and include fields from response model

response_model_include and response_model_exclude path operation decorator parameters are used to specify which fields are included/excluded from the response model.

 

Example 1: using response_model_include

@app.get("/emps/by-id-ex1/{empId}", response_model = Employee, response_model_include ={'name', 'country'})
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4))

 

Example 2: Using response_model_exclude

@app.get("/emps/by-id-ex2/{empId}", response_model = Employee, response_model_exclude={'age','tax'})
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4))

 

Find the below working application.

 

responseModelExcludeInclude.py

 

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from enum import Enum

app = FastAPI()

class CountryEnum(str, Enum):
    India = "India"
    China = "China"
    Russia = "Russia"

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str = 'India'
    tax: float = 30.5

emp1 = Employee(name= "Krishna", age = 32, country = "India", tax = 20)
emp2 = Employee(name= "Ram", age = 42, country = "China", tax = 35)
emp3 = Employee(name= "Sailu", age = 33)

employees = {1 : emp1, 2 : emp2, 3 : emp3}

@app.get("/emps/by-id-ex1/{empId}", response_model = Employee, response_model_include ={'name', 'country'})
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4)):
    if(empId in employees):
        return employees[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

@app.get("/emps/by-id-ex2/{empId}", response_model = Employee, response_model_exclude={'age','tax'})
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4)):
    if(empId in employees):
        return employees[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

 

Open terminal and execute the command 'uvicorn responseModelExcludeInclude:app --reload'.

$uvicorn responseModelExcludeInclude:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [40731] using statreload
INFO:     Started server process [40733]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

 

Open the url ‘http://localhost:8000/docs’ in browser, you will see swagger documentation.

 


 

 

Previous                                                    Next                                                    Home

Sunday, 30 January 2022

JanusGraph: Get the vertex Property object by property name

Using 'property(final String key)' method, you can get the Property for the vertex given its key.

 

Example

VertexProperty<?> vertexProperty = janusGraphVertex.property("name");

 

GetPropertyObject.java

package com.sample.app.vertex;

import java.util.Iterator;
import java.util.Set;
import java.util.StringJoiner;

import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

public class GetPropertyObject {

	public static void main(String args[]) {
		JanusGraph janusGraph = null;

		try {
			janusGraph = JanusGraphFactory.open("/Users/Shared/janus.properties");

			// Create a person vertex
			JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");

			// Add properties to the vertex
			janusGraphVertex.property("name", "Krishna");
			janusGraphVertex.property("age", 31);
			janusGraphVertex.property("gender", 'M');

			janusGraph.tx().commit();

			VertexProperty<?> vertexProperty = janusGraphVertex.property("name");
			String key = vertexProperty.key();
			String value = vertexProperty.value().toString();

			System.out.println(key + " has value " + value);

			System.out.println("-----------------------------");
		} finally {

			if (janusGraph != null)
				janusGraph.close();
			System.out.println("Done!!!");
		}

	}

}

 

Output

name has value Krishna
-----------------------------
Done!!!

 


  

Previous                                                 Next                                                 Home

JanusGraph: Add multiple values to a vertex property

By specifying the vertex property cardinality, we can add multiple values to a vertex property. VertexProperty.Cardinality specifies the vertex cardinality.

public interface VertexProperty<V> extends Property<V>, Element {

    public enum Cardinality {
        single, list, set
    }


    .......
    .......
}

 

Example

janusGraphVertex.property(VertexProperty.Cardinality.set, "hobbies", "cricket");
janusGraphVertex.property(VertexProperty.Cardinality.set, "hobbies", "football");
janusGraphVertex.property(VertexProperty.Cardinality.set, "hobbies", "tennis");

If the cardinality is VertexProperty.Cardinality#single, then set the key to the value. If the cardinality is  VertexProperty.Cardinality#list, then add a new value to the key. If the cardinality is VertexProperty.Cardinality#set, then only add a new value if that value doesn't already exist for the key. If the value already exists for the key, add the provided key value vertex property properties to it.

 

AddMultipleValuesToAProperty.java

 

package com.sample.app.vertex;

import java.util.Iterator;
import java.util.Set;
import java.util.StringJoiner;

import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

public class AddMultipleValuesToAProperty {

	public static void main(String args[]) {
		JanusGraph janusGraph = null;

		try {
			janusGraph = JanusGraphFactory.open("/Users/Shared/janus.properties");

			// Create a person vertex
			JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");

			// Add properties to the vertex
			janusGraphVertex.property("name", "Krishna");
			janusGraphVertex.property("age", 31);
			janusGraphVertex.property("gender", 'M');

			janusGraphVertex.property(VertexProperty.Cardinality.set, "hobbies", "cricket");
			janusGraphVertex.property(VertexProperty.Cardinality.set, "hobbies", "football");
			janusGraphVertex.property(VertexProperty.Cardinality.set, "hobbies", "tennis");

			janusGraph.tx().commit();

			Iterator<Vertex> janusGraphVertexes = janusGraph.vertices(janusGraphVertex.id());
			Vertex vertex = janusGraphVertexes.next();

			System.out.println("-----------------------------");
			System.out.println("id : " + vertex.id());
			System.out.println("long id : " + ((JanusGraphVertex) vertex).longId());
			System.out.println("label : " + vertex.label());

			System.out.println("properties");
			Set<String> properties = janusGraphVertex.keys();
			for (String property : properties) {

				if ("hobbies".equals(property)) {
					Iterator<? extends Property<Object>> propertyIterator = janusGraphVertex.properties(property);

					StringJoiner hobbies = new StringJoiner(",");
					while (propertyIterator.hasNext()) {
						hobbies.add(propertyIterator.next().value().toString());
					}

					System.out.println("\t" + property + " -> " + hobbies.toString());
				} else {
					System.out.println("\t" + property + " -> " + janusGraphVertex.property(property).value());
				}

			}
			System.out.println("-----------------------------");
		} finally {

			if (janusGraph != null)
				janusGraph.close();
			System.out.println("Done!!!");
		}

	}

}

 

Output

-----------------------------
id : 40964264
long id : 40964264
label : person
properties
	gender -> M
	hobbies -> cricket,football,tennis
	name -> Krishna
	age -> 31
-----------------------------
Done!!!

 

 

 

 

 

Previous                                                 Next                                                 Home

JanusGraph: Create edge between vertexes

‘addEdge’ method is used to create an edge between vertexex.

 

JanusGraphEdge addEdge(String label, Vertex vertex, Object... keyValues)

Creates a new edge incident on this vertex. Creates and returns a new JanusGraphEdge of the specified label with this vertex being the outgoing vertex and the given vertex being the incoming vertex.

        

AddEdge.java

package com.sample.app.edges;

import java.util.Iterator;
import java.util.Set;

import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphEdge;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

public class AddEdge {
	public static void main(String args[]) {

		JanusGraph janusGraph = JanusGraphFactory.open("/Users/Shared/janus.properties");

		// Create a person vertex
		JanusGraphVertex krishnaVertex = janusGraph.addVertex("person");
		krishnaVertex.property("name", "Krishna");
		krishnaVertex.property("age", 31);
		krishnaVertex.property("gender", 'M');

		// Create a person vertex
		JanusGraphVertex ramVertex = janusGraph.addVertex("person");
		ramVertex.property("name", "Ram");
		ramVertex.property("age", 34);
		ramVertex.property("gender", 'M');

		JanusGraphEdge janusGraphEdge = ramVertex.addEdge("knows", krishnaVertex, "from", 2017, "colleague", "N");

		janusGraph.tx().commit();

		Iterator<Edge> edges = ramVertex.edges(Direction.OUT);
		while (edges.hasNext()) {
			Edge edge = edges.next();
			System.out.println(edge.outVertex().property("name").value() + "--" + edge.label() + "-->"
					+ edge.inVertex().property("name").value());
		}

		janusGraph.close();
		System.out.println("Done!!!");
	}
}

 

Output

Ram--knows-->Krishna
Done!!!

 

 

 

  

Previous                                                 Next                                                 Home

JanusGraph: Add a label to vertex

While adding a vertex to the graph, you can attach a label to it. A vertex label is a label attached to vertices in a JanusGraph graph. This can be used to define the nature of a vertex.

 

Example

JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");

 

VertexLabel.java

package com.sample.app.vertex;

import java.util.Iterator;

import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraphVertex;

public class VertexLabel {

	public static void main(String args[]) {

		JanusGraph janusGraph = JanusGraphFactory.open("/Users/Shared/janus.properties");

		// Create a person vertex
		JanusGraphVertex janusGraphVertex = janusGraph.addVertex("person");
		janusGraph.tx().commit();

		Iterator<Vertex> janusGraphVertexes = janusGraph.vertices(janusGraphVertex.id());
		Vertex vertex = janusGraphVertexes.next();

		System.out.println("label : " + vertex.label());

		janusGraph.close();
		System.out.println("Done!!!");
	}

}

 

Output

label : person
Done!!!

 

 

 

  

Previous                                                 Next                                                 Home