Hot questions for Using Neo4j in database

Question:

I use a Neo4J database with nearly 500k nodes. When I startup my Spring application and do the first query, it takes about 4-5 seconds. This happens just for the first query, so I thought I could do a warmup after spring is initialized to make all subsequent queries faster.

This is my applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-2.5.xsd">

    <!-- neo4j database -->
    <util:map id="config">
        <entry key="enable_remote_shell" value="false" />
    </util:map>

    <bean id="graphDbFactory" class="org.neo4j.graphdb.factory.GraphDatabaseFactory" />

    <bean id="graphDbBuilder" factory-bean="graphDbFactory"
        factory-method="newEmbeddedDatabaseBuilder">
        <constructor-arg value="/path/to/db" />
    </bean>

    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder"
        factory-method="setConfig">
        <constructor-arg ref="config" />
    </bean>

    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" class="org.neo4j.graphdb.GraphDatabaseService"/>

    <context:component-scan base-package="com.app.components" />
</beans>

I saw that one way to wait for Spring beans initialization was to implement an ApplicationListener, and the regular way to warmup the database with Neo was to call the apoc.runtime.warmup() function, so I did as follows:

package com.app.components;

@Component
public class StartupTasks implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger LOG = LogManager.getLogger(StartupTasks.class);

    @Autowired
    GraphDatabaseService db;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        executeTestSelect();
    }

    private void executeTestSelect() {
        LOG.info("Warming up Neo4j...");

        Transaction tx = db.beginTx();
        db.execute("CALL apoc.warmup.run()");
        tx.close();

        LOG.info("Warmup complete.");
    }
}

This one didn't work, everything gets correctly logged but the first neo4j query is still slow.

Since this approach didn't work, I edited the executeTestSelect method to run a real query and process the results like this:

private void executeTestSelect() {
    String textToSearch = "a"; // returns almost all nodes, should make neo4j cache them all
    Transaction tx = db.beginTx();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("textToSearch", textToSearch );
    Result resultSet = db.execute("MATCH (n:PROD) WHERE n.description CONTAINS {textToSearch} RETURN n",
                params);
    Iterator<Node> results = resultSet.columnAs("n");
    int count = 0;
    while (results.hasNext()) {
        results.next();
        count++:
    }
    tx.close();
    LOG.info("Neo4j cache done. Processed " + count + " nodes.");
}

This time the startup takes 4-5 seconds just to execute the query, but then it prints

Neo4j cache done. Processed 0 nodes.

This is weird, because the exact same query run when the app is fully initialized returns 450k nodes.

What am I missing? Is it possible that when reaching onApplicationEvent the Neo4j DB hasn't been initialized yet and can't execute queries?

How do I correctly warmup a neo4j database right after the complete spring app initialization?


Answer:

Ok I discovered this by pure luck.

I removed the ApplicationListener and created a @Service class with the @Autowired annotation on the method that does the warmup, it seems to be working.

I discovered this by removing a class field without seeing the @Autowired annotation left here, and it worked. I tried it several times, the warmup is working now. I don't know if it is documented somewhere in the Spring Documentation.

This is my final class:

package com.app.components;

@Component
public class Neo4jWarmup {

    private static final Logger LOG = LogManager.getLogger(StartupTasks.class);

    @Autowired
    GraphDatabaseService db;

    /*
     * this did the trick - the method gets called 
     * after Spring initialization and the DB works as expected
     */
    @Autowired 
    public void neo4jWarmup() {
        executeTestSelect();
    }

    private void executeTestSelect() {
        LOG.info("Warming up Neo4j...");

        Transaction tx = db.beginTx();
        db.execute("CALL apoc.warmup.run()");
        tx.close();

        LOG.info("Warmup complete.");
    }
}

Question:

I am creating neo4j graph database (.DB file) using java program by inputting one excel file. I can update this .DB file with another excel file but once this .DB file is opened in Neo4j after that I am unable to update this existing database by inputting another excel file it is showing exception.

Exception in thread "main" java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, D:\innoneuron\Transform\Feature1_Automatic_Tagging\Feature1_Automatic_Tagging\test.db
    at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:366)
    at org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:59)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:91)
    at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:181)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:71)
    at feature3.AutomatedGraph.startDb(AutomatedGraph.java:88)
    at feature3.AutomatedGraph.main(AutomatedGraph.java:50)
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.transaction.XaDataSourceManager@5a4aa2f2' was successfully initialized, but failed to start. Please see attached cause exception.
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
    at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:343)
    ... 6 more
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource@f0f2775' was successfully initialized, but failed to start. Please see attached cause exception.
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513)
    at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
    at org.neo4j.kernel.impl.transaction.XaDataSourceManager.start(XaDataSourceManager.java:164)
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
    ... 8 more
Caused by: org.neo4j.kernel.impl.storemigration.StoreUpgrader$UpgradingStoreVersionNotFoundException: 'neostore.nodestore.db' does not contain a store version, please ensure that the original database was shut down in a clean state.
    at org.neo4j.kernel.impl.storemigration.UpgradableDatabase.checkUpgradeable(UpgradableDatabase.java:78)
    at org.neo4j.kernel.impl.storemigration.StoreMigrator.needsMigration(StoreMigrator.java:135)
    at org.neo4j.kernel.impl.storemigration.StoreUpgrader.getParticipantsEagerToMigrate(StoreUpgrader.java:268)
    at org.neo4j.kernel.impl.storemigration.StoreUpgrader.migrateIfNeeded(StoreUpgrader.java:143)
    at org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.start(NeoStoreXaDataSource.java:344)
    at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
    ... 11 more

Is there any way to update this .DB file with different input excels? Thanks in advance


Answer:

Per the initial cause of the exception:

please ensure that the original database was shut down in a clean state

Are you sure that you correctly shut down the database at the end of its creation, when you imported the first Excel file? You need to call GraphDatabaseService.shutdown() before exiting.

Question:

Hi,

I've created a maven project in eclipse and added the dependency:

<dependency>
    <groupId>org.neo4j</groupId>
    <artifactId>neo4j-jdbc</artifactId>
    <version>3.0</version>
</dependency>

I'm just trying to get a connection to my db working so that I can move on to integrate the connection with my main project but I'm having trouble getting things off the ground.

I've used the code example given on the official repo:

import org.neo4j.jdbc.Connection;
import org.neo4j.jdbc.PreparedStatement;
import org.neo4j.jdbc.ResultSet;

public class Neo4jConnectionTest {

    public static void main(String[] args) {
        // Connect
        Connection con = DriverManager.getConnection(
                                        "jdbc:neo4j:bolt://localhost");

        // Querying
        String query = "MATCH (u:User)-[:FRIEND]-(f:User) 
                        WHERE u.name = {1} 
                        RETURN f.name, f.age";
        try {
            PreparedStatement stmt = con.prepareStatement(query);
            stmt.setString(1,"John");
            ResultSet rs = con.execute();

            while (rs.next()) {
                System.out.println(
                    "Friend: "+rs.getString("f.name")+" is "+rs.getInt("f.age"));
            }
        } catch (Exception e) { e.printStackTrace(); }
        con.close();
    }
}

I am unable to compile this as:

DriverManager cannot be resolved within the neo4j-jdbc-3.0,

Prepared stmt = con.prepareStatement(query); causes a type mismatch,

and con.execute() is undefined for type org.neo4j.jdbc.Connection

I'd greatly appreciate any advice and expertise on the matter, thanks.


Answer:

By changing to:

<dependency>
    <groupId>org.neo4j.driver</groupId>
    <artifactId>neo4j-java-driver</artifactId>
    <version>1.0.4</version>
</dependency>

I was able to successfully connect to the Neo4j 3.0 server using an example from Neo4j's site:

public static void main(String[] args) {
    Driver driver = GraphDatabase.driver( 
        "bolt://localhost", AuthTokens.basic( "neo4j", "neo4j" ) );
    Session session = driver.session();

    session.run( "CREATE (a:Person {name:'Arthur', title:'King'})" );

    StatementResult result = session.run( 
                                        "MATCH (a:Person) 
                                         WHERE a.name = 'Arthur' 
                                         RETURN a.name AS name, a.title AS title");

    while ( result.hasNext() ) {
        Record record = result.next();
        System.out.println( record.get( "title" ).asString() + 
                                " " + record.get("name").asString() );
    }

    session.close();
    driver.close();
}

I thought I'd share as this worked instantly with no hassle.

Neo4j Language Guides

Question:

I'd like to list all labels in my neo4j database.

For example, in my site, I have 'songs' which I'd like to tag with labels such as 'jazz', 'classical', 'hiphop', or 'funk'. I can do this, but then I also want to let users know which tags already exist by returning all the labels (aka tags) in my database.

I could use nodes for tags instead, but I thought tagging would be a good use case for labels. Am I missing something?


Answer:

GlobalGraphOperations.getAllLabels() is your friend.

Question:

I access the neo4j database via GraphDatabaseService. I added some nodes and relation and want to do a query. My goal is to get all Nodes that got an Calling relation to the endnode. So i have the whole paths to this node. (e.g.: node1 -calling-> node2 -calling*-> nodeX -calling-> endnode)

I tried something like this:

GraphDatabaseService _graphDatabase; // db is running and working fine
Node node;//given by the function call

HashMap<String, Object> properties = Maps.newHashMap();
properties.put("name", getPropertyFromNode(node, "name"));
String query = "MATCH p=(startnode)-[rel:CALLING*]->(endnode) WHERE endnode.name = {name} RETURN p";

Result result = _graphDatabase.execute(query, properties);
while (result.hasNext()) {
    Map<String, Object> next = result.next();
    next.forEach((k, v) -> {
        System.out.println(k + " : " + v.toString());
        if (v instanceof PathImpl) {
            PathImpl pathImpl = (PathImpl) v;
            String startNodeName = getPropertyFromNode(pathImpl.startNode(), "name");
            String endNodeName = getPropertyFromNode(pathImpl.endNode(), "name");
            System.out.println(startNodeName + " -calling-> " + endNodeName);
        }
    });
}

public String getPropertyFromNode(Node node, String propertyName) {
    String result = null;
    try (Transaction transaction = _graphDatabase.beginTx()) {
        result =node.getProperty(propertyName).toString();
        transaction.success();
    }
    return result;
}

Problem for me is, that the result is a Map<'String, Object>, and i want do get the id's or names of the nodes that are in the relation. I tried to cast the Object to PathImpl because thats the type that is returned (figured out by debug), but it seams like that this class is in a different class loader so the statement instanceof returns false. v.toString() returns a String representation of the liked nodes with id's (e.g.: p : (24929)--[CALLING,108061]-->(24930))

My question is, can i access this information in a better way or how can i change the classLoader (if that is the problem, i'm working with eclipse in a gradle project) to make that cast happened. I don't wanna parse the String to get the id's and get the nodes from the db via that property, its seams ugly for me.


Answer:

If you want to get the names of the start and end nodes, then you should modify the Cypher code to return them (instead of the paths), which would greatly simplify the code needed to extract that data from the response. For example:

MATCH p=(startnode)-[rel:CALLING*]->(endnode)
WHERE endnode.name = {name}
RETURN startnode.name AS s_name, endnode.name AS e_name, p;

Question:

I am trying to insert a 1 MB image inside neo4j using the following code:

 File fnew = new File("C:\\Users\\myimage.jpg");
 BufferedImage originalImage = ImageIO.read(fnew);
 ByteArrayOutputStream baos = new ByteArrayOutputStream();
 baos.flus();
 ImageIO.write(originalImage, "jpg", baos);
 return baos.toByteArray();

Then I insert this byte array using:

 user.setProperty("photo", photo);

This all goes fine. When I try to select the photo, using the following method, it writes it on my hard drive disk as 536KB instead of the 1 MB original size.

 byte[] imageInByte = (byte[]) user.getProperty("photo");
 InputStream in = new ByteArrayInputStream(imageInByte);
 BufferedImage bImageFromConvert = ImageIO.read(in);
 ImageIO.write(bImageFromConvert, "jpg", new File("C:\\newimage.jpg"));

Now the weird part: I can see the image, open it, same resolution, I don't see any difference in terms of quality though. Looks like it is compressed.

Why is this happening?


Answer:

Saving a jpg image through ImageIO results in lossy compression of the jpg (I believe the quality defaults to 70%). You can a) Change the the quality of the image when you write to file (see Setting jpg compression level with ImageIO in Java ) or b) if you don't actually need the BufferedImage, just read/write the bytes from file to database.

Question:

I've been working on Neo4j recently and i know basic rules and how to select property names. However , i need to get the identifier name.

Here is the code:

CREATE (Jugan:Person {name:'George'})

I DON'T want to find 'George' name, but i wanna get the identifier name that is 'Jugan'.

When i write something with " match and return " stuff , i wanna get this "Jugan" name. I hope i explained clearly.


Answer:

Identifiers are not persisted at all. Their lifetime is just the current statement and their main usage is to refer back to a known node e.g. for returning them.

So no luck finding Jugan in your example. Introduce a property for this.

Question:

I have a server Neo4j database. I'd like to connect it with my Java application using JPA. There are few possibilities, for example:

  • Hibernate OGM
  • DataNucleus

However, every Neo4j JPA implementation I found works only with embedded databases.

Currently I managed to solve this temporary by using direct queries to Neo4J REST interface.

Are there any other options for using server Neo4j database in my application?


Answer:

The latest Hibernate OGM, comes now with Remote Neo4j server support: http://hibernate.org/ogm/

Question:

I have two different test classes, one testing a module that I wrote and the other testing a user-defined function that I developed. These two tests instantiate a Neo4j for testing purposes differently. Module test does it like this:

class ModuleTest
{
    GraphDatabaseService database;

    @Before
    public void setUp()
    {
        String confFile = this.getClass().getClassLoader().getResource("neo4j-module.conf").getPath();
        database = new TestGraphDatabaseFactory()
                .newImpermanentDatabaseBuilder()
                .loadPropertiesFromFile(confFile)
                .newGraphDatabase();
    }
}

While the UDF test class instantiates its embedded database this way:

public class UdfTest
{
    @Rule
    public Neo4jRule neo4j = new Neo4jRule()
        .withFunction(Udf.class);

    @Test
    public void someTest() throws Throwable
    {
        try (Driver driver = GraphDatabase.driver(neo4j.boltURI() , Config.build().withEncryptionLevel(Config.EncryptionLevel.NONE).toConfig())) {
            Session session = driver.session();
            //...
        }
    }
}

The problem here is that in the first form the UDFs are not registered and in the second the module. My question is; how can I start an embedded Neo4j database for my tests in which both my module and UDF is loaded?


Answer:

Take a look at how APOC Procedures loads procedures and functions within their test classes. They call a utility method during setUp():

public static void registerProcedure(GraphDatabaseService db, Class<?>...procedures) throws KernelException {
    Procedures proceduresService = ((GraphDatabaseAPI) db).getDependencyResolver().resolveDependency(Procedures.class);
    for (Class<?> procedure : procedures) {
        proceduresService.registerProcedure(procedure);
        proceduresService.registerFunction(procedure);
    }
}

Just pass the GraphDatabaseService and the Class with the procedures/functions to register, and this should set everything up for your test class.

Question:

I'm building a Spring Application using a Neo4j database. I have some services, that implement basic database-functions like persisting a user or finding a user by his username. Since I implemented some restraints, for example that it's not possible to delete a not existing user, i want to test my service. My wish would be having a test that builds a temporary Neo4j graphdb like described in http://neo4j.com/docs/stable/tutorials-java-unit-testing.html. But additionally I want to autowire my UserService into the test, do some operations on the temporary database and destroy the temporary database in the end again. I'm expecting that I can solve this with TestConfigurations, but since I'm not really experienced with Spring or Neo4j, it's not that simple.

I have the following configuration

@Configuration
@EnableNeo4jRepositories(basePackages = "de.myapp")
@EnableTransactionManagement
public class UserTestConfiguration extends Neo4jConfiguration{

  @Bean
  public UserService userService() {
    return new UserBean();
  }

  @Bean
  public Neo4jServer neo4jServer() {
    //This is probably wrong since i really want to connect to the impermanent db
    return new RemoteServer("http://localhost:7474");
  }

  @Bean
  public SessionFactory getSessionFactory() {
    return new SessionFactory("de.myapp");
  }
}

And the following test-class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TSUserTestConfiguration.class)
public class TSUserBeanTest {

  private GraphDatabaseService graphDb;

  @Autowired
  private TSUserService userService;

  @Before
  public void prepareTestDatabase() {
    graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
  }

  @After
  public void destroyTestDatabase() {
    graphDb.shutdown();
  }

  @Test
  public void createUserTest() {
    TSUser user = new TSUser("TestUser", "TestEmail");
    //This should create the user in the impermanent db
    userService.persistUser(user);
    //assert stuff here
  }
}

However, I get a NullPointer Exception for the graphDB in the destroy and I'm not even sure if I'm on the right way. Does someone have an example for this scenario maybe? Even a better way to integration-test my service on a temporary db is welcome.

Thanks and regards Urr4


Answer:

Looks like you're using SDN 4.x. - which version?

SDN 4.0 RELEASE

Instead of a RemoteServer, you will use an InProcessServer which internally starts a new instance of CommunityNeoServer on an available local port. It will manage shut down as well, so it's ideal and recommended for tests. In your configuration, use this instead of the RemoteServer-

@Bean public Neo4jServer neo4jServer() { return new InProcessServer(); }

The dependencies required are documented in the reference guide. Further reading, the test section in this blog post.

SDN 4.1 M1

The InProcessServer is no longer available, and instead you'll want to use the Embedded Driver which will set up for you the Impermanent graph database. ogm.properties for the impermanent embedded store should contain-

driver=org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver

Dependencies required are documented in the reference guide. An example of upgrading your tests to use SDN 4.1 can be found here.

Question:

Anyone have experience with using embedded Neo4j in GWT? I get an AccessControlException when I try to create the embedded database.

Here's the line I use to create my database in my ServiceImpl file:

GraphDatabaseService graphDb = new GraphDatabaseFactory().newEmbeddedDatabase("/var/uwcompanygraph");

Here's the stacktrace:

SEVERE: javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract com.coreywu.uwcompanygraph.client.CompanyGraph com.coreywu.uwcompanygraph.client.QueryGraphService.getGraph()' threw an unexpected exception: java.security.AccessControlException: access denied ("java.io.FilePermission" "\var\uwcompanygraph" "read")
    at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:389)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:579)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:265)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:305)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:127)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:491)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: java.security.AccessControlException: access denied ("java.io.FilePermission" "\var\uwcompanygraph" "read")
    at java.security.AccessControlContext.checkPermission(AccessControlContext.java:372)
    at java.security.AccessController.checkPermission(AccessController.java:559)
    at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
    at com.google.appengine.tools.development.DevAppServerFactory$CustomSecurityManager.checkPermission(DevAppServerFactory.java:429)
    at java.lang.SecurityManager.checkRead(SecurityManager.java:888)
    at java.io.File.exists(File.java:808)
    at org.neo4j.kernel.DefaultFileSystemAbstraction.mkdirs(DefaultFileSystemAbstraction.java:111)
    at org.neo4j.kernel.impl.util.StringLogger$ActualStringLogger.<init>(StringLogger.java:582)
    at org.neo4j.kernel.impl.util.StringLogger$ActualStringLogger.<init>(StringLogger.java:560)
    at org.neo4j.kernel.impl.util.StringLogger.loggerDirectory(StringLogger.java:109)
    at org.neo4j.kernel.logging.ClassicLoggingService.<init>(ClassicLoggingService.java:41)
    at org.neo4j.kernel.logging.ClassicLoggingService.<init>(ClassicLoggingService.java:36)
    at org.neo4j.kernel.logging.LogbackWeakDependency$1.apply(LogbackWeakDependency.java:41)
    at org.neo4j.kernel.logging.LogbackWeakDependency$1.apply(LogbackWeakDependency.java:37)
    at org.neo4j.kernel.logging.LogbackWeakDependency.tryLoadLogbackService(LogbackWeakDependency.java:98)
    at org.neo4j.kernel.logging.LogbackWeakDependency.tryLoadLogbackService(LogbackWeakDependency.java:103)
    at org.neo4j.kernel.logging.DefaultLogging.createDefaultLogging(DefaultLogging.java:42)
    at org.neo4j.kernel.InternalAbstractGraphDatabase.createLogging(InternalAbstractGraphDatabase.java:979)
    at org.neo4j.kernel.InternalAbstractGraphDatabase.create(InternalAbstractGraphDatabase.java:442)
    at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:336)
    at org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:59)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:91)
    at org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:181)
    at org.neo4j.graphdb.factory.GraphDatabaseFactory.newEmbeddedDatabase(GraphDatabaseFactory.java:71)
    at com.coreywu.uwcompanygraph.server.QueryGraphServiceImpl.getGraph(QueryGraphServiceImpl.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:115)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:561)
    ... 40 more

Answer:

Your JVM has the Java SecurityManager enabled. Either disable it or set an appropriate policy for the security manager that grants I/O permissions to /var/uwcompanygraph.

According to FAQ list of GWT, there's a setting in the Eclipse plugin for Google App Engine that might be activated by error, see http://www.gwtproject.org/doc/latest/FAQ_Troubleshooting.html#AccessControlException_access_denied.

Question:

While running the following query in Neo4j

USING PERIODIC COMMIT LOAD CSV WITH HEADERS FROM 'file:///home/peppa/database/ap/aC.csv' AS line
CREATE (:Aporte {Organization: line[1] ,ruc: line[2] , year: line[4] ,date: line[6] ,process: line[7] ,LastName: line[8] ,LastNameM: line [9] ,Name: line[10] ,DocType: line[11] ,DocNum: line[12] ,TypeAp: line[13] ,Nature: line[14]})

I get the following error:

Expected 10 to be a java.lang.String, but it was a java.lang.Long

Don't know if the file is bad structured or my query is wrong. Please Help!!.

EDIT: I keep having the same issues with the following query:

USING PERIODIC COMMIT 500 LOAD CSV WITH HEADERS FROM 'file:////home/peppa/database/aP/AC.csv' AS line
CREATE (:Ap  {dni: toint(line[1]) ,rc: toint(line[0])})

PD: I already tried without toint.

Here is some of the data I'm working with:

"20501723844","06747807"
"20501723844","00803710"
"20501723844","40596835"
"20501723844","41696842"
"20501723844","27241420"
"20501723844","19249405"
"20501723844","23154926"
"20501723844","25446127"
"20501723844","18016385"
"20501723844","07093664"
"20501723844","07286049"
"20501723844","21140951"
"20501723844","10291445"
"20501723844","08866233"
"20501723844","09684232"
"20501723844","28297360"

Answer:

Have a look at the hints available here.

http://neo4j.com/developer/guide-import-csv/

May be that your dataset has something not expected

Question:

We have a moderate size graph having 6330318 nodes and 6779549 relationships. After having imported the data, I have been unable to start the neo4j server or the neo4j shell. Both of them fail with GC overhead limit exceeded errors. I am giving a maximum heap space size of 12 GB to the JVM. The server has 15GB RAM. The neo4j.properies has following configuration for memory mapped IO.

neostore.nodestore.db.mapped_memory=400M
neostore.relationshipstore.db.mapped_memory=520M
neostore.propertystore.db.mapped_memory=100M
neostore.propertystore.db.strings.mapped_memory=10M
neostore.propertystore.db.arrays.mapped_memory=10M

We don't have any properties in the graph, therefore such low values for propertystore related settings.

I have also written a small web application for querying the graph, which is deployed on Tomcat. That also failed to query the graph with the following errors

java.lang.OutOfMemoryError: Java heap space
    java.util.Arrays.copyOf(Arrays.java:2245)
    java.util.Arrays.copyOf(Arrays.java:2219)
    java.util.ArrayList.grow(ArrayList.java:242)
    java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:216)
    java.util.ArrayList.ensureCapacityInternal(ArrayList.java:208)
    java.util.ArrayList.add(ArrayList.java:440)
    org.apache.lucene.index.FieldInfos.addInternal(FieldInfos.java:216)
    org.apache.lucene.index.FieldInfos.read(FieldInfos.java:361)
    org.apache.lucene.index.FieldInfos.<init>(FieldInfos.java:74)
    org.apache.lucene.index.SegmentCoreReaders.<init>(SegmentCoreReaders.java:80)
    org.apache.lucene.index.SegmentReader.get(SegmentReader.java:116)
    org.apache.lucene.index.SegmentReader.get(SegmentReader.java:94)
    org.apache.lucene.index.DirectoryReader.<init>(DirectoryReader.java:105)
    org.apache.lucene.index.ReadOnlyDirectoryReader.<init>(ReadOnlyDirectoryReader.java:27)
    org.apache.lucene.index.DirectoryReader$1.doBody(DirectoryReader.java:78)
    org.apache.lucene.index.SegmentInfos$FindSegmentsFile.run(SegmentInfos.java:709)
    org.apache.lucene.index.DirectoryReader.open(DirectoryReader.java:72)
    org.apache.lucene.index.IndexReader.open(IndexReader.java:256)
    org.neo4j.kernel.api.impl.index.LuceneLabelScanStore.init(LuceneLabelScanStore.java:249)
    org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.init(LifeSupport.java:483)
    org.neo4j.kernel.lifecycle.LifeSupport.init(LifeSupport.java:72)
    org.neo4j.kernel.impl.nioneo.xa.NeoStoreXaDataSource.start(NeoStoreXaDataSource.java:423)
    org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
    org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
    org.neo4j.kernel.impl.transaction.XaDataSourceManager.start(XaDataSourceManager.java:164)
    org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507)
    org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115)
    org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:339)
    org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:59)
    org.neo4j.graphdb.factory.GraphDatabaseFactory$1.newDatabase(GraphDatabaseFactory.java:90)
    org.neo4j.graphdb.factory.GraphDatabaseBuilder.newGraphDatabase(GraphDatabaseBuilder.java:199)
    com.socialtwist.rnet.web.RnetNeo4jServlet.init(RnetNeo4jServlet.java:44)

We have deployed the application on a server with 16 GB of RAM and have given Tomcat a heap space of 12 GB. What other tuning options are available for Neo4J to make this work under reasonable response time?


Answer:

How many labels do you have in your graph? Something is very off with your graph and query. I think you confused labels (types) with id's

Create index on :User(id);

MATCH (referee:User)<-[:IS_FRIEND_OF]-(referrer:User) WHERE referee.id=1677523 RETURN referrer;

Should return instantly after you fixed you graph model, i.e. Removed all numeric labels

Question:

I use DataNucleus and JDO. To create the schema for "tables" during the persistence process I use datanucleus.schema.autoCreateAll=true to tell DataNucleus to auto create schema. Once I have made enty to the Table any attempt to add field to the model results to org.neo4j.graphdb.NotFoundException: NODE[68] has no property with propertyKey="newFieldName".

What is the best way to alter or add properties to a Table which already contains entries?

This is the stack trace.

2017-12-27 13:46:08.509 [qtp1955990522-68] Query - JDOQL Query : Executing "SELECT FROM com.hope.tub.neo4j.jdo.model.Product WHERE name.equals(value) PARAMETERS String value" ...
2017-12-27 13:46:08.509 [qtp1955990522-68] Native - Retrieving objects of type com.hope.tub.neo4j.jdo.model.Product using Cypher query : START this=node:DN_TYPES(class="com.hope.tub.neo4j.jdo.model.Product") RETURN this
[INFO ] 2017-12-27 13:46:08.537 [qtp1955990522-68] Query - Reading in results for query "SELECT FROM com.hope.tub.neo4j.jdo.model.Product WHERE name.equals(value) PARAMETERS String value" since the connection used is closing/committing
2017-12-27 13:46:08.539 [qtp1955990522-68] Cache - Object with id "com.hope.tub.neo4j.jdo.model.Product:11" not found in Level 1 cache
2017-12-27 13:46:08.540 [qtp1955990522-68] Cache - Object "com.hope.tub.neo4j.jdo.model.Product@74e1d24" (id="com.hope.tub.neo4j.jdo.model.Product:11") added to Level 1 cache (loadedFlags="[NNNYNNNNNNN]")
2017-12-27 13:46:08.567 [qtp1955990522-68] Connection - Managed connection org.datanucleus.store.neo4j.ConnectionFactoryImpl$ManagedConnectionImpl@7e678a93 [conn=org.neo4j.kernel.impl.factory.GraphDatabaseFacade@18f961ba, commitOnRelease=true, closeOnRelease=true, closeOnTxnEnd=false] is committing
2017-12-27 13:46:08.567 [qtp1955990522-68] Connection - Managed connection org.datanucleus.store.neo4j.ConnectionFactoryImpl$ManagedConnectionImpl@7e678a93 [conn=org.neo4j.kernel.impl.factory.GraphDatabaseFacade@18f961ba, commitOnRelease=true, closeOnRelease=true, closeOnTxnEnd=false] committed connection
2017-12-27 13:46:08.568 [qtp1955990522-68] Persistence - Disconnecting com.hope.tub.neo4j.jdo.model.Product@74e1d24 from StateManager[pc=com.hope.tub.neo4j.jdo.model.Product@74e1d24, lifecycle=HOLLOW]
2017-12-27 13:46:08.568 [qtp1955990522-68] Cache - Level 1 Cache cleared
2017-12-27 13:46:08.568 [qtp1955990522-68] Persistence - ExecutionContext CLOSED "org.datanucleus.ExecutionContextImpl@7464295a"
2017-12-27 13:46:08.568 [qtp1955990522-68] Transaction - Transaction rolling back for ExecutionContext org.datanucleus.ExecutionContextImpl@59f25f8e
2017-12-27 13:46:08.568 [qtp1955990522-68] Transaction - Rolling back [DataNucleus Transaction, ID=1608044257-5, enlisted resources=[]]
2017-12-27 13:46:08.568 [qtp1955990522-68] Transaction - Transaction rolled back in 0 ms
2017-12-27 13:46:08.569 [qtp1955990522-68] Persistence - ExecutionContext CLOSED "org.datanucleus.ExecutionContextImpl@59f25f8e"
Dec 27, 2017 1:46:08 PM com.hope.tub.servlets.TuCreateServlet doPost
SEVERE: null
org.neo4j.graphdb.NotFoundException: NODE[11] has no property with propertyKey="creatorID".
at org.neo4j.kernel.impl.core.NodeProxy.getProperty(NodeProxy.java:479)
at     org.datanucleus.store.neo4j.fieldmanager.FetchFieldManager.fetchLongField(FetchFieldManager.java:157)
at org.datanucleus.state.StateManagerImpl.replacingLongField(StateManagerImpl.java:1912)
at com.hope.tub.neo4j.jdo.model.Product.dnReplaceField(Product.java)
at com.hope.tub.neo4j.jdo.model.Product.dnReplaceFields(Product.java)
at org.datanucleus.state.StateManagerImpl.replaceFields(StateManagerImpl.java:4286)
at org.datanucleus.state.StateManagerImpl.replaceFields(StateManagerImpl.java:4311)
at org.datanucleus.store.neo4j.Neo4jUtils$1.fetchFields(Neo4jUtils.java:605)
at org.datanucleus.state.StateManagerImpl.loadFieldValues(StateManagerImpl.java:3719)
at org.datanucleus.store.neo4j.Neo4jUtils.getObjectUsingApplicationIdForDBObject(Neo4jUtils.java:601)
at org.datanucleus.store.neo4j.Neo4jUtils.getObjectForPropertyContainer(Neo4jUtils.java:565)
at org.datanucleus.store.neo4j.query.LazyLoadQueryResult.getResultFromMapRow(LazyLoadQueryResult.java:153)
at org.datanucleus.store.neo4j.query.LazyLoadQueryResult.closingConnection(LazyLoadQueryResult.java:136)
at org.datanucleus.store.query.AbstractQueryResult.disconnect(AbstractQueryResult.java:105)
at org.datanucleus.store.neo4j.query.JDOQLQuery.performExecute(JDOQLQuery.java:291)
at org.datanucleus.store.query.Query.executeQuery(Query.java:1966)
at org.datanucleus.store.query.Query.executeWithArray(Query.java:1855)
at org.datanucleus.api.jdo.JDOQuery.executeInternal(JDOQuery.java:433)
at org.datanucleus.api.jdo.JDOQuery.execute(JDOQuery.java:276)
at com.hope.tub.neo4j.jdo.services.impl.ProductNeo4jServiceImpl.findByName(ProductNeo4jServiceImpl.java:76)
at com.hope.tub.neo4j.jdo.services.impl.ProductNeo4jServiceImpl.save(ProductNeo4jServiceImpl.java:90)
at com.hope.tub.neo4j.jdo.services.impl.ProductNeo4jServiceImpl.save(ProductNeo4jServiceImpl.java:24)
at com.hope.tub.access.beans.ProductBean.createProduct(ProductBean.java:135)
at com.hope.tub.servlets.TuCreateServlet.createProduct(TuCreateServlet.java:107)
at com.hope.tub.servlets.TuCreateServlet.doPost(TuCreateServlet.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:848)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1772)
at com.hope.tub.filters.ValidateJsonAntiForgeryTokenFilter.doFilter(ValidateJsonAntiForgeryTokenFilter.java:254)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1751)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:205)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFil[INFO ] 2017-12-27 13:46:08.571 [qtp1955990522-68] / - ValidateJsonAntiForgeryTokenFilter:DoAfterProcessing
ter(ServletHandler.java:1759)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:582)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:226)
at org.eclipse.jetty.server.handler.ContextHandler.__doHandle(ContextHandler.java:1180)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:512)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1112)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:213)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:134)
at org.eclipse.jetty.server.Server.handle(Server.java:534)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:320)
at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:267)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:671)
at org.eclipse.jetty.util.thread.QueuedThreadPool$2.run(QueuedThreadPool.java:589)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.neo4j.kernel.api.exceptions.PropertyNotFoundException: NODE[11] has no property with propertyKeyId=29.
at org.neo4j.kernel.impl.core.NodeProxy.getProperty(NodeProxy.java:471)
... 50 more

Initial Model:

@PersistenceCapable(identityType = IdentityType.APPLICATION, cacheable = "false", detachable = "true")
public class Product implements Serializable {

private static final long serialVersionUID = 8269335445554701873L;

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
long id;
@Persistent
private String name = null;
...

Any attempt to add new property like this below, reproduces the above stack trace.

...
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
long id;
@Persistent
private String name = null;
@Persistent
private long creatorID;
...

Answer:

Missing (non-String) columns are not currently catered for. That is, it assumes that the objects stored in the Neo4j database are consistent with the model used for retrieving them.

That is fixed in GitHub. https://github.com/datanucleus/datanucleus-neo4j/issues/32

Question:

I try to get a working system of an embedded tomcat-server with spring-boot, joinfaces and the embedded neo4j-graph-database with the object-mapping ogm. Everything seems to work fine. I commit my sources to https://svn.riouxsvn.com/circlead-embedd/circlead-embedded/

The problem is that all neo4j-ogm-examples (see i.e. http://www.hascode.com/2016/07/object-graph-mapping-by-example-with-neo4j-ogm-and-java/) show that @Relationship works with ogm. But when i test it with

@NodeEntity
public abstract class GenericNode<T> implements INode<T> {

    @GraphId
    public Long id;

    @SuppressWarnings("unused")
    private void setId(Long id) {
        this.id = id;
    }

    public String label;

    @Relationship(type = "PARENT_OF", direction = Relationship.INCOMING)
    public Set<T> parents = new HashSet<T>();

    @Relationship(type = "CHILD_OF", direction = Relationship.OUTGOING)
    public Set<T> children = new HashSet<T>();

    ...

then all relations seem not to be written in the database, because the lines

    Role rp = new Role("Role 1");
    Role rc = new Role("Role 2");
    rc.addParent(rp);
    session.save(rc);
    Iterable<Role> roles = session.query(Role.class, "MATCH (x) RETURN x;", Collections.<String, Object>emptyMap());

    for (Role role : roles) {
        System.out.println(role);
    }

show in the console that the relations of the database are missing. It seems that only in the active session-relations are found. After a server-reboot all relations are missing.

Role [id=52, label=Role 2, parents=[]]
Role [id=53, label=Role 1, parents=[]]
Role [id=54, label=Role 1, parents=[]]
Role [id=55, label=Role 2, parents=[54]]

I have no clue what occurs this kind of error. I use neo4j-ogm 2.1.2 and neo4j 3.1.3.

Any idea?


Answer:

The result you are seeing is expected - neo4j-ogm maps what you return in your cypher query (plus what you already have in your session). If you also want related entities then return the relationship and other nodes:

MATCH (x)-[r]-(x2) RETURN x,r,x2

or if you want e.g. only parent field hydrated:

MATCH (x)<-[r:PARENT_OF]-(p) RETURN x,r,p

This will hydrate first level only. To hydrate all levels (parent of a parent) you need to use variable length path and return its nodes and relationships (returning paths directly doesn't work reliably):

MATCH p=(x)-[:PARENT_OF*..]-() RETURN nodes(p),rels(p)

Question:

I've created a graph database. There are nodes, that are called Vertex and that have attributes: attr1:<float-value>, attr2:<float-value>, etc., and relationships, that are called Padre and that have the follow attributes attr1:<float-value>, attr2:<float-value>, etc. Now, I'm writing a Java program that, given two Vertexes (two ints that match to the id of the nodes), check if a path exists between them. If so, then calculates the sum of attributes of the path.

I've tried with this code:

public void res(Session session, int x, int y) {

    float z = 0F;
    boolean found = false;

    while (!found) {
        if (x == y) {
            StatementResult res = session.run("MATCH (N:Vertex) WHERE N.ID=" + x +" RETURN PROPERTIES(N)");
            Record record = res.next();

            for (String a: record.get("PROPERTIES(N)").keys()) {
                if(a.equals("ID") || a.equals("IdAlbero")) {
                    continue;
                }

                Value k = record.get("PROPERTIES(N)").get(a);
                z += k.asFloat();
            }

            found = true;
        } else {
            StatementResult res = session.run("MATCH (N:Vertex) WHERE N.ID=" + x +" RETURN PROPERTIES(N)");
            Record record = res.next();
            for (String a: record.get("PROPERTIES(N)").keys()) {
                if(a.equals("ID") || a.equals("IdAlbero")) {
                    continue;
                }

                Value k = record.get("PROPERTIES(N)").get(a);
                z += k.asFloat();
            }

            res = session.run("MATCH (N:Vertex),(M:Vertex), (N) - [R:Padre] ->(M) WHERE N.ID = " + x + " RETURN PROPERTIES(R)");
            record = res.next();

            for (String a: record.get("PROPERTIES(R)").keys()) {
                if (a.equals("ID") || a.equals("IdAlbero")) {
                    continue;
                }

                Value k = record.get("PROPERTIES(R)").get(a);
                z += k.asFloat();
            }
        }
    }

    System.out.println(z);
}

Now, I've an error to the z += k.asFloat() statement. This is the error:

Exception in thread "main" org.neo4j.driver.v1.exceptions.value.Uncoercible: Cannot coerce FLOAT to Java String at org.neo4j.driver.internal.value.ValueAdapter.asString(ValueAdapter.java:84) at Neo4j.res(Neo4j.java:160) at Connessione.connettiti(Connessione.java:27) at Connessione.main(Connessione.java:35).

What can I do?


Answer:

I do not know much Java, but you can fit everything in one Cypher-query using the filter and reduce:

MATCH (N1:Vertex {id: 1})
OPTIONAL MATCH (N1)-[R:Padre]->(N2:Vertex {id:3})
WITH N1, FILTER(k in keys(N1) WHERE k<>'id' AND k<>'idAlbero') as kN1,
     N2, FILTER(k in keys(N2) WHERE k<>'id' AND k<>'idAlbero') as kN2
WITH N1, kN1, REDUCE(sum1=0.0, k in kN1 | sum1 + toFloat(N1[k])) as sum1,
     N2, kN2, REDUCE(sum2=0.0, k in kN2 | sum2 + toFloat(N2[k])) as sum2
WITH N1, kN1, CASE WHEN sum1 IS NULL THEN 0 ELSE sum1 END as sum1,
     N2, kN2, CASE WHEN sum2 IS NULL THEN 0 ELSE sum2 END as sum2,
     sum1 + toFloat(sum2) as total
RETURN N1, kN1, sum1,
       N2, kN2, sum2,
       sum1 + sum2 as total

Question:

I have followed this guide when creating a Spring Data Neo4j application.

I have included:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-neo4j</artifactId>
    <version>3.3.1.RELEASE</version>
</dependency>

In my pom.xml

When trying to start the server I get the following error:

"Starting Neo4j Server failed: Component 'org.neo4j.server.database.LifecycleManagingDatabase@' was successfully initialized, but failed to start."

The message log says:

"Error starting org.neo4j.kernel.EmbeddedGraphDatabase"

I have read that the Spring Data Neo4j and the Neo4j server versions might not be compatible with each other.

Question: How can I know which versions are compatible?

Stacktrace:

2015-07-09 13:03:56.231+0000 INFO  [o.n.k.EmbeddedGraphDatabase]: Shutdown started
2015-07-09 13:03:56.244+0000 ERROR [o.n.s.d.LifecycleManagingDatabase]: Failed to start database.
java.lang.RuntimeException: Error starting org.neo4j.kernel.EmbeddedGraphDatabase, D:\neo4j
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:335) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.EmbeddedGraphDatabase.<init>(EmbeddedGraphDatabase.java:59) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.server.database.LifecycleManagingDatabase$1.newGraphDatabase(LifecycleManagingDatabase.java:44) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.server.database.LifecycleManagingDatabase.start(LifecycleManagingDatabase.java:110) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.server.AbstractNeoServer.start(AbstractNeoServer.java:203) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.desktop.runtime.DatabaseActions.start(DatabaseActions.java:71) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.desktop.ui.StartDatabaseActionListener$1.run(StartDatabaseActionListener.java:61) [neo4j-desktop-2.2.3.jar:2.2.3]
at java.awt.event.InvocationEvent.dispatch(Unknown Source) [na:1.7.0_75]
at java.awt.EventQueue.dispatchEventImpl(Unknown Source) [na:1.7.0_75]
at java.awt.EventQueue.access$300(Unknown Source) [na:1.7.0_75]
at java.awt.EventQueue$3.run(Unknown Source) [na:1.7.0_75]
at java.awt.EventQueue$3.run(Unknown Source) [na:1.7.0_75]
at java.security.AccessController.doPrivileged(Native Method) [na:1.7.0_75]
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) [na:1.7.0_75]
at java.awt.EventQueue.dispatchEvent(Unknown Source) [na:1.7.0_75]
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) [na:1.7.0_75]
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) [na:1.7.0_75]
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) [na:1.7.0_75]
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [na:1.7.0_75]
at java.awt.EventDispatchThread.pumpEvents(Unknown Source) [na:1.7.0_75]
at java.awt.EventDispatchThread.run(Unknown Source) [na:1.7.0_75]
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.impl.transaction.state.DataSourceManager@5a7c7505' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.InternalAbstractGraphDatabase.run(InternalAbstractGraphDatabase.java:331) ~[neo4j-desktop-2.2.3.jar:2.2.3]
... 22 common frames omitted
Caused by: org.neo4j.kernel.lifecycle.LifecycleException: Component 'org.neo4j.kernel.NeoStoreDataSource@50f074ae' was successfully initialized, but failed to start. Please see attached cause exception.
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:513) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.lifecycle.LifeSupport.start(LifeSupport.java:115) [neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.impl.transaction.state.DataSourceManager.start(DataSourceManager.java:117) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507) [neo4j-desktop-2.2.3.jar:2.2.3]
... 24 common frames omitted
Caused by: org.neo4j.kernel.impl.storemigration.StoreUpgrader$UpgradingStoreVersionNotFoundException: 'neostore.nodestore.db' does not contain a store version, please ensure that the original database was shut down in a clean state.
at org.neo4j.kernel.impl.storemigration.UpgradableDatabase.checkUpgradeable(UpgradableDatabase.java:86) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.impl.storemigration.StoreMigrator.needsMigration(StoreMigrator.java:158) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.impl.storemigration.StoreUpgrader.getParticipantsEagerToMigrate(StoreUpgrader.java:259) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.impl.storemigration.StoreUpgrader.migrateIfNeeded(StoreUpgrader.java:134) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.NeoStoreDataSource.upgradeStore(NeoStoreDataSource.java:564) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.NeoStoreDataSource.start(NeoStoreDataSource.java:460) ~[neo4j-desktop-2.2.3.jar:2.2.3]
at org.neo4j.kernel.lifecycle.LifeSupport$LifecycleInstance.start(LifeSupport.java:507) [neo4j-desktop-2.2.3.jar:2.2.3]
... 27 common frames omitted
2015-07-09 13:03:56.244+0000 INFO  [o.n.s.CommunityNeoServer]: Successfully shutdown Neo4j Server.

Answer:

I did solve the problem by closing the stream as stated by Michael Hunger (misunderstood what was meant by shutting down the spring app).

I.e.

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appContext.xml"); context.close();

Question:

I'm constructing graph database of dbpedia - 2014 it consists of about 60GB triple text files. What would be time and memory effective solution for this? My machine has:

  1. RAM - 8gb
  2. CPU - 2.20 ghz
  3. HD - 500 GB (HDD)

Answer:

Use this project: https://github.com/mirkonasato/graphipedia

Then your computer is enough, just make sure to use a SSD.