Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 839
Jotschi Avatar asked Jan 21 '26 16:01

Jotschi


1 Answers

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

like image 147
troig Avatar answered Jan 23 '26 21:01

troig



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!