简体   繁体   中英

getting properties of a node in neo4j java driver

I'm using neo4j, I have linux laptop with the server of neo4j, I did all configuration, so I can access from a mac to ip/browser, after that I'm trying to use that remotely from java project I'm using java-driver because neo4j-enbedded does not seems to support remote connections, so the questions is this how can I get all nodes and print the properties:

in the code below I have match(p:Book)return p

if I try to iterate "p" I'm not getting the properties, but I'm using like

match( p:Book) return p.title, then im able to see the values of title property,

I have 3 nodes books: Book( title:"book1", author:"author1" ) Book( title:"book2", author:"author2" ) Book( title:"book3", author:"author3" )

try ( Session session = Neo4jDriver.getInstance( URI.create( "bolt://10.0.0.17:7687" ),
                "neo4j", "pass" ).session() )
        {
       StatementResult result = session.run( "match(p:Book) return p" );

 while ( result.hasNext() )
{
    Record res = result.next();

    System.err.println(" --> "+res.get(0) ); 
}  }

This is only printing something like:
->node<0>
->node<1>
->node<2>

Next you need to pull the values out of your node, something like this:

List<Pair<String,Value>> values = res.fields();
for (Pair<String,Value> nameValue: values) {
    if ("p".equals(nameValue.key())) {  // you named your node "p"
        Value value = nameValue.value();
        // print Book title and author
        String title = value.get("title").asString();
        String author = value.get("author").asString();
    }
}

If you return a node in your query, Neo4j's drivers will give you a Node object.

This object has some methods to retreive the data inside :

  • get(key) : to get the key value of the node. You will receive a Value object which has some method to cast this object to string , boolean , ...
  • contains(key) : to know if the node has a key property
  • keys() : to get the list of the node's properties
  • ...

More details can be found here : https://github.com/neo4j/neo4j-java-driver/blob/1.6/driver/src/main/java/org/neo4j/driver/v1/types/MapAccessor.java

On your example, you just print the Node object, so you are calling its toString() method, and this method doesn't print all the value of the node, but just its id.

You can use this traitement and you will get all the result within a list of Object :

String cypherQuery  = "match(p:Book) return p";
List<Map<String,Object>> nodeList=  new ArrayList<>();
StatementResult result = session .run( cypherQuery);
while (result.hasNext()) {
    nodeList.add(result.next().fields().get(0).value().asMap());
}
return nodeList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM