You have a user database, and want to retrieve users by name.
| 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 ); nodeIndex = graphDb.index().forNodes( "nodes" ); registerShutdownHook();
It’s time to add the users:
Transaction tx = graphDb.beginTx();
try
{
// Create some users and index their names with the IndexService
for ( int id = 0; id < 100; id++ )
{
Node userNode = 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 ) );
Copyright © 2013 Neo Technology