Select a node by name in NEO4J in Java

2020-02-14 08:05发布

问题:

I am working in NEO4J embedded in Java. Say there is a node named NODE_abc and it has a few properties. I want to select the node so that i can get the properties using getProperty().

I want to select the NODE_abc as mynode so that i can use mynode.getProperty() to get the properties of the node "NODE_abc".

The name of node "NODE_abc" is stored in a variable, say String str="NODE_abc"

回答1:

I agree with tstorms about indexing and execution of cypher queries. I would point out, however, that node identifiers are ephemeral. They are useful within a limited time window, but then are recycled. So, a node will not necessarily have the same identifier over multiple executions (or once the garbage collector has run).

Generally, in Neo4J, if you need to query nodes by properties (and not through traversal), you create an index. For example, you could create an index named "actors":

IndexManager index = graphDb.index();
Index<Node> actors = index.forNodes( "actors" );

If the index does not exist, this command will create it. Otherwise, it returns the existing index.

However, unlike SQL, in Neo4J you must manually add the node to the index:

Node reeves = graphDb.createNode();
reeves.setProperty( "name", "Keanu Reeves" );
actors.add( reeves, "name", reeves.getProperty( "name" ) );

You can then query the index for all nodes that match the specified query (indices do not guarantee uniqueness):

IndexHits<Node> hits = actors.get( "name", "Keanu Reeves" );
Node reeves = hits.getSingle();

Source: https://neo4j.com/docs/java-reference/current/indexing/#indexing-create

Note that Neo4J indices don't actually read properties from the node, you must explicitly tell it how to index the node. You could provide an arbitrary piece of information on which to index that isn't stored on the node, but I wouldn't recommend it.



回答2:

Not sure what you mean with a node named "node_abc". Nodes do not have a name, but a unique id (=identifier) which you can get by node.getId(). So my guess is that you have nodes with a name property. If you have an index on the name property, than you could retrieve it via the index (indexing search). If you have the identifier of the node, you can also retrieve it via a CYPHER query (executing cypher queries).