Hot questions for Using Neo4j in graphaware

Top Java Programmings / Neo4j / graphaware

Question:

I'm writing some unit tests and want to use TimeTree along with Spring repositories, to auto attach event nodes to a time tree. Something like this issue, but I'm using boot 2.0 and SDN5. I think my main issue is I don't know how to set up the configuration so my repositories and my TimeTree use the same GraphDatabaseService. My @Confuration is like this:

    @Configuration
    public class SpringConfig {

        @Bean
        public SessionFactory sessionFactory() {
            // with domain entity base package(s)
            return new SessionFactory(configuration(), "org.neo4j.boot.test.domain");
        }

        @Bean
        public org.neo4j.ogm.config.Configuration configuration() {
            return new org.neo4j.ogm.config.Configuration.Builder()
                .uri("bolt://localhost")
                .build();
        }

        @Bean
        public Session getSession() {
            return sessionFactory().openSession();
        }

        @Bean
        public GraphDatabaseService graphDatabaseService() {
            return new GraphDatabaseFactory()
                .newEmbeddedDatabase(new File("/tmp/graphDb"));
        }

        @Bean
        public GraphAwareRuntime graphAwareRuntime() {
            GraphDatabaseService graphDatabaseService = graphDatabaseService();
            GraphAwareRuntime runtime = GraphAwareRuntimeFactory
                .createRuntime(graphDatabaseService);

            runtime.registerModule(new TimeTreeModule("timetree",
                TimeTreeConfiguration
                    .defaultConfiguration()
                    .withAutoAttach(true)
                    .with(new NodeInclusionPolicy() {
                        @Override
                        public Iterable<Node> getAll(GraphDatabaseService graphDatabaseService) {
                            return null;
                        }

                        @Override
                        public boolean include(Node node) {
                            return node.hasLabel(Label.label("User"));
                        }
                    })
                    .withRelationshipType(RelationshipType.withName("CREATED_ON"))
                    .withTimeZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+1")))
                    .withTimestampProperty("createdOn")
                    .withResolution(Resolution.DAY)
    //                      .withCustomTimeTreeRootProperty("timeTreeName")
                    .withResolution(Resolution.HOUR), graphDatabaseService));
            runtime.start();
            return runtime;
        }
    }

And my test looks like this:

    User user = new User("Michal");
    user.setCreatedOn(1431937636995l);
    userRepository.save(user);

    GraphUnit.assertSameGraph(graphDb, "CREATE (u:User {name:'Michal', createdOn:1431937636995})," +
            "(root:TimeTreeRoot)," +
            "(root)-[:FIRST]->(year:Year {value:2015})," +
            "(root)-[:CHILD]->(year)," +
            "(root)-[:LAST]->(year)," +
            "(year)-[:FIRST]->(month:Month {value:5})," +
            "(year)-[:CHILD]->(month)," +
            "(year)-[:LAST]->(month)," +
            "(month)-[:FIRST]->(day:Day {value:18})," +
            "(month)-[:CHILD]->(day)," +
            "(month)-[:LAST]->(day)," +
            "(day)<-[:CREATED_ON]-(u)"
    );

    GraphUnit.printGraph(graphDb);
    graphDb.shutdown();

There's a host of errors, but I think they all stem from this one:

Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to 
instantiate [org.springframework.data.repository.support.Repositories]: 
Factory method 'repositories' threw exception; nested exception is 
org.springframework.beans.factory.UnsatisfiedDependencyException: Error 
creating bean with name 'userRepository': Unsatisfied dependency 
expressed through method 'setSession' parameter 0; nested exception is 
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No 
qualifying bean of type 'org.neo4j.ogm.session.Session' available: 
expected single matching bean but found 2: getSession,
org.springframework.data.neo4j.transaction.SharedSessionCreator#0

Answer:

It is because the configuration class redefines some beans already automatically configured by Spring boot (here the Session).

So spring injection does not know how to choose between the 2. Removing the getSession() should help.

A second thing is that your SessionFactory has to use the embedded DB setup in the graphDatabaseService() method. For this, configure an embedded driver with the existing database.

Summary config that should work fine for you :

@Bean
public SessionFactory sessionFactory() {
    EmbeddedDriver driver = new EmbeddedDriver(graphDatabaseService());
    return new SessionFactory(driver, "org.neo4j.boot.test.domain");
}

@Bean
public PlatformTransactionManager transactionManager() {
    return new Neo4jTransactionManager(sessionFactory());
}

@Bean
public GraphDatabaseService graphDatabaseService() {
    return new TestGraphDatabaseFactory().newImpermanentDatabaseBuilder().newGraphDatabase();
}

@Bean
public GraphAwareRuntime graphAwareRuntime() {
    ...

Question:

In a standalone version of Neo4j database server, there's this plugin folder in which I can copy APOC library and then use its awesome functions in my queries. Right now, I'm trying to do the same in a test Java project which instantiates an embedded version of Neo4j, using the Graphaware framework.

My question is, how can I feed the APOC library to the embedded version of the Neo4j when it is setup 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();
    }
}

?


Answer:

You have to register the procedure classes that you want to use during your test.

An example is in the APOC TestUtil :

https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/3.0/src/test/java/apoc/util/TestUtil.java#L89

Question:

I want to run neo4j-reco README exmple with standalone server.

How can I change it to use and connect to my external neo4j server?


Answer:

You can deploy the recommendation engine jar as well as the corresponding version to your neo4j standalone server.

Then you can create a stored procedure attached to the engine so you can request recommendations via Cypher.

There is an example of the procedure here :

https://github.com/graphaware/recommendations-meetup/blob/master/src/main/java/com/graphaware/meetup/procedure/MeetupRecommendationProcedure.java

And the corresponding integration test :

https://github.com/graphaware/recommendations-meetup/blob/master/src/test/java/com/graphaware/meetup/MyRecommendationEngineIntegrationTest.java#L72

Question:

This is my pom.xml file,

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>neo4j.embedded.myserver</groupId>
<artifactId>myserver</artifactId>
<packaging>jar</packaging>
<properties>
<java.version>1.7</java.version>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<version>1.0-SNAPSHOT</version>
<name>myserver</name>
<url>http://maven.apache.org</url>
<dependencies>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j</artifactId>
        <version>2.2.4</version>
    </dependency>
    <dependency>
        <groupId>com.sun.jersey</groupId>
        <artifactId>jersey-client</artifactId>
        <version>1.8</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.core</groupId>
        <artifactId>jersey-client</artifactId>
        <version>2.13</version>
    </dependency>
    <dependency>
        <groupId>org.neo4j</groupId>
        <artifactId>neo4j-kernel</artifactId>
        <version>2.2.4</version>
        <type>test-jar</type>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
        <scope>test</scope>
    </dependency>  
    <dependency>
        <groupId>com.graphaware.neo4j</groupId>
        <artifactId>tests</artifactId>
        <version>2.1.5.25</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-neo4j</artifactId>
        <version>1.0.0</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20140107</version>
    </dependency>
</dependencies>
</project>

And I use eclipse , use run as→maven build , this is my error information,

Results :

Tests in error: nodeCreationWithLabel(neo4j.tests.Neo4jTest): org/neo4j/kernel/impl/util/function/Optionals$LazyOptional nodeCreationWithLabel(neo4j.tests.Neo4jTest) compareProperties(neo4j.tests.Neo4jTest): org/neo4j/kernel/impl/cache/HPCSettingFunctions$4 compareProperties(neo4j.tests.Neo4jTest) compareNeo4jDatabase(neo4j.tests.Neo4jTest): org/neo4j/kernel/impl/cache/HPCSettingFunctions$4 compareNeo4jDatabase(neo4j.tests.Neo4jTest)

Tests run: 6, Failures: 0, Errors: 6, Skipped: 0

[INFO] ------------------------------------------------------------------------

[INFO] BUILD FAILURE

[INFO] ------------------------------------------------------------------------

[INFO] Total time: 2.838 s

[INFO] Finished at: 2015-10-28T16:14:21+08:00

[INFO] Final Memory: 11M/28M

[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project myserver: There are test failures.

[ERROR]

[ERROR] Please refer to D:\Eclipse\workspace\MyNeo4jSamples\target\surefire-reports for the individual test results.

[ERROR] -> [Help 1]

[ERROR]

[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.

[ERROR] Re-run Maven using the -X switch to enable full debug logging.

[ERROR]

[ERROR] For more information about the errors and possible solutions, please read the following articles:

[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException


Answer:

You are using Neo4j and GraphAware framework.

GraphAware framework version is coupled with Neo4j version.

Neo4j - 2.2.4 GraphAware Framework - 2.1.5.25 (here is the problem)

You should use version 2.2.4.34 of GraphAware Framework.

Question:

I'm giving the GraphAware's example a try to understand how it works. But I'm having trouble running their friendship counter example.

To this end, I've built the mentioned example package using mvn package which generated the following jar files:

  • friendship-strength-counter-module-3.1.0.45-SNAPSHOT.jar
  • friendship-strength-counter-module-3.1.0.45-SNAPSHOT-javadoc.jar
  • friendship-strength-counter-module-3.1.0.45-SNAPSHOT-sources.jar
  • graphaware-friendship-strength-counter-module-3.1.0.45-SNAPSHOT.jar

Then I copied the first file alongside GraphAware framework-server-community's latest version into the plugins directory of the neo4j. Then I added the following line to neo4j.conf file:

dbms.unmanaged_extension_classes=com.graphaware.server=/graphaware

and restarted the neo4j server. When I go to http://localhost:7474/graphaware/friendship/strength I can see that the REST API part of the code is working since it returns 0 and also it creates a :FriendshipCounter node on the server.

But it seems that the FriendshipStrengthCounter class is not registered as a TransactionEventHandler since when I create the following two nodes:

CREATE (n)-[:FRIEND_OF{strength: 2}]->(m);

the counter is not updated. Can someone please tell me where did I make a mistake? Thanks.


Answer:

Can you try enabling the framework and the module by adding those lines to your neo4j.conf :

com.graphaware.runtime.enabled=true

#COUNTER becomes the module ID:
com.graphaware.module.COUNTER.1=com.graphaware.example.module.FriendshipStrengthModuleBootstrapper

Question:

I am using neo4j-reco, to pre-compute real-time recommendations.

I have a sample graph and .jar files have been placed into the plugins directory of Neo4j installation as mentioned in the readme file, but getting following error when restarting the server.

2015-12-01 15:38:35.769+0530 INFO  Neo4j Server shutdown initiated by request
15:38:35.788 [Thread-12] INFO  c.g.s.f.b.GraphAwareServerBootstrapper - stopped
2015-12-01 15:38:35.789+0530 INFO  Successfully shutdown Neo4j Server
15:38:36.399 [Thread-12] INFO  c.g.runtime.BaseGraphAwareRuntime -  Shutting down GraphAware Runtime... 
15:38:36.399 [Thread-12] INFO  c.g.r.schedule.RotatingTaskScheduler - Terminating task scheduler...
15:38:36.399 [Thread-12] INFO  c.g.r.schedule.RotatingTaskScheduler - Task scheduler terminated successfully.
15:38:36.399 [Thread-12] INFO  c.g.runtime.BaseGraphAwareRuntime - GraphAware Runtime shut down.
2015-12-01 15:38:36.405+0530 INFO  Successfully stopped database
2015-12-01 15:38:36.405+0530 INFO  Successfully shutdown database
15:38:40.041 [main] INFO  c.g.r.b.RuntimeKernelExtension - GraphAware Runtime enabled, bootstrapping...
15:38:40.069 [main] INFO  c.g.r.b.RuntimeKernelExtension - Bootstrapping module with order 1, ID reco, using com.graphaware.reco.neo4j.module.RecommendationModuleBootstrapper
15:38:40.077 [main] INFO  c.g.r.n.m.RecommendationModuleBootstrapper - Constructing new recommendation module with ID: reco
15:38:40.080 [main] INFO  c.g.r.n.m.RecommendationModuleBootstrapper - Trying to instantiate class FriendsComputingEngine
15:38:40.089 [main] ERROR c.g.r.n.m.RecommendationModuleBootstrapper - Engine FriendsComputingEngine wasn't found on the classpath. Will not pre-compute recommendations
java.lang.ClassNotFoundException: FriendsComputingEngine
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366) ~[na:1.7.0_91]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355) ~[na:1.7.0_91]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.7.0_91]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354) ~[na:1.7.0_91]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425) ~[na:1.7.0_91]
   at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) ~[na:1.7.0_91]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ~[na:1.7.0_91]
    at java.lang.Class.forName0(Native Method) ~[na:1.7.0_91]
    at java.lang.Class.forName(Class.java:195) ~[na:1.7.0_91]

How to solve this


Answer:

You need to build one first if you're referring to it in your config. If you follow the steps in the readme file you're mentioning, you will end up building one.