Java连接Neo4j,Neo4j查询实体与关系,Neo4j增加关系,Neo4j增加实体
- 第一步 添加依赖
org.neo4j.driver
neo4j-java-driver
4.2.0
- 第二步 ,建议连接{注意连接地址ip端口为Neo4j服务暴露端口7687,非可视化页面7474端口}
private static Driver driver = GraphDatabase.driver("bolt://localhost:7687", AuthTokens.basic("neo4j", "neo4j"));
- 第三部,查询
import org.neo4j.driver.*;
import org.neo4j.driver.internal.InternalNode;
import org.neo4j.driver.internal.InternalPath;
import org.neo4j.driver.internal.InternalResult;
import org.neo4j.driver.types.Node;
import org.neo4j.driver.types.Relationship;
// 非下列依赖jar
//import org.neo4j.ogm.model.Property;
//import org.neo4j.ogm.model.Result;
//import org.neo4j.ogm.response.model.NodeModel;
//import org.neo4j.ogm.session.Session;
Session session = driver.session();
Result result = null;
String neo4jCql = "match p=(a:label1:label2{propertyDemo:'propertyValue'})-[*..1]->(b:label1:label2)-[*..1]-(c:label1:label2:`label3`) return p"
String neo4jCql = "match p=(a:label1:label2{propertyDemo:'propertyValue'})<-[:`关系label`]->(b:label1:label2) return p"
// 原CQL String neo4jCql = "match p=(a:label1:label2{propertyDemo:'propertyValue',propertyDemo2:'propertyValue2'})-[*..20]->(b:label1:label2:label3{propertyDemo:'propertyValue'}) return p limit 200";
String neo4jCql = "";
if (!ObjectUtils.isEmpty(nameFrom页面传值)){
esopCql = "match p=(a:`"+页面传值label1+"`:`"+页面传值label2+"`{propertyDemo:%s"+"})-[r]->(b:`"+页面传值label1+"`:`"+页面传值label2+"`:`页面传值label3`{propertyDemo:%s"+"}) return p";
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("\"");
stringBuilder.append(nameFrom页面传值);
stringBuilder.append("\"");
esopCql = String.format(neo4jCql,stringBuilder.toString(),stringBuilder.toString());
}else {
}
result = session.run( neo4jCql);
Map returnMapForD3 = new HashMap();
Map selfPointNodesMap = new HashMap();
HashSet
- 插入关系 demo
String addRelationCypherSql = "match (startNode:`"+label1+"`:`"+label2+"`{propertyKey:%s"+"}),(endNode:`"+label1+"`:`"+label2+"`{propertyKey:%s"+"}) create (startNode)-[r:`"+关系type值+"`]->(endNode) return r ";
StringBuilder stringBuilderFrom = new StringBuilder();
stringBuilderFrom.append("\"");
stringBuilderFrom.append(from);
stringBuilderFrom.append("\"");
StringBuilder stringBuilderTo = new StringBuilder();
stringBuilderTo.append("\"");
stringBuilderTo.append(to);
stringBuilderTo.append("\"");
addRelationCypherSql = String.format(addRelationCypherSql,stringBuilderFrom.toString(),stringBuilderTo);
Result result = session.run(addRelationCypherSql);
- 增加实体 demo
// 建立实体对象类
//节点实体类
public class Neo4jBasicNode implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
private Long id;
/**
* 标签
*/
private List labels;
/**
* 标签属性
*/
private Map property;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List getLabels() {
return labels;
}
public void setLabels(List labels) {
this.labels = labels;
}
public Map getProperty() {
return property;
}
public void setProperty(Map property) {
this.property = property;
}
}
/**
* init map序列号
*/
private static final ObjectMapper mapper = new ObjectMapper();
static {
mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);
}
public static String propertiesMapToPropertiesStr(Map map) {
map.entrySet().removeIf(entry -> org.springframework.util.ObjectUtils.isEmpty(entry.getValue()));
String s = null;
try {
s = mapper.writeValueAsString(map);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return s;
}
/**
* 新增实体 拼接动态 Cql
*/
@PostMapping("/edit/add")
public AjaxResult add(@RequestBody Neo4jBasicNode neo4jBasicNode)
{
Session session = null;
int num = 0;
try {
session = driver.session();
String labels = "";
if (!ObjectUtils.isEmpty(neo4jBasicNode.getLabels())) {
labels = ":`" + String.join("`:`", neo4jBasicNode.getLabels()) + "`";
}
String property = "";
if (!ObjectUtils.isEmpty(neo4jBasicNode.getProperty())) {
property = propertiesMapToPropertiesStr(neo4jBasicNode.getProperty());
}
String cypherSql = String.format("%s(%s%s)","create", labels, property);
Result result = session.run(cypherSql);
num = 1;
} catch (Exception e) {
num = 0;
e.printStackTrace();
logger.error(e.getMessage());
} finally {
session.close();
}
return toAjax(num);
}
- 更新实体 demo
/**
* 修改实体节点
*/
@PutMapping("/edit/edit")
public AjaxResult edit(@Validated @RequestBody Neo4jBasicNode neo4jBasicNode)
{
Session session = null;
Result result = null;
int num = 0;
try {
session = driver.session();
Map propertyMap = neo4jBasicNode.getProperty();
String ID = propertyMap.get("ID")+"";
String labels = "";
if (!ObjectUtils.isEmpty(neo4jBasicNode.getLabels())) {
labels = ":`" + String.join("`:`", neo4jBasicNode.getLabels()) + "`";
}
Map noMap = new HashMap<>();
noMap.put("ID","id");
noMap.put("id","id");
noMap.put("labels","id");
String propertyStr = "SET ";
for (String key : propertyMap.keySet()) {
if (!noMap.containsKey(key+"")){
String setStr = "node."+key+"= '"+(propertyMap.get(key)+""+"',");
propertyStr+=setStr;
}
}
String propertyStrSubstring = propertyStr.substring(0, propertyStr.length() - 1);
/*if (!ObjectUtils.isEmpty(neo4jBasicNode.getProperty())) {
propertyStr = propertiesMapToPropertiesStr(neo4jBasicNode.getProperty());
}*/
String format = String.format("MATCH(%s%s)", labels, propertyStr);
String updateByParam = "MATCH (node"+labels+"{ID:'"+ID+"'}) "+propertyStrSubstring+" RETURN node";
logger.info("修改实体nodeId:====>"+(ID+"")+"{CQL}==>{"+updateByParam+"}");
result = session.run(updateByParam);
num = 1;
logger.info("修改实体nodeId:====>"+(ID+"")+"成功");
} catch (NumberFormatException e) {
num = 0;
e.printStackTrace();
logger.error(e.getMessage());
} finally {
session.close();
}
/*MATCH (node:`label1`:`label2`:`label3`{唯一属性名Key:'唯一属性名Key对应值'})
SET
node.key1= 'value1"',
node.key2= 'value2',
node.key2= 'value3'
RETURN node*/
return toAjax(num);
}