Last active
March 18, 2019 12:36
-
-
Save latant/cd9cf4a2c9dd7979f51fa4ad2033ca0d to your computer and use it in GitHub Desktop.
Template functions for the most common neo4j queries using erictsangx/kotlin-neo4j
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import github.etx.neo4j.CursorWrapper | |
import github.etx.neo4j.NeoQuery | |
import github.etx.neo4j.destruct | |
import github.etx.neo4j.DefaultNeoSerializer | |
val driver: Driver = GraphDatabase.driver( | |
"bolt://localhost", | |
AuthTokens.basic("neo4j", "demo") | |
) | |
val neo = NeoQuery(driver, DefaultNeoSerializer()) | |
inline fun <reified T> CursorWrapper.convertAll(key: String) = | |
map { mapper.convertValue<T>(it.unwrap(key).asMap(), T::class.java) } | |
inline fun <reified T> node(id: String, kv: Map<String,Any>): String { | |
val props = kv.entries.joinToString { "${it.key}:{${it.value}}" } | |
val cname = T::class.java.simpleName | |
return "($id:$cname{$props})" | |
} | |
inline fun <reified T> node(id: String, k: Iterable<String>): String { | |
val props = k.joinToString { "$it:{$it}"} | |
val cname = T::class.java.simpleName | |
return "($id:$cname{$props})" | |
} | |
inline fun <reified T> NeoQuery.getAll(vararg kv: Pair<String,Any>): Sequence<T> { | |
val map = mapOf(*kv) | |
return submit("match ${node<T>("r", map.keys)} return r", map).convertAll<T>("r") | |
} | |
inline fun <reified T> NeoQuery.getOne(vararg kv: Pair<String,Any>): T? { | |
return getAll<T>(*kv).firstOrNull() | |
} | |
inline fun <reified T> NeoQuery.exists(vararg kv: Pair<String, Any>): Boolean { | |
val map = mapOf(*kv) | |
return submit("match ${node<T>("u", map.keys)} return count(u) > 0", map).unwrap("u").bool | |
} | |
inline fun <reified T: Any> NeoQuery.createNode(vararg nodes: T) { | |
nodes.forEach { n -> submit("create ${node<T>("", propNamesOf<T>())}", n.destruct()) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment