gpt4 book ai didi

java - 如何确保 Neo4j 节点在同一事务内添加到索引中?

转载 作者:行者123 更新时间:2023-11-30 04:06:31 25 4
gpt4 key购买 nike

我想将节点存储到 Neo4j 中,但我不想多次存储相同的节点。为此,我使用 Neo4j 索引 API。

http://docs.neo4j.org/chunked/milestone/indexing-search.html

http://docs.neo4j.org/chunked/milestone/auto-indexing.html

但是,刚刚创建的节点并未反射(reflect)在索引中。

如何确保Neo4j节点在同一事务内添加到索引中?

package graph

import org.neo4j.graphdb.Direction
import org.neo4j.graphdb.GraphDatabaseService
import org.neo4j.graphdb.Node
import org.neo4j.graphdb.Path
import org.neo4j.graphdb.Relationship
import org.neo4j.graphdb.RelationshipType
import org.neo4j.graphdb.Transaction
import org.neo4j.graphdb.factory.GraphDatabaseFactory
import org.neo4j.graphdb.traversal.Evaluators
import org.neo4j.graphdb.traversal.TraversalDescription
import org.neo4j.graphdb.traversal.Traverser
import org.neo4j.kernel.Traversal
import scala.sys.ShutdownHookThread
import collection.JavaConversions._
import java.io.File
import scala.collection.mutable
import org.neo4j.graphdb.factory.GraphDatabaseSettings

object indextest extends App {

def deleteFileOrDirectory(file: File): Unit = {
if (!file.exists()) return ;
if (file.isDirectory()) for (child <- file.listFiles()) deleteFileOrDirectory(child)
else file.delete()
}

val GRAPHLOCATION = "/tmp/testgraph"

// setup Graph DB
deleteFileOrDirectory(new File(GRAPHLOCATION))
val graphDb = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(GRAPHLOCATION)
.setConfig(GraphDatabaseSettings.node_keys_indexable, "name")
.setConfig(GraphDatabaseSettings.node_auto_indexing, "true")
.newGraphDatabase()

// register shutdown hook thread
ShutdownHookThread {
graphDb.shutdown()
}

val tx = graphDb.beginTx
val indexManager = graphDb.index()
val nameIdsIndex = indexManager.forNodes("nameIds", Map("type" -> "exact"))

val node1 = createOrFetchNode("A")
val node2 = createOrFetchNode("A")

tx.success()
tx.finish()

def createOrFetchNode(nodeName: String) = {
val hits = nameIdsIndex.get("name", nodeName)
val node = hits.getSingle()
println(s"search for $nodeName -> list: ${hits.iterator.toList} node: $node")

if (node == null) {
val node2 = graphDb.createNode()
node2.setProperty("name", nodeName)
node2
} else node
}

}

电流输出:

search for A -> list: List() node: nullsearch for A -> list: List() node: null

预期输出:

search for A -> list: List() node: nullsearch for A -> list: List(Node[1]) node: Node[1]

我做错了什么?

最佳答案

您实际上有两个索引:auto_index,您在传递给配置时创建的(GraphDatabaseSettings.node_auto_indexing, "true"),以及第二个索引nameIdsIndex 。第二个索引是手动索引,因此您必须显式地添加和删除其中的条目。这就是为什么您在查询中找不到任何内容(不过您应该在 auto_index 中找到该节点)。

有特殊的机制来保证创建节点时的唯一性:http://docs.neo4j.org/chunked/milestone/tutorials-java-embedded-unique-nodes.html

关于java - 如何确保 Neo4j 节点在同一事务内添加到索引中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20613824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com