Orientdb--写入数据

2022-04-08 00:00:00 专区 订阅 付费 导入 斯坦福

近在调研图数据库,由于使用的是斯坦福数据(pyorientdb 不支持3.7协议,因此换成kotlin进行写入数据)。

脚本内容
class ImportListener : ApplicationListener<ApplicationReadyEvent> {

private val log = LoggerFactory.getLogger(ImportListener::class.java)

override fun onApplicationEvent(event: ApplicationReadyEvent) {
// 连接orientdb
val orientDB = OrientDB("remote:localhost", OrientDBConfig.defaultConfig())
val db = orientDB.open("pgap_test", "root", "haizhi1234")
importVer(db)
importEdge(db)
db.close()
orientDB.close()
}

// 导入边
private fun importEdge(db: ODatabaseSession) {
if (db.getClass("stf_edge") == null)
db.createEdgeClass("stf_edge")

readFileFromResources("/data/soc-pokec-relationships.txt") {
val addEdge = findVertexById(it[0], db)
addEdge?.addEdge(findVertexById(it[1], db))
addEdge?.save<OVertexDocument>()
log.info("----edge is ---${it[0]} to ${it[1]}")
}
}

// 导入边
private fun importVer(db: ODatabaseSession) {
var stfVe = db.getClass("stf")
if (stfVe == null)
stfVe = db.createVertexClass("stf")
if (stfVe.getProperty("name") == null) {
stfVe.createProperty("name", OType.STRING)
stfVe.createIndex("stf_name_index", OClass.INDEX_TYPE.NOTUNIQUE, "name")
}
if (stfVe.getProperty("id") == null) {
stfVe.createProperty("id", OType.STRING)
stfVe.createIndex("stf_id_index", OClass.INDEX_TYPE.UNIQUE, "id")
}
if (stfVe.getProperty("createTime") == null) {
stfVe.createProperty("createTime", OType.STRING)
}
if (stfVe.getProperty("endTime") == null) {
stfVe.createProperty("endTime", OType.STRING)
}
if (stfVe.getProperty("type") == null) {
stfVe.createProperty("type", OType.STRING)
}

readFileFromResources("/data/soc-pokec-profiles.txt") {
val vAddress = db.newVertex("stf")
// 创建顶点
vAddress.setProperty("id", it[0])
vAddress.setProperty("name", it[4])
vAddress.setProperty("createTime", it[5])
vAddress.setProperty("endTime", it[6])
vAddress.setProperty("type", it[7])
vAddress.save<OVertex>()
log.info("----v is ---${it[0]}")
}
}

// 读取文件
private fun readFileFromResources(path: String, apply: (List<String>) -> Unit) {
// val resourceAsStream = Thread.currentThread().contextClassLoader.getResourceAsStream(path)
val file = File(path)
// 读取
val bufferedReader = BufferedReader(InputStreamReader( FileInputStream(file)))
while (true) {
val readLine = bufferedReader.readLine()
if (StringUtils.isEmpty(readLine))
break
val split = readLine.split('\t')
apply.invoke(split)
}
}

fun findVertexById(id: String, db: ODatabaseSession): OVertex? {
val query = "select * from `stf` where id = ?"
val findFirst = db.query(query, id).vertexStream().findFirst()
if (!findFirst.isPresent) {
return null
}
return findFirst.get()
}
}

引用
官方java操作

git demo地址
demo地址

相关文章