3.5. User database with explicit index

The functionality described in this section has been deprecated and will be removed in Neo4j 4.0.

Explicit indexes are deprecated and due to be removed. Please see Cypher Manual → Indexes to support full-text search to learn about using full-text schema indexes instead.

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( databaseDirectory );
        registerShutdownHook();

Now we can 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 is 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 ) );

Please read Section 3.6, “Managing resources when using long running transactions” on how to properly close ResourceIterators returned from index lookups.