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.
Related
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?
I am working on connecting Neo4j with Java via Eclipse, when I run the code it works and I got the nodes and their relationship between them, now I need to have a cypher query, I tried many ways but they did not work?
I have looked to this, but I had an error.
[EDITED]
Here is my code:
package testtest;
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;
public class Testnn {
// This is the path of the Neo4J
private static final String Neo4J_DBPath = "/Users/nahla.INTRA/Documents/Neo4j/default.graphdb";
Node first;
Node second;
Relationship relation;
GraphDatabaseService graphDataService;
// List of Relationships first knows second
private static enum RelTypes implements RelationshipType
{
KNOWS
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Testnn hello = new Testnn();
hello.createDatabase();
hello.removeData();
hello.shutDown();
}
void createDatabase ()
{
// GraphDatabaseService
graphDataService = new GraphDatabaseFactory().newEmbeddedDatabase(Neo4J_DBPath);
//Begin Transaction
Transaction transaction = graphDataService.beginTx();
try{
// create nodes and set the properties
first = graphDataService.createNode();
first.setProperty("name", "Tom");
second = graphDataService.createNode();
second.setProperty("name", "Sara");
// Relationship
relation = first.createRelationshipTo(second, RelTypes.KNOWS);
relation.setProperty("relationship-type", "KNOWS");
System.out.println(first.getProperty("name").toString());
System.out.println(relation.getProperty("relationship-type").toString());
System.out.println(second.getProperty("name").toString());
// success Transaction
transaction.success();
}
finally {
//finish the Transaction
transaction.finish();
}
}
void removeData ()
{
Transaction transaction = graphDataService.beginTx();
try
{
// delete
first.getSingleRelationship(RelTypes.KNOWS, Direction.OUTGOING).delete();
System.out.println("Nodes are removed");
// delete nodes
first.delete();
second.delete();
transaction.success();
}
finally
{
// finish the transaction
transaction.finish();
}
}
void shutDown ()
{
// shut down graphDataService
graphDataService.shutdown();
System.out.println("Neo4J database is shutdown");
}
}
and now I have the query part:
try ( Transaction ignored = db.beginTx();
Result result = db.execute( "match (n {name: 'my node'}) return n, n.name" ) )
{
while ( result.hasNext() )
{
Map<String,Object> row = result.next();
for ( Entry<String,Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
}
rows += "\n";
}
}
so,,, first of all how to include the second part of the code to the first one, may be I did not put it in the right place, the second thing : the error is {result can not be resolved}
I have created folder using superuser and provided read-only access to folder for application user.
When trying to query all accessible folders(nt:folder), getting properties list as empty.
Partial code to reproduce:
Created folder:
public Node createFolder(Session adminSession) {
try {
Node parentNode = adminSession.getNode("/MyCompany/CommonFolder”);
if(!parentNode.hasNode("T1")){
Node node = parentNode.addNode("T1", "nt:folder");
node.addMixin("et:folderProperties");
node.setProperty("et:folderName", "T1");
node.addMixin("rep:AccessControllable");
session.save(); return node;
}else {
System.out.println("Node already exists");
}
} catch (RepositoryException e) {
e.printStackTrace();
}
return null;
}
Sharing to user(Principal based)
accessControlManager = (JackrabbitAccessControlManager)
adminSession.getAccessControlManager();
accessControlPolicy = accessControlManager.getApplicablePolicies(userPrincipal);
// for ex., principal is appuser1
if(accessControlPolicy != null && accessControlPolicy.length > 0) {
accessControlList = (JackrabbitAccessControlList) accessControlPolicy[0];
}else {
accessControlPolicy = accessControlManager.getPolicies(userPrincipal);
accessControlList = (JackrabbitAccessControlList) accessControlPolicy[0];
}
ValueFactory valueFactory = adminSession.getValueFactory();
//Tried all combinations, even providing with "JCR:ALL";
Privilege[] readPrivilege = new javax.jcr.security.Privilege[] {
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_READ),
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_NODE_TYPE_MANAGEMENT),
accessControlManager.privilegeFromName(
javax.jcr.security.Privilege.JCR_READ_ACCESS_CONTROL)};
Map<String, Value> restrictions = new HashMap<String, Value>();
restrictions.put("rep:nodePath", valueFactory.createValue("/MyCompany/CommonFolder/T1",
PropertyType.PATH));
restrictions.put("rep:glob", valueFactory.createValue(""));
accessControlList.addEntry(userPrincipal, privileges, true , restrictions);
accessControlManager.setPolicy(accessControlList.getPath(), accessControlList);
adminSession.save();
Printing all applicable folders for user
public void printAllFolders(Session userSession) {
QueryManager queryManager;
try {
queryManager = userSession.getWorkspace().getQueryManager();
String sql = "SELECT * FROM [nt:folder]";
Query query= queryManager.createQuery(sql, Query.JCR_SQL2);
QueryResult result = query.execute();
NodeIterator nodeIterator = result.getNodes();
System.out.println("Printing all applicable folders");
while(nodeIterator.hasNext()) {
Node node = nodeIterator.nextNode();
System.out.println("Folder Name:" + node.getName() + "; path: " + node.getPath());
PropertyIterator pIterator = node.getProperties();
while (pIterator.hasNext()){ //Returning empty for path "/MyCompany/CommonFolder/T1"
Property property = pIterator.nextProperty();
if (property.getDefinition().isMultiple()) {
Value[] values = property.getValues();
for(Value v11: values) {
QValueValue value = (QValueValue)v11;
System.out.println(String.format("Multi-valued property for node:
'%s' - %s has values",node.getName(),
property.getName() ,value.getString()));
}
} else {
QValueValue value = (QValueValue) property.getValue();
String strValue = value.getString();
System.out.println(String.format("property for node: '%s' - %s has value
%s",node.getName(),property.getName(),strValue));
}
}
}
} catch (RepositoryException e) {
e.printStackTrace();
}
}
using Jackrabbit(2.6.0 version) and JCR( 2.0 version).
Node child = cl.addNode("ONE");
child.setProperty("message", ("CL Child" + i));
session.save();
PropertyIterator iter = child.getProperties();
System.out.println("Size" + iter.getSize());
while (iter.hasNext()) {
PropertyImpl key = (PropertyImpl) iter.next();
String value = key.getString();
System.out.println("------------->" + key);
System.out.println("------------->" + value);
}
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.
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.