Using indexes
It is possible to create and use all the index types described in Cypher Manual → Indexes.
This section demonstrates how to work with indexes with an example of a user database.
For information about how to create an index on all User nodes that have a username property, see Cypher Manual → Create a single-property index for nodes.
|
The source code used in this example is found at: EmbeddedNeo4jWithIndexing.java |
Begin with starting the database server:
DatabaseManagementService managementService = new DatabaseManagementServiceBuilder( databaseDirectory ).build();
GraphDatabaseService graphDb = managementService.database( DEFAULT_DATABASE_NAME );
Then, you can configure the database to index users by name. This only needs to be done once.
|
Note that schema changes and data changes are not allowed in the same transaction. Each transaction must either change the schema or the data, but not both. |
IndexDefinition usernamesIndex;
try ( Transaction tx = graphDb.beginTx() )
{
Schema schema = tx.schema();
usernamesIndex = schema.indexFor( Label.label( "User" ) ) (1)
.on( "username" ) (2)
.withName( "usernames" ) (3)
.create(); (4)
tx.commit(); (5)
}
| 1 | A single-property index is defined on a label in combination with a property name. Start your index definition by specifying the node label. |
| 2 | Next, define the property that should be part of this index.
Index all nodes with the User label, that also have a username property.
This way, you can find User nodes by their username properties. |
| 3 | An index always has a name. If not specified, it will be generated for you. |
| 4 | Calling create is necessary for the index definition to be created in the database.
This index is now created, but it still only exists in your current transaction. |