Making relationships between nodes using graphdb - java

I am very new to graph-db and now I'm trying to do basics of that using examples. below is the sample code which i tried and I am trying to make relationship between three nodes. I am trying to get the below as o/p.
my code
private static final String DB_PATH = "/home/nnn/Documents/softwares/neo4j-community-2.0.1";
public String greeting;
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Node thirdNode;
Relationship relationship;
private static enum RelTypes implements RelationshipType
{
LIKES
}
public static void main( final String[] args )
{
G1 hello = new G1();
hello.createDb();
hello.removeData();
hello.shutDown();
}
void createDb()
{
clearDb();
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH );
registerShutdownHook( graphDb );
try ( Transaction tx = graphDb.beginTx() )
{
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Alice " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "Bob" );
thirdNode = graphDb.createNode();
thirdNode.setProperty( "message", "Anu" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.LIKES);
relationship.setProperty( "message", "likes " );
relationship = firstNode.createRelationshipTo( thirdNode, RelTypes.LIKES);
relationship.setProperty( "message", "likes " );
System.out.print( firstNode.getProperty("message"));
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
System.out.print( firstNode.getProperty( "message" ) );
//System.out.print( relationship.getProperty( "message" ) );
//System.out.print( thirdNode.getProperty( "message" ) );
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) )
+ ( (String) thirdNode.getProperty( "message" ) );
tx.success();
}
}
private void clearDb()
{
try
{
FileUtils.deleteRecursively( new File( DB_PATH ) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
void removeData()
{
try ( Transaction tx = graphDb.beginTx() )
{
firstNode.getSingleRelationship( RelTypes.LIKES, Direction.OUTGOING ).delete();
firstNode.delete();
secondNode.delete();
thirdNode.delete();
tx.success();
}
}
void shutDown()
{
System.out.println();
System.out.println( "Shutting down database ..." );
graphDb.shutdown();
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}

As the exception indicates, you're calling
firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
when you have more than one outgoing relation of type KNOWS from firstNode
(firstNode->secondNode and firstNode->thirdNode)
Maybe you want to use http://api.neo4j.org/2.0.1/org/neo4j/graphdb/Node.html#getRelationships(org.neo4j.graphdb.RelationshipType,%20org.neo4j.graphdb.Direction) instead
As for the output, you want to get all the relations from the first node to be able to get the end node of each relation.

You created two outgoing KNOWS relationships for your firstNode.
If you want to delete them all do:
for (Relationship rel : node.getRelationships()) {
rel.delete();
}
You can pass direction and type parameters to that method too.
But if you want to delete a node, all its relationships have to be deleted first.

Related

Auto-wiring not working in overridden `get()` method of Supplier Interface in spring-boot

I have a class named WorkerThread which overrides get() method
of implemented Supplier Interface. Inside WorkerThread class auto wiring of MockService is happening but when while calling methods of those services it throws NullPointerException.
I have created #PostConstruct init() method in MockService with logs which are getting printed on startup. Also If I remove the method calls of MockService the code works fine.
SomeServiceImpl.java (calling class for WorkerThread)
//initializing engine pool for processing which will be responsible for providing engine Objects
Supplier<OcrData> callable = new WorkerThread( enginesPool, imageFile, scanId, pageCount, saveOcrContent,
maxLangConsideration, pageThreshold, preprocess, outputFolder, saveInMongo );
response = CompletableFuture.supplyAsync( callable, executorService );
WorkerThread.java
#Component
public class WorkerThread implements Supplier<OcrData>
{
private static final Logger LOG = LoggerFactory.getLogger( WorkerThread.class );
private boolean SAVE_IN_MONGO;
private String outputFolder;
private Boolean preprocess;
private Integer pageThreshold;
private Integer maxLangConsideration;
private Boolean saveOcrContent;
private EnginesPool enginesPool;
private File imageFile;
private String scanId;
private String threadId;
private Integer pageCount;
private DocumentProcessor documentProcessor;
private MockService mockService;
private DummyService dummyService;
#Autowired
public void setMockAbbyyService( MockService mockService )
{
this.mockService = mockService;
}
#Autowired
public void setDocumentProcessor( DocumentProcessor documentProcessor )
{
this.documentProcessor = documentProcessor;
}
public WorkerThread()
{
}
public WorkerThread( EnginesPool pool, File source, String imageKey, Integer pageCount, Boolean saveOcrContent,
Integer maxLang, Integer threshold, Boolean preprocess, String outputFolder, boolean saveInMongo )
{
enginesPool = pool;
scanId = imageKey;
this.saveOcrContent = saveOcrContent;
maxLangConsideration = maxLang;
pageThreshold = threshold;
this.preprocess = preprocess;
this.outputFolder = outputFolder;
this.pageCount = pageCount;
this.SAVE_IN_MONGO = saveInMongo;
File reducedResolutionImage = null;
try {
boolean performPreprocess = this.preprocess;
if ( performPreprocess ) {
if ( pageCount > pageThreshold ) {
reducedResolutionImage = documentProcessor.getPreprocessedImage( imageFile );
}
}
} catch ( Exception ex ) {
LOG.error( "Error while getting preprocessed image for scanId: {}", ex, scanId );
}
if ( null != reducedResolutionImage ) {
imageFile = reducedResolutionImage;
} else {
imageFile = source;
}
}
#Override
public OcrData get()
{
Response response = null;
OcrData ocrData = new OcrData();
this.threadId = String.valueOf( Thread.currentThread().getId() );
try {
LOG.info( "Thread {} started ", this.threadId );
if ( imageFile != null ) {
LOG.info( "Thread {} processing scanId: {}", this.threadId, scanId );
try {
// SAVE_IN_MONGO false got for ocr
LOG.info( "Value of save in mongo {}", SAVE_IN_MONGO );
// SAVE_IN_MONGO flag to check mock abbyy
if ( SAVE_IN_MONGO ) {
// SAVE_IN_MONGO true get reponse from mongo if found then return
LOG.info( "fetching data from mongo" );
//HERE it fails complaining for null
if(mockService != null) {
response = mockService.getResponse( imageFile );
}else {
LOG.warn( "Could not autowire mock service." );
response = null;
}
LOG.info( "data fetched from mongo with response: {}", response!= null?"data exist":"no data found" );
// response not found
if ( response == null ) {
// submit for ocr
LOG.info("submiting request for ocr");
response = processImageFile( imageFile );
LOG.info("response for ocr : {}", response!=null?"ocr done": "ocr failed");
if ( response != null ) {
// saving result in mongo
//HERE also it fails
mockService.saveTo( response, imageFile );
}
}
} else {
// otherwise go for ocr.
response = processImageFile( imageFile );
}
//build ocrDate response object
ocrData.setResponse( response );
ocrData.setStatus( ScanRequestStatus.OCRED.getStatus() );
} catch ( Exception ex ) {
LOG.error( "Thread {}: Error caused {} for processing scanId: {}", this.threadId, ex, scanId );
ocrData.setException( ex );
ocrData.setStatus( ScanRequestStatus.FAILED.getStatus() );
ex.printStackTrace();
}
}
LOG.info( "Thread {} finished ", this.threadId );
} catch ( Exception ex ) {
LOG.error( "Error occurred while processing requests in parallel with exception {}", ex );
}
return ocrData;
}
private Response processImageFile( File imageFile ) throws Exception
{
//code to process
}
}
MockService.java
public interface MockService
{
String getImageKey( File file );
Response getResponse( File file );
void saveTo( Response responseFrom, File file );
}
MockServiceImpl.java
#Service
public class MockServiceImpl implements MockService
{
private static final Logger LOG = LoggerFactory.getLogger( MockServiceImpl.class );
private MockRepository mockAbbyyRepository;
#Autowired
public void setMockRepository( MockRepository mockRepository )
{
this.mockRepository = mockRepository;
}
#PostConstruct
public void postConstruct(){
// this log is getting printed
LOG.info( "After constructing MockService object" );
}
#Override
public String getImageKey( File file )
{
LOG.debug( "Getting image key for file {}", file.getName() );
FileInputStream fin = null;
byte fileContent[] = new byte[(int) file.length()];
try {
fin = new FileInputStream( file );
fin.read( fileContent );
} catch ( FileNotFoundException e ) {
LOG.error( "Exception found while getting image key", e );
} catch ( IOException e ) {
LOG.error( "Exception found while getting image key", e );
} catch ( Exception e ) {
LOG.error( "Exception found while getting image key", e );
}
String s = new String( fileContent );
String imageKey = sha256Encoding( s );
return imageKey;
}
#Override
public AbbyyResponse getAbbyyResponse( File file )
{
// code to get response
}
#Override
public void saveTo( AbbyyResponse responseFrom, File file )
{
// code to save the response
}
private String sha256Encoding( String phrase )
{
return Hashing.sha256().hashString( phrase, StandardCharsets.UTF_8 ).toString();
}
}
please share your inputs for this issue.
Thanks in advance
Supplier<OcrData> callable = new WorkerThread() can not be autowired.
To get a spring managed bean,
Supplier<OcrData> callable = applicationContext.getBean(WorkerThread.class);
or
Supplier<OcrData> callable = new WorkerThread();
AutowireCapableBeanFactory beanFactory = applicationContext.getBean(AutowireCapableBeanFactory.class);
beanFactory.autowiredBean(callable);

Neo4j browser freezes the whole system

I'm using an embedded Neo4j instance in my Spring Boot project (I'm using Spring JPA and Neo4j separately and I'm not using Spring-Boot-Neo4j stuff) and I want to visualise the graph I build using the Neo4j browser that I downloaded from here with the addition of a custom init.coffee that allows it to display images inside the nodes
This is the code I use in order to build my graph. The "buildGraph" function is executed when a request is being received by one of my RestControllers
(the reason I include all of my business logic implementation is because it may help detecting relationships/nodes etc being created/handled in a wrong way)
#Component
public class GraphBuilder
{
private String dbPath;
private int numberOFConnectionsForKeyIndividuals;
private String neo4jBoltAddress;
#Autowired
PersonService personService;
private final GraphDatabaseService graphDb;
public GraphBuilder(#Value("${dbPath}") String dbPath,
#Value("${neo4jBoltAddress}") String neo4jBoltAddress,
#Value("${numberOFConnectionsForKeyIndividuals}") int numberOFConnectionsForKeyIndividuals)
{
GraphDatabaseSettings.BoltConnector bolt = GraphDatabaseSettings.boltConnector( "0" );
this.dbPath = dbPath;
this.neo4jBoltAddress = neo4jBoltAddress;
this.numberOFConnectionsForKeyIndividuals = numberOFConnectionsForKeyIndividuals;
graphDb = new GraphDatabaseFactory()
.newEmbeddedDatabaseBuilder( new File(dbPath) )
.setConfig( bolt.type, "BOLT" )
.setConfig( bolt.enabled, "true" )
.setConfig( bolt.address, neo4jBoltAddress )
.newGraphDatabase();
registerShutdownHook( graphDb );
}
public void buildGraph()
{
List<Long> AsIDs = new ArrayList<>();
Map<Long,Long> personIdToNodeMap = new HashMap<>();
Map<String,List<Long>> nameToId = new HashMap<>();
Map<Long,List<Association>> associationsMap = new HashMap<>();
try ( Transaction tx = graphDb.beginTx() )
{
Schema schema = graphDb.schema();
for(Person person : personService.findAllPersons())
{
Node personNode = graphDb.createNode(new Label() {
#Override
public String name() {
return "Person";
}
});
//mapping persons to their respective nodes
personIdToNodeMap.put(person.getPersonId(),personNode.getId());
//mapping names to the ids of the persons
if(nameToId.get(person.getName()) == null)
{
nameToId.put(person.getName(), new ArrayList<>());
}
nameToId.get(person.getName()).add(person.getPersonId());
personNode.setProperty("Name", person.getName());
for(int a = 0 ; a < person.getAliases().size() ; a++)
{
personNode.setProperty("Alias " + a+1, person.getAliases().get(a).getAlias());
}
personNode.setProperty("Additional Name Information", person.getAdditionalNameInformation() != null ? person.getAdditionalNameInformation() : "");
personNode.setProperty("Id", person.getPersonId());
personNode.setProperty("Date of Birth", person.getDob() != null ? person.getDob() : "");
for(int f = 0 ; f < person.getFacebook().size() ; f++)
{
personNode.setProperty("Facebook " + f+1, person.getFacebook().get(f).getFacebookPage() + " (" + person.getFacebook().get(f).getAdditionalFacebookPageInformation() + ")");
}
personNode.setProperty("Additional Information", person.getInfo() != null ? person.getInfo() : "");
personNode.setProperty("image_url","http://localhost:8888/files/"+person.getPictureFilePath());
personNode.setProperty("Node Type", "Person");
if(person.getAssociations().size() > numberOFConnectionsForKeyIndividuals)
{
personNode.setProperty("Key_Individual","Yes");
}
for(A A : person.getAs())
{
Node ANode = graphDb.createNode(new Label() {
#Override
public String name() {
return "A";
}
});
ANode.setProperty("A", A.getA());
//TODO elaborate more on the A with additional properties
ANode.setProperty("Node Type", "A");
personNode.createRelationshipTo( ANode, EdgeTypes.HAS_DONE );
ANode.setProperty("image_url","http://localhost:8888/images/A.png");
AsIDs.add(ANode.getId());
}
for(Association association : person.getAssociations())
{
if(associationsMap.get(person.getPersonId()) == null)
{
associationsMap.put(person.getPersonId(), new ArrayList<>());
}
associationsMap.get(person.getPersonId()).add(association);
}
}
//Validating and building the association edges
//iterating through the nodes
for(Long personFromId : associationsMap.keySet())
{
//iterating through the associations registered for the node
for(Association associationFrom : associationsMap.get(personFromId))
{
String personNameFrom = associationFrom.getPersonNameFrom();
String personNameTo = associationFrom.getPersonNameTo();
//iterating through the persons whose name matches the other end of the association
if(nameToId.get(personNameTo) != null)
{
for(Long personToId : nameToId.get(personNameTo))
{
//iterating through the associations of the person at the other end of the association
if(associationsMap.get(personToId) != null)
{
List<Association> associationsToRemove = new ArrayList<>();
for(Association associationTo : associationsMap.get(personToId))
{
if(associationTo.getPersonNameTo().equals(personNameFrom) && nameToId.get(personNameFrom).contains(personFromId))
{
if(nameToId.get(personNameFrom).size() == 1)
{
Relationship relationship = graphDb.getNodeById(personIdToNodeMap.get(personFromId))
.createRelationshipTo( graphDb.getNodeById(personIdToNodeMap.get(personToId)), EdgeTypes.ASSOCIATES_WITH );
if(associationFrom.getType() != null)
{
relationship.setProperty("Association Type",associationFrom.getType());
}
associationsToRemove.add(associationTo);
}
else
{
boolean alreadyConnected = false;
for(Relationship rel : graphDb.getNodeById(personIdToNodeMap.get(personFromId)).getRelationships())
{
if( ( rel.getOtherNode(graphDb.getNodeById(personIdToNodeMap.get(personFromId))).
equals(graphDb.getNodeById(personIdToNodeMap.get(personToId))) ) )
{
alreadyConnected = true;
break;
}
}
if(!alreadyConnected)
{
Relationship relationship = graphDb.getNodeById(personIdToNodeMap.get(personFromId))
.createRelationshipTo( graphDb.getNodeById(personIdToNodeMap.get(personToId)), EdgeTypes.PROBABLY_ASSOCIATES_WITH );
if(associationFrom.getType() != null)
{
relationship.setProperty("Association Type",associationFrom.getType());
}
}
// associationsToRemove.add(associationTo);
}
}
}
associationsMap.get(personToId).removeAll(associationsToRemove);
}
}
}
}
}
tx.success();
}
Map<Long,List<String>> AToNamesMap = new HashMap<>();
//detecting names referred in the A's description
try(Transaction txAs = graphDb.beginTx() )
{
for(Long id : AsIDs)
{
Node ANode = graphDb.getNodeById(id);
String A = (String) ANode.getProperty("A");
for(String name : nameToId.keySet())
{
if(A.contains(name)) {
if(AToNamesMap.get(id) == null)
{
AToNamesMap.put(id,new ArrayList<>());
}
AToNamesMap.get(id).add(name);
}
}
}
List<Long> groupedAs = new ArrayList<>();
for(Long id : AsIDs)
{
if(AToNamesMap.get(id)!= null && AToNamesMap.get(id).size() > 1)
{
for(Long otherAID : AToNamesMap.keySet())
{
if(id != otherAID && !groupedAs.contains(otherAID) && !groupedAs.contains(id))
{
if(compareNamesLists(AToNamesMap.get(id), AToNamesMap.get(otherAID)))
{
Relationship rel = graphDb.getNodeById(otherAID).getSingleRelationship(EdgeTypes.HAS_DONE,Direction.INCOMING);
Node otherPersonNode = rel.getStartNode();
if(nameToId.get(otherPersonNode.getProperty("Name")) != null && nameToId.get(otherPersonNode.getProperty("Name")).size() > 1)
{
otherPersonNode.createRelationshipTo(graphDb.getNodeById(id), EdgeTypes.HAS_PROBABLY_DONE);
}
else
{
otherPersonNode.createRelationshipTo(graphDb.getNodeById(id), EdgeTypes.HAD_DONE);
}
rel.delete();
graphDb.getNodeById(otherAID).delete();
groupedAs.add(otherAID);
}
}
}
}
groupedAs.add(id);
}
txAs.success();
}
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
When I open the browser and connect it to the bolt that I expose for my embedded neo4j, the browser is able to show all the nodes in my graph database (at the moment less than 100) and it then freezes, causing the entire system to freeze (MacBook Pro 2016, 16GB). This happens around 3/5 times.
I know that the way I make my transactions is not ideal, but as I said all this processing happens before the neo4j browser starts.
Can you advise me on how to solve this issue?
Can you see anything in my code (connection left open etc) Is this a known issue for the neo4j browser?

Why does the client keep getting stuck on the read method in the client?

I have created 2 Java applications to form a chat room, and the client application freezes when trying to read a message over the network.
It never says 'leaving readText', but it does say 'Inside readText' on the client application.
Server Application:
Server.java:
import java.io.*;
import java.net.*;
import java.util.*;
public class Server
{
public static void main(String[] args) throws IOException
{
final int PORT = 2525;
Socket sock = null;
ServerSocket serverSocket = null;
UserHandler userHandler = null;
try
{
serverSocket = new ServerSocket( PORT );
System.out.println( "Service started..." );
}
catch( IOException exc )
{
System.out.println( "Failed to start service..." );
System.exit( 0 );
}
do
{
sock = hSSocket.accept();
System.out.println( "Incoming connection..." );
userHandler = new UserHandler( sock );
userHandler.start();
}while( true );
}
}
UserHandler.java:
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
public class UserHandler extends Thread
{
private Socket sock = null;
private Scanner in = null;
private String user = "";
private boolean loggedIn = false;
public UserHandler( Socket sock ) throws IOException
{
super("UserHandler");
this.sock = sock;
in = new Scanner( this.sock.getInputStream() );
}
public void run()
{
String inText;
System.out.printf( "Running...\n" );
do
{
inText = in.nextLine();
System.out.println( msg );
try
{
processInText( inText );
} catch (SQLException e)
{
e.printStackTrace();
}
}while( !msg.equals("Disconnect") );
try
{
sock.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
private void processInText( String inText )
{
String password = "";
code = msg.substring( 0, 4 );
switch( inText )
{
case "User":
if( loggedIn )
{
System.out.println( "Already logged in" );
sendText( "allw" );
return;
}
if( inText.length() > 5 )
{
name = inText.substring( 5 );
System.out.println( "Asking for password" );
sendText( "Pass" );
return;
}
sendText( "allw" );
break;
case "Pass":
System.out.printf( "password received %s\n", inText.substring(5) );
if( user.equals( "user" ) && inText.substring( 5 ).equals( "pass" ) )
loggedIn = true;
break;
default:
System.out.println( "Unknown" );
}
}
private void sendText( String outText )
{
PrintWriter out = null;
System.out.println( "Inside sendText" );
try
{
out = new PrintWriter( sock.getOutputStream() );
} catch (IOException e)
{
e.printStackTrace();
}
System.out.println( "Sending message..." );
System.out.printf( "%s\n", outText);
out.println( outText );
System.out.println( "Message sent..." );
}
}
Client Application:
Client.java:
import java.io.*;
import java.net.*;
import java.util.*;
public class Client extends Thread
{
private static final int PORT = 2525;
private Socket sock = null;
private InetAddress host = null;
private Scanner in = null;
private PrintWriter out = null;
public static void main(String[] args)
{
Client client = new Client();
client.setup();
client.start();
}
public void sendText( String outText )
{
out.println( outText );
}
public String readText()
{
String inText = "";
System.out.println( "Inside readText" );
if( in != null )
inText = in.nextLine();
System.out.println( "leaving readText" );
return inText;
}
public void setup()
{
try
{
host = InetAddress.getLocalHost();
sock = new Socket( host, PORT );
}
catch( IOException exc )
{
}
try
{
in = new Scanner( sock.getInputStream() );
out = new PrintWriter( sock.getOutputStream(), true );
} catch (Exception e)
{
}
}
private void sortText( String inText )
{
try
{
System.out.println( "Handling comms..." );
switch( inText.substring( 0, 3 ) )
{
case "User":
System.out.println( "Sending user" );
sendText("User user" );
break;
case "Pass":
System.out.println( "Sending pass" );
sendText("Pass pass" );
break;
case "Disc":
System.out.println( "User " + msg.substring(3) + " disconnected." );
break;
case "allw":
System.out.println( "logged in" );
break;
default:
System.out.println( "Who knows what the server is saying" );
}
}
catch( Exception e)
{
}
// TODO Auto-generated method stub
}
#Override
public void run()
{
String inText = "";
do
{
System.out.println( "sending user" );
sendText( "User user" );
System.out.println( "User sent" );
readText();
System.out.println( "sending pass" );
sendMessage( "Pass pass" );
System.out.println( "Pass sent" );
inText = readMessage();
sortText( inText );
}while( !inText.equals( "Disconnect" ) );
}
}

Cannot see nodes on neo4j web interface created using EmbeddedJava program

I am able to successfully run the Embeddedjava program.but my nodes are not getting reflected when i open the neo4j interface through localhost.For your reference
I made the following changes to my neo4j-server.properties
org.neo4j.server.database.location=C:/neo4j-community-1.9.6/data/graph.db/
org.neo4j.server.webadmin.data.uri=C:/neo4j-community-1.9.6/data/graph.db/
this is the same DB_path that i am using in the code.
Everytime I run the program ,the count on the dashboard increases by 2(i have created 2 nodes in my program).But when i run the query
START root=node(*)
return count(root)
it gives me the answer as 0.
Also,i noticed that the data/keystore file does not get generated when i run the java program.it gets generated only when i start the interface through localhost:7474.Does this have anything to do ?
Java Code
import java.io.File;
import java.io.IOException;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.kernel.impl.util.FileUtils;
import org.neo4j.kernel.StoreLocker;
public class EmbeddedNeo4j
{
private static final String DB_PATH = "C://neo4j-community-1.9.6//data//graph.db";
public String greeting;
// START SNIPPET: vars
GraphDatabaseService graphDb;
Node firstNode;
Node secondNode;
Relationship relationship;
// END SNIPPET: vars
// START SNIPPET: createReltype
private static enum RelTypes implements RelationshipType
{
KNOWS
}
// END SNIPPET: createReltype
public static void main( final String[] args )
{
EmbeddedNeo4j hello = new EmbeddedNeo4j();
hello.createDb();
hello.removeData();
hello.shutDown();
}
void createDb()
{
// clearDb();
// START SNIPPET: startDb
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
// registerShutdownHook( graphDb );
// END SNIPPET: startDb
// START SNIPPET: transaction
Transaction tx=null;
try
{
tx= graphDb.beginTx();
firstNode = graphDb.createNode();
firstNode.setProperty( "message", "Hello, " );
secondNode = graphDb.createNode();
secondNode.setProperty( "message", "World!" );
relationship = firstNode.createRelationshipTo( secondNode, RelTypes.KNOWS );
relationship.setProperty( "message", "brave Neo4j " );
// END SNIPPET: addData
// START SNIPPET: readData
System.out.print( firstNode.getProperty( "message" ) );
System.out.print( relationship.getProperty( "message" ) );
System.out.print( secondNode.getProperty( "message" ) );
// END SNIPPET: readData
greeting = ( (String) firstNode.getProperty( "message" ) )
+ ( (String) relationship.getProperty( "message" ) )
+ ( (String) secondNode.getProperty( "message" ) );
tx.success();
}
catch(Exception e)
{
tx.failure();
}
finally
{
// Database operations go here
// END SNIPPET: transaction
// START SNIPPET: addData
// START SNIPPET: transaction
tx.finish();
}
// END SNIPPET: transaction
}
private void clearDb()
{
try
{
FileUtils.deleteRecursively( new File(DB_PATH) );
}
catch ( IOException e )
{
throw new RuntimeException( e );
}
}
void removeData()
{
Transaction tx=null;
try
{
tx = graphDb.beginTx() ;
firstNode.getSingleRelationship( RelTypes.KNOWS, Direction.OUTGOING ).delete();
firstNode.delete();
secondNode.delete();
tx.success();
}
catch(Exception e)
{
tx.failure();
}
finally
{
// START SNIPPET: removingData
// let's remove the data
// END SNIPPET: removingData
tx.finish();
}
}
void shutDown()
{
System.out.println();
System.out.println( "Shutting down database ..." );
// START SNIPPET: shutdownServer
graphDb.shutdown();
// END SNIPPET: shutdownServer
}
// START SNIPPET: shutdownHook
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
// END SNIPPET: shutdownHook
}
public static void main( final String[] args )
{
EmbeddedNeo4j hello = new EmbeddedNeo4j();
hello.createDb();
hello.removeData();
hello.shutDown();
}
You are creating DB then calling removeData.
If your question is about the webadmin showing you an increase of 2 nodes when the query to count all nodes shows 0, then you should ignore the webadmin node count. It is not truly the number of nodes but sort of the highest node ID in use. The query
START root=node(*)
return count(root)
will correctly show you the number of nodes. This is 0 which is expected since your java program creates nodes and then deletes them.

Neo4j 1.9.4 java community edition persistence

For the life of me, I cannot understand why I am unable to read a graph I already created in neo4j 1.9.4 community edition. In eclipse, I run the following code:
public class neo4jtest {
private GraphDatabaseService graphDb;
private static final String neo4j_db = "c:/tmp/db/neo4j-new-db";
private UniqueFactory<Node> nodefactory;
private static enum RelTypes implements RelationshipType
{
FRIEND, FOLLOWER
}
public neo4jtest() {
graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(neo4j_db).
setConfig( GraphDatabaseSettings.node_keys_indexable, "ScreenName,ID" ).
setConfig( GraphDatabaseSettings.relationship_keys_indexable, (RelTypes.FRIEND).name()+","+(RelTypes.FOLLOWER).name()).
setConfig( GraphDatabaseSettings.node_auto_indexing, "true" ).
setConfig( GraphDatabaseSettings.relationship_auto_indexing, "true" ).
newGraphDatabase();
//graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(neo4j_db);
registerShutdownHook( graphDb );
nodefactory = new UniqueFactory.UniqueNodeFactory( graphDb, "users" )
{
#Override
protected void initialize( Node created, Map<String, Object> properties )
{
created.setProperty( "ScreenName", properties.get( "ScreenName" ) );
}
};
}
public void exit() {
graphDb.shutdown();
}
public static void main(String[] args) {
neo4jtest n4 = new neo4jtest();
String u1 = "Moe";
//Node unode = n4.createNeo4jGraph(u1);
n4.exploreNeo4jGraph(u1);
n4.exit();
}
public Node createNeo4jGraph(String uname) {
Node firstNode;
Relationship relationship;
// build a graph
try {
Transaction tx = graphDb.beginTx();
firstNode = nodefactory.getOrCreate("ScreenName", uname);
firstNode.setProperty( "ScreenName", uname );
firstNode.setProperty("ID", 1);
Node followerNode = nodefactory.getOrCreate("ScreenName", "Larry");
followerNode.setProperty("ID", 2);
relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
followerNode = nodefactory.getOrCreate("ScreenName", "Curly");
followerNode.setProperty("ID", 3);
relationship = firstNode.createRelationshipTo( followerNode, RelTypes.FOLLOWER ); // may not be unique
relationship = followerNode.createRelationshipTo(firstNode, RelTypes.FRIEND);
tx.success();
return firstNode;
} catch(Exception ex) {}
return null;
}
private void exploreNeo4jGraph(String scname) {
// use the auto indexer to lookup node with string name
// Get the Node auto index
ReadableIndex<Node> autoNodeIndex = graphDb.index()
.getNodeAutoIndexer()
.getAutoIndex();
Node mainUser = autoNodeIndex.get( "ScreenName", scname ).getSingle();
if (mainUser==null) {
// why not use nodefactory to get it?
System.out.println("Auto indexer did not work");
mainUser = nodefactory.getOrCreate("ScreenName", scname);
}
exploreNeo4jGraph(mainUser);
}
private void exploreNeo4jGraph(Node unode) {
// explore the nodes and edges in the graph
if (unode==null) {
System.err.println("Cannot explore from null node!");
return;
}
long currRels = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllRelationships());
long currNodes = IteratorUtil.count(GlobalGraphOperations.at(graphDb).getAllNodes());
System.out.println("Number of nodes in graph is " + currNodes);
System.out.println("Number of edges in graph is " + currRels);
int numberOfFollowers = 0;
String output = unode.getProperty( "ScreenName" ) + "'s friends:\n";
Traverser friendsTraverser = getFriends( unode );
for ( Path friendPath : friendsTraverser )
{
output += "At depth " + friendPath.length() + " <= "
+ friendPath.endNode().getProperty( "ScreenName" ) + "\n";
numberOfFollowers++;
}
output += "Number of friends found: " + numberOfFollowers + "\n";
System.out.println(output);
}
private Traverser getFriends(final Node person )
{
TraversalDescription td = Traversal.description()
.breadthFirst()
.relationships( RelTypes.FRIEND, Direction.INCOMING )
.evaluator( Evaluators.excludeStartPosition() );
return td.traverse( person );
}
private static void registerShutdownHook( final GraphDatabaseService graphDb )
{
// Registers a shutdown hook for the Neo4j instance so that it
// shuts down nicely when the VM exits (even if you "Ctrl-C" the
// running application).
Runtime.getRuntime().addShutdownHook( new Thread()
{
#Override
public void run()
{
graphDb.shutdown();
}
} );
}
}
Basically, I uncomment line
Node unode = n4.createNeo4jGraph(u1);
to create the graph.
Then run it again with that line commented to just explore the graph that was created. When I run it again, it does not report the graph that was created. What am I doing wrong?
Thanks,
D
I'd guess you need to close the transaction. From the javadoc:
finish() (in 1.9)
Commits or marks this transaction for rollback, depending on whether success() or failure() has been previously invoked.

Categories

Resources