Search code examples
neo4j-ogm

In neo4j-ogm how do I retrieve one single object from the graph by an object attribute query?


I tried to query for an object using

val query = new java.lang.String("MATCH (n:MicroConfig) WHERE n.nodeId = {nodeId} RETURN n LIMIT 1")
val parameters = new java.util.HashMap[String, String]()
parameters.put("nodeId", nodeId)
val all = session.queryForObject(new MicroConfig().getClass, query, parameters)

However it returns a GraphModel, not the MicroConfig class I wanted back.


Solution

  • Checking Assumptions:

    First, is MicroConfig a class that is managed by the OGM (i.e. Does it appear in a package that is supplied to the SessionFactory constructor)?

    Second, is your query wanting to check ID(n) = {nodeId}? This will check that the Neo4j internal ID is matches the supplied nodeId argument. Otherwise this must be an actual property on the class MicroConfig.

    Potential solutions:

    With the current API you could do this in two ways:

    1. Use a Filter and return only one item from the Collection. You can do something like:

      val microConfig = session.loadAll(classOf[MicroConfig], new Filter("nodeId", nodeId)).lift(0)
      
    2. Double check the Scala class going in to the session.queryForObject. Keep your existing query but use classOf[MicroConfig] instead of new MicroConfig().getClass.