How to create Dynamic Query in neo4j
Posted By : Md Qasim Siddiqui | 10-Mar-2015
Hi guys In this blog I will explain how to build Dynamic query in neo4j. This will blog will surely help you if you want to build conditonal part in neo4j query or entire query.
For example: if you want to build query (“match (n:Entity) where n.a=true AND n.b=true return n”).
Or suppose your first part of query is “match (n:Entity1)-[r]->(m:Entity2)” and you have map with parameters then checkout this code:
def dynamicQuery(){
def map = [:]
map.isExist = params.isExist as boolean
map.isActive = params.isActive as boolean
String entity = params.entity
String query = params.query
buildDynamicQuery(map,entity,query)
respond ControllerUtils.generateSuccessResponse("SUCCESS")
}
This method have parameters , name of the entity and query .
Note: param.query may be null.
def buildDynamicQuery(Map param,String entity,String query){
def map = [:]
def entityList = []
String dynQuery
StringBuilder conditionBuilder = new StringBuilder()
String node = "nodeAlias"
param.each{
conditionBuilder.append(node).append(".").append(it).append(" AND ")
}
String conditionBuilderString = conditionBuilder.toString()
conditionBuilderString = conditionBuilderString.substring(0,conditionBuilderString.lastIndexOf('AND'))
if(query){
dynQuery = query+" where "+conditionBuilderString+" return nodeAlias"
}else{
dynQuery = "Match (nodeAlias:"+entityName+") where "+conditionBuilderString+" return nodeAlias"
}
def result = dynamicQuery(dynQuery,map)
return result
}
Building dynamic query method will return nodes you can convert nodes to entity by using -
neo4jTemplate.convert(node,entityName) which will return domain.
Hope this blog helps you to build dynamic query.
THANKS
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Md Qasim Siddiqui
Qasim is an experienced web app developer with expertise in groovy and grails,Hadoop , Hive, Mahout, AngularJS and Spring frameworks. He likes to listen music in idle time and plays counter strike.