Unless you have specific reasons to use the legacy indexing, see Section 32.4, “User database with indexes” instead.
| Note Please read Section 32.6, “Managing resources when using long running transactions” on how to properly close |
You have a user database, and want to retrieve users by name using the legacy indexing system.
| Tip The source code used in this example is found here: EmbeddedNeo4jWithIndexing.java |
We have created two helper methods to handle user names and adding users to the database:
private static String idToUserName( final int id )
{
return "user" + id + "@neo4j.org";
}
private static Node createAndIndexUser( final String username )
{
Node node = graphDb.createNode();
node.setProperty( USERNAME_KEY, username );
nodeIndex.add( node, USERNAME_KEY, username );
return node;
}
The next step is to start the database server:
graphDb = new GraphDatabaseFactory().newEmbeddedDatabase( DB_PATH ); registerShutdownHook();
It’s time to add the users:
try ( Transaction tx = graphDb.beginTx() )
{
nodeIndex = graphDb.index().forNodes( "nodes" );
// Create some users and index their names with the IndexService
for ( int id = 0; id < 100; id++ )
{
createAndIndexUser( idToUserName( id ) );
}
And here’s how to find a user by Id:
int idToFind = 45;
String userName = idToUserName( idToFind );
Node foundUser = nodeIndex.get( USERNAME_KEY, userName ).getSingle();
System.out.println( "The username of user " + idToFind + " is "
+ foundUser.getProperty( USERNAME_KEY ) );