Database Reference
In-Depth Information
the
GraphDatabaseService.schema()
method. First, you create an index for the
MOVIE
label on the
name
property , then you do the same for the
USER
label .
Note that this code is wrapped in its own transaction, separate from the remainder of the
example. That's because this code would typically only be done once upfront in the ap-
plication. More importantly, you'll get an exception if you try to do this all in one trans-
action—something along the lines of “org.neo4j.graphdb.Constraint-ViolationException:
Cannot perform data updates in a transaction that has performed schema updates.”
Having defined the indexes, you can now continue to create some nodes. First you create
a node for the movie “Michael Collins” with the
MOVIE
label . Because the movie's
label and property
name
match the index you've already defined, this node will automat-
icallybeindexedandbesearchable byitsname.Next,justforfun,youcreateauserwhose
name is “Michael Collins”, the same as the movie name
, then commit the transaction.
Provided all has gone according to plan, you can realistically now expect that your
nodes have been indexed. You can verify that by searching for the “Michael Collins”
movie. To search the schema index, you use the
GraphDatabaseSer-
vice.findNodesByLabelAndProperty(...)
method .Asitsnamesuggests,
this method will perform the search across all nodes for the label and property values sup-
plied.Inthiscase,youwanttosearchacrossthe
MOVIE
labelwitha
name
propertymatch-
ing the value “Michael Collins”. The returned result is a Java
Iterable
containing the
matchingnodes.You'dexpectexactlyoneresultfromthissearch.Youhavetwonodeswith
the same name, “Michael Collins”, but only one has the
MOVIE
label, and this is the one
you expect to get. The assertion proves that the result is correct
.
Every node can have one or more labels attached, each with an index defined. If the node
has multiple labels, Neo4j will ensure that all relevant indexes are updated as required.
Here is an illustration.