Jotschi
Jotschi

Reputation: 3632

Neo4j Spring Data Query Builder

Is there a way of dynamically building a cypher query using spring data neo4j?


I have a cypher query that filters my entities similar to this one:

@Query("MATCH (n:Product) WHERE n.name IN {0} return n")
findProductsWithNames(List<String> names);

@Query("MATCH (n:Product) return n")
findProductsWithNames();

When the names list is empty or null i just want to return all products. Therefore my service impl. checks the names array and calls the correct repository method. The given example is looks clean but it really gets ugly once the cypher statements are more complex and the code starts to repeat itself.

Upvotes: 3

Views: 1548

Answers (2)

Jotschi
Jotschi

Reputation: 3632

Handling paging is also possible this way:

@Test
@SuppressWarnings("unchecked")
public void testQueryBuilding() {
    String query = "MATCH (n:Product) return n";
    Result<Map<String, Object>> result = neo4jTemplate.query(query, Collections.emptyMap());
    for (Map<String, Object> r : result.slice(1, 3)) {
        Product product = (Product) neo4jTemplate.getDefaultConverter().convert(r.get("n"), Product.class);
        System.out.println(product.getUuid());
    }
}

Upvotes: 2

troig
troig

Reputation: 7212

You can create your own dynamic Cypher queries and use Neo4jOperations to execute them. Here is it an example (with a query different from your OP) that I think can ilustrate how to do that:

   @Autowired
   Neo4jOperations template;

   public User findBySocialUser(String providerId, String providerUserId) {
      String query = "MATCH (n:SocialUser{providerId:{providerId}, providerUserId:{providerUserId}})<-[:HAS]-(user) RETURN user";

      final Map<String, Object> paramsMap = ImmutableMap.<String, Object>builder().
            put("providerId", providerId).
            put("providerUserId", providerUserId).
            build();

      Map<String, Object> result = template.query(query, paramsMap).singleOrNull();
      return (result == null) ? null : (User) template.getDefaultConverter().convert(result.get("user"), User.class);
   }

Hope it helps

Upvotes: 2

Related Questions