当前位置:   article > 正文

【neo4j学习】入门demo_neo4j demo

neo4j demo

官方介绍

https://neo4j.com/docs/developer-manual/current/cypher/clauses/

https://neo4j.com/developer/data-modeling/

When using Maven, add the following block to your pom.xml file. Note the placeholder for the driver version. You will have to find out the exact patch version that you wish to install.

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.neo4j.driver</groupId>
  4. <artifactId>neo4j-java-driver</artifactId>
  5. <version>$JAVA_DRIVER_VERSION</version>
  6. </dependency>
  7. </dependencies>

 

  1. import org.neo4j.driver.v1.*;
  2. import static org.neo4j.driver.v1.Values.parameters;
  3. public class HelloWorldExample implements AutoCloseable
  4. {
  5. private final Driver driver;
  6. public HelloWorldExample( String uri, String user, String password )
  7. {
  8. driver = GraphDatabase.driver( uri, AuthTokens.basic( user, password ) );
  9. }
  10. @Override
  11. public void close() throws Exception
  12. {
  13. driver.close();
  14. }
  15. public void printGreeting( final String message )
  16. {
  17. try ( Session session = driver.session() )
  18. {
  19. String greeting = session.writeTransaction( new TransactionWork<String>()
  20. {
  21. @Override
  22. public String execute( Transaction tx )
  23. {
  24. StatementResult result = tx.run( "CREATE (a:Greeting) " +
  25. "SET a.message = $message " +
  26. "RETURN a.message + ', from node ' + id(a)",
  27. parameters( "message", message ) );
  28. return result.single().get( 0 ).asString();
  29. }
  30. } );
  31. System.out.println( greeting );
  32. }
  33. }
  34. public static void main( String... args ) throws Exception
  35. {
  36. try ( HelloWorldExample greeter = new HelloWorldExample( "bolt://localhost:7687", "neo4j", "password" ) )
  37. {
  38. greeter.printGreeting( "hello, world" );
  39. }
  40. }
  41. }
  1. public boolean addItem()
  2. {
  3. try ( Session session = driver.session() )
  4. {
  5. return session.writeTransaction( new TransactionWork<Boolean>()
  6. {
  7. @Override
  8. public Boolean execute( Transaction tx )
  9. {
  10. tx.run( "CREATE (a:Item)" );
  11. return true;
  12. }
  13. } );
  14. }
  15. catch ( ServiceUnavailableException ex )
  16. {
  17. return false;
  18. }
  19. }

 

  1. public void addPerson(String name)
  2. {
  3. try ( Session session = driver.session() )
  4. {
  5. session.run("CREATE (a:Person {name: $name})", parameters( "name", name ) );
  6. }
  7. }

 

  1. public void addPerson( final String name )
  2. {
  3. try ( Session session = driver.session() )
  4. {
  5. session.writeTransaction( new TransactionWork<Integer>()
  6. {
  7. @Override
  8. public Integer execute( Transaction tx )
  9. {
  10. return createPersonNode( tx, name );
  11. }
  12. } );
  13. }
  14. }
  15. private static int createPersonNode( Transaction tx, String name )
  16. {
  17. tx.run( "CREATE (a:Person {name: $name})", parameters( "name", name ) );
  18. return 1;
  19. }
  1. public List<String> getPeople()
  2. {
  3. try ( Session session = driver.session() )
  4. {
  5. return session.readTransaction( new TransactionWork<List<String>>()
  6. {
  7. @Override
  8. public List<String> execute( Transaction tx )
  9. {
  10. return matchPersonNodes( tx );
  11. }
  12. } );
  13. }
  14. }
  15. private static List<String> matchPersonNodes( Transaction tx )
  16. {
  17. List<String> names = new ArrayList<>();
  18. StatementResult result = tx.run( "MATCH (a:Person) RETURN a.name ORDER BY a.name" );
  19. while ( result.hasNext() )
  20. {
  21. names.add( result.next().get( 0 ).asString() );
  22. }
  23. return names;
  24. }

 

  1. public int addEmployees( final String companyName )
  2. {
  3. try ( Session session = driver.session() )
  4. {
  5. int employees = 0;
  6. List<Record> persons = session.readTransaction( new TransactionWork<List<Record>>()
  7. {
  8. @Override
  9. public List<Record> execute( Transaction tx )
  10. {
  11. return matchPersonNodes( tx );
  12. }
  13. } );
  14. for ( final Record person : persons )
  15. {
  16. employees += session.writeTransaction( new TransactionWork<Integer>()
  17. {
  18. @Override
  19. public Integer execute( Transaction tx )
  20. {
  21. tx.run( "MATCH (emp:Person {name: $person_name}) " +
  22. "MERGE (com:Company {name: $company_name}) " +
  23. "MERGE (emp)-[:WORKS_FOR]->(com)",
  24. parameters( "person_name", person.get( "name" ).asString(), "company_name",
  25. companyName ) );
  26. return 1;
  27. }
  28. } );
  29. }
  30. return employees;
  31. }
  32. }
  33. private static List<Record> matchPersonNodes( Transaction tx )
  34. {
  35. return tx.run( "MATCH (a:Person) RETURN a.name AS name" ).list();
  36. }

【学习创建方式】

  1. class TwitterNeo4jWriter {
  2. static String STATEMENT = "UNWIND {tweets} AS t\n" +
  3. "WITH t,\n" +
  4. " t.entities AS e,\n" +
  5. " t.user AS u,\n" +
  6. " t.retweeted_status AS retweet\n" +
  7. "WHERE t.id is not null " +
  8. "MERGE (tweet:Tweet {id:t.id})\n" +
  9. "SET tweet.text = t.text,\n" +
  10. " tweet.created = t.created_at,\n" +
  11. " tweet.favorites = t.favorite_count\n" +
  12. "MERGE (user:User {screen_name:u.screen_name})\n" +
  13. "SET user.name = u.name,\n" +
  14. " user.location = u.location,\n" +
  15. " user.followers = u.followers_count,\n" +
  16. " user.following = u.friends_count,\n" +
  17. " user.statuses = u.statuses_count,\n" +
  18. " user.profile_image_url = u.profile_image_url\n" +
  19. "MERGE (user)-[:POSTED]->(tweet)\n" +
  20. "FOREACH (h IN e.hashtags |\n" +
  21. " MERGE (tag:Tag {name:LOWER(h.text)})\n" +
  22. " MERGE (tag)<-[:TAGGED]-(tweet)\n" +
  23. ")\n" +
  24. "FOREACH (u IN [u IN e.urls WHERE u.expanded_url IS NOT NULL] |\n" +
  25. " MERGE (url:Link {url:u.expanded_url})\n" +
  26. " MERGE (tweet)-[:LINKED]->(url)\n" +
  27. ")\n" +
  28. "FOREACH (m IN e.user_mentions |\n" +
  29. " MERGE (mentioned:User {screen_name:m.screen_name})\n" +
  30. " ON CREATE SET mentioned.name = m.name\n" +
  31. " MERGE (tweet)-[:MENTIONED]->(mentioned)\n" +
  32. ")\n" +
  33. "FOREACH (r IN [r IN [t.in_reply_to_status_id] WHERE r IS NOT NULL] |\n" +
  34. " MERGE (reply_tweet:Tweet {id:r})\n" +
  35. " MERGE (tweet)-[:REPLIED_TO]->(reply_tweet)\n" +
  36. ")\n" +
  37. "FOREACH (retweet_id IN [x IN [retweet.id] WHERE x IS NOT NULL] |\n" +
  38. " MERGE (retweet_tweet:Tweet {id:retweet_id})\n" +
  39. " MERGE (tweet)-[:RETWEETED]->(retweet_tweet)\n" +
  40. ")";
  41. private Driver driver;
  42. public TwitterNeo4jWriter(String neo4jUrl) throws URISyntaxException {
  43. URI boltUri = new URI(neo4jUrl);
  44. String[] authInfo = boltUri.getUserInfo().split(":");
  45. driver = GraphDatabase.driver(boltUri, AuthTokens.basic(authInfo[0], authInfo[1]));
  46. }
  47. public void init() {
  48. try (Session session = driver.session()) {
  49. session.run("CREATE CONSTRAINT ON (t:Tweet) ASSERT t.id IS UNIQUE");
  50. session.run("CREATE CONSTRAINT ON (u:User) ASSERT u.screen_name IS UNIQUE");
  51. session.run("CREATE CONSTRAINT ON (t:Tag) ASSERT t.name IS UNIQUE");
  52. session.run("CREATE CONSTRAINT ON (l:Link) ASSERT l.url IS UNIQUE");
  53. }
  54. }
  55. public void close() {
  56. driver.close();
  57. }
  58. public int insert(List<String> tweets, int retries) {
  59. while (retries > 0) {
  60. try (Session session = driver.session()) {
  61. Gson gson = new Gson();
  62. List<Map> statuses = tweets.stream().map((s) -> gson.fromJson(s, Map.class)).collect(toList());
  63. long time = System.nanoTime();
  64. ResultSummary result = session.run(STATEMENT, Values.parameters("tweets", statuses)).consume();
  65. int created = result.counters().nodesCreated();
  66. System.out.println(created+" in "+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime()-time)+" ms");
  67. System.out.flush();
  68. return created;
  69. } catch (Exception e) {
  70. System.err.println(e.getClass().getSimpleName() + ":" + e.getMessage()+" retries left "+retries);
  71. retries--;
  72. }
  73. }
  74. return -1;
  75. }
  76. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/727664
推荐阅读
相关标签
  

闽ICP备14008679号