分享

java连接Neo4j服务器

 木棉下的守望 2014-12-11

一:Neo4j服务器安装(参考:http://docs./server-installation.html)

1.下载Neo4j数据,我下载的版本是: neo4j-enterprise-1.8.1-windows

2.解压 neo4j-enterprise-1.8.1-windows 

3.到Neo4j的bin目录下neo4j-enterprise-1.8.1-windows\neo4j-enterprise-1.8.1\bin

4.运行 neo4j start 命令

5.打开 http://localhost:7474  看到图形化界面则安装成功!


二:测试代码(参考:http://www./2012/07/30/server-java-rest-client-example/)

测试代码总共有三个类:

CreateSimpleGraph.java  下载地址:https://github.com/neo4j/community/blob/1.8.M06/server-examples/src/main/java/org/neo4j/examples/server/CreateSimpleGraph.java
Relationship.java  下载地址:https://github.com/neo4j/community/blob/1.8.M06/server-examples/src/main/java/org/neo4j/examples/server/Relationship.java
TraversalDescription.java  下载地址:https://github.com/neo4j/community/blob/1.8.M06/server-examples/src/main/java/org/neo4j/examples/server/TraversalDescription.java


三:程序正常运行用到的jar包

1.neo4j-enterprise-1.8.1-windows\neo4j-enterprise-1.8.1\lib下所有jar包

2.自己下载的jar包

com.sun.jersey.jersey-core-1.4.0.jar

javax.ws.rs.jar

jersey-client-1.9.jar


四:程序代码

  1. package com.wzs.linux;  
  2.   
  3. public class Relationship  
  4. {  
  5.     public static final String OUT = "out";  
  6.     public static final String IN = "in";  
  7.     public static final String BOTH = "both";  
  8.     private String type;  
  9.     private String direction;  
  10.   
  11.     public String toJsonCollection()  
  12.     {  
  13.         StringBuilder sb = new StringBuilder();  
  14.         sb.append("{ ");  
  15.         sb.append(" \"type\" : \"" + type + "\"");  
  16.         if (direction != null)  
  17.         {  
  18.             sb.append(", \"direction\" : \"" + direction + "\"");  
  19.         }  
  20.         sb.append(" }");  
  21.         return sb.toString();  
  22.     }  
  23.   
  24.     public Relationship(String type, String direction)  
  25.     {  
  26.         setType(type);  
  27.         setDirection(direction);  
  28.     }  
  29.   
  30.     public Relationship(String type)  
  31.     {  
  32.         this(type, null);  
  33.     }  
  34.   
  35.     public void setType(String type)  
  36.     {  
  37.         this.type = type;  
  38.     }  
  39.   
  40.     public void setDirection(String direction)  
  41.     {  
  42.         this.direction = direction;  
  43.     }  
  44. }  

  1. import java.net.URI;  
  2. import java.net.URISyntaxException;  
  3.   
  4. import javax.ws.rs.core.MediaType;  
  5.   
  6. import com.sun.jersey.api.client.Client;  
  7. import com.sun.jersey.api.client.ClientResponse;  
  8. import com.sun.jersey.api.client.WebResource;  
  9.   
  10. public class CreateSimpleGraph  
  11. {  
  12.     private static final String SERVER_ROOT_URI = "http://localhost:7474/db/data/";  
  13.   
  14.     public static void main( String[] args ) throws URISyntaxException  
  15.     {  
  16.         checkDatabaseIsRunning();  
  17.   
  18.         // START SNIPPET: nodesAndProps  
  19.         URI firstNode = createNode();  
  20.         addProperty( firstNode, "name", "Joe Strummer" );  
  21.         URI secondNode = createNode();  
  22.         addProperty( secondNode, "band", "The Clash" );  
  23.         // END SNIPPET: nodesAndProps  
  24.   
  25.         // START SNIPPET: addRel  
  26.         URI relationshipUri = addRelationship( firstNode, secondNode, "singer",  
  27.                 "{ \"from\" : \"1976\", \"until\" : \"1986\" }" );  
  28.         // END SNIPPET: addRel  
  29.   
  30.         // START SNIPPET: addMetaToRel  
  31.         addMetadataToProperty( relationshipUri, "stars", "5" );  
  32.         // END SNIPPET: addMetaToRel  
  33.   
  34.         // START SNIPPET: queryForSingers  
  35.         findSingersInBands( firstNode );  
  36.         // END SNIPPET: queryForSingers  
  37.     }  
  38.   
  39.     private static void findSingersInBands( URI startNode )  
  40.             throws URISyntaxException  
  41.     {  
  42.         // START SNIPPET: traversalDesc  
  43.         // TraversalDescription turns into JSON to send to the Server  
  44.         TraversalDescription t = new TraversalDescription();  
  45.         t.setOrder( TraversalDescription.DEPTH_FIRST );  
  46.         t.setUniqueness( TraversalDescription.NODE );  
  47.         t.setMaxDepth( 10 );  
  48.         t.setReturnFilter( TraversalDescription.ALL );  
  49.         t.setRelationships( new Relationship( "singer", Relationship.OUT ) );  
  50.         // END SNIPPET: traversalDesc  
  51.   
  52.         // START SNIPPET: traverse  
  53.         URI traverserUri = new URI( startNode.toString() + "/traverse/node" );  
  54.         WebResource resource = Client.create()  
  55.                 .resource( traverserUri );  
  56.         String jsonTraverserPayload = t.toJson();  
  57.         ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )  
  58.                 .type( MediaType.APPLICATION_JSON )  
  59.                 .entity( jsonTraverserPayload )  
  60.                 .post( ClientResponse.class );  
  61.   
  62.         System.out.println( String.format(  
  63.                 "POST [%s] to [%s], status code [%d], returned data: "  
  64.                         + System.getProperty( "line.separator" ) + "%s",  
  65.                 jsonTraverserPayload, traverserUri, response.getStatus(),  
  66.                 response.getEntity( String.class ) ) );  
  67.         response.close();  
  68.         // END SNIPPET: traverse  
  69.     }  
  70.   
  71.     // START SNIPPET: insideAddMetaToProp  
  72.     private static void addMetadataToProperty( URI relationshipUri,  
  73.             String name, String value ) throws URISyntaxException  
  74.     {  
  75.         URI propertyUri = new URI( relationshipUri.toString() + "/properties" );  
  76.         String entity = toJsonNameValuePairCollection( name, value );  
  77.         WebResource resource = Client.create()  
  78.                 .resource( propertyUri );  
  79.         ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )  
  80.                 .type( MediaType.APPLICATION_JSON )  
  81.                 .entity( entity )  
  82.                 .put( ClientResponse.class );  
  83.   
  84.         System.out.println( String.format(  
  85.                 "PUT [%s] to [%s], status code [%d]", entity, propertyUri,  
  86.                 response.getStatus() ) );  
  87.         response.close();  
  88.     }  
  89.   
  90.     // END SNIPPET: insideAddMetaToProp  
  91.   
  92.     private static String toJsonNameValuePairCollection( String name,  
  93.             String value )  
  94.     {  
  95.         return String.format( "{ \"%s\" : \"%s\" }", name, value );  
  96.     }  
  97.   
  98.     private static URI createNode()  
  99.     {  
  100.         // START SNIPPET: createNode  
  101.         final String nodeEntryPointUri = SERVER_ROOT_URI + "node";  
  102.         // http://localhost:7474/db/data/node  
  103.   
  104.         WebResource resource = Client.create()  
  105.                 .resource( nodeEntryPointUri );  
  106.         // POST {} to the node entry point URI  
  107.         ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )  
  108.                 .type( MediaType.APPLICATION_JSON )  
  109.                 .entity( "{}" )  
  110.                 .post( ClientResponse.class );  
  111.   
  112.         final URI location = response.getLocation();  
  113.         System.out.println( String.format(  
  114.                 "POST to [%s], status code [%d], location header [%s]",  
  115.                 nodeEntryPointUri, response.getStatus(), location.toString() ) );  
  116.         response.close();  
  117.   
  118.         return location;  
  119.         // END SNIPPET: createNode  
  120.     }  
  121.   
  122.     // START SNIPPET: insideAddRel  
  123.     private static URI addRelationship( URI startNode, URI endNode,  
  124.             String relationshipType, String jsonAttributes )  
  125.             throws URISyntaxException  
  126.     {  
  127.         URI fromUri = new URI( startNode.toString() + "/relationships" );  
  128.         String relationshipJson = generateJsonRelationship( endNode,  
  129.                 relationshipType, jsonAttributes );  
  130.   
  131.         WebResource resource = Client.create()  
  132.                 .resource( fromUri );  
  133.         // POST JSON to the relationships URI  
  134.         ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )  
  135.                 .type( MediaType.APPLICATION_JSON )  
  136.                 .entity( relationshipJson )  
  137.                 .post( ClientResponse.class );  
  138.   
  139.         final URI location = response.getLocation();  
  140.         System.out.println( String.format(  
  141.                 "POST to [%s], status code [%d], location header [%s]",  
  142.                 fromUri, response.getStatus(), location.toString() ) );  
  143.   
  144.         response.close();  
  145.         return location;  
  146.     }  
  147.     // END SNIPPET: insideAddRel  
  148.   
  149.     private static String generateJsonRelationship( URI endNode,  
  150.             String relationshipType, String... jsonAttributes )  
  151.     {  
  152.         StringBuilder sb = new StringBuilder();  
  153.         sb.append( "{ \"to\" : \"" );  
  154.         sb.append( endNode.toString() );  
  155.         sb.append( "\", " );  
  156.   
  157.         sb.append( "\"type\" : \"" );  
  158.         sb.append( relationshipType );  
  159.         if ( jsonAttributes == null || jsonAttributes.length < 1 )  
  160.         {  
  161.             sb.append( "\"" );  
  162.         }  
  163.         else  
  164.         {  
  165.             sb.append( "\", \"data\" : " );  
  166.             for ( int i = 0; i < jsonAttributes.length; i++ )  
  167.             {  
  168.                 sb.append( jsonAttributes[i] );  
  169.                 if ( i < jsonAttributes.length - 1 )  
  170.                 { // Miss off the final comma  
  171.                     sb.append( ", " );  
  172.                 }  
  173.             }  
  174.         }  
  175.   
  176.         sb.append( " }" );  
  177.         return sb.toString();  
  178.     }  
  179.   
  180.     private static void addProperty( URI nodeUri, String propertyName,  
  181.             String propertyValue )  
  182.     {  
  183.         // START SNIPPET: addProp  
  184.         String propertyUri = nodeUri.toString() + "/properties/" + propertyName;  
  185.         // http://localhost:7474/db/data/node/{node_id}/properties/{property_name}  
  186.   
  187.         WebResource resource = Client.create()  
  188.                 .resource( propertyUri );  
  189.         ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )  
  190.                 .type( MediaType.APPLICATION_JSON )  
  191.                 .entity( "\"" + propertyValue + "\"" )  
  192.                 .put( ClientResponse.class );  
  193.   
  194.         System.out.println( String.format( "PUT to [%s], status code [%d]",  
  195.                 propertyUri, response.getStatus() ) );  
  196.         response.close();  
  197.         // END SNIPPET: addProp  
  198.     }  
  199.   
  200.     private static void checkDatabaseIsRunning()  
  201.     {  
  202.         // START SNIPPET: checkServer  
  203.         WebResource resource = Client.create()  
  204.                 .resource( SERVER_ROOT_URI );  
  205.         ClientResponse response = resource.get( ClientResponse.class );  
  206.   
  207.         System.out.println( String.format( "GET on [%s], status code [%d]",  
  208.                 SERVER_ROOT_URI, response.getStatus() ) );  
  209.         response.close();  
  210.         // END SNIPPET: checkServer  
  211.     }  
  212. }  

  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3. import java.util.List;  
  4.   
  5. public class TraversalDescription  
  6. {  
  7.     public static final String DEPTH_FIRST = "depth first";  
  8.     public static final String NODE = "node";  
  9.     public static final String ALL = "all";  
  10.   
  11.     private String uniqueness = NODE;  
  12.     private int maxDepth = 1;  
  13.     private String returnFilter = ALL;  
  14.     private String order = DEPTH_FIRST;  
  15.     private List<Relationship> relationships = new ArrayList<Relationship>();  
  16.   
  17.     public void setOrder( String order )  
  18.     {  
  19.         this.order = order;  
  20.     }  
  21.   
  22.     public void setUniqueness( String uniqueness )  
  23.     {  
  24.         this.uniqueness = uniqueness;  
  25.     }  
  26.   
  27.     public void setMaxDepth( int maxDepth )  
  28.     {  
  29.         this.maxDepth = maxDepth;  
  30.     }  
  31.   
  32.     public void setReturnFilter( String returnFilter )  
  33.     {  
  34.         this.returnFilter = returnFilter;  
  35.     }  
  36.   
  37.     public void setRelationships( Relationship... relationships )  
  38.     {  
  39.         this.relationships = Arrays.asList( relationships );  
  40.     }  
  41.   
  42.     public String toJson()  
  43.     {  
  44.         StringBuilder sb = new StringBuilder();  
  45.         sb.append( "{ " );  
  46.         sb.append( " \"order\" : \"" + order + "\"" );  
  47.         sb.append( ", " );  
  48.         sb.append( " \"uniqueness\" : \"" + uniqueness + "\"" );  
  49.         sb.append( ", " );  
  50.         if ( relationships.size() > 0 )  
  51.         {  
  52.             sb.append( "\"relationships\" : [" );  
  53.             for ( int i = 0; i < relationships.size(); i++ )  
  54.             {  
  55.                 sb.append( relationships.get( i )  
  56.                         .toJsonCollection() );  
  57.                 if ( i < relationships.size() - 1 )  
  58.                 { // Miss off the final comma  
  59.                     sb.append( ", " );  
  60.                 }  
  61.             }  
  62.             sb.append( "], " );  
  63.         }  
  64.         sb.append( "\"return filter\" : { " );  
  65.         sb.append( "\"language\" : \"builtin\", " );  
  66.         sb.append( "\"name\" : \"" );  
  67.         sb.append( returnFilter );  
  68.         sb.append( "\" }, " );  
  69.         sb.append( "\"max depth\" : " );  
  70.         sb.append( maxDepth );  
  71.         sb.append( " }" );  
  72.         return sb.toString();  
  73.     }  
  74. }  


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约