Neo4J工具化封装v3.0

import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.neo4j.driver.internal.value.PathValue;
import org.neo4j.driver.v1.Record;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *  @author: yanghuijuan
 *  @Date: 2020/09/22 11:05
 *  @Description:
 */ 
public class NodeUtil {

    private static Logger logger = LoggerFactory.getLogger(NodeUtil.class);

    /**
     *  records 转 map
     *
     * @param records
     * @return
     */
    public static Map>> getGrap(List records) {
        Map>> map = new HashMap<>(2);
        List nodeList = new ArrayList<>();
        List edgeList = new ArrayList<>();
        // data 为cql cypher查询语句命名的别名
        records.stream().map(e -> (PathValue) e.get("data")).map(pathValue -> pathValue.asPath()).forEach(path -> {
            nodeList.addAll(IteratorUtils.asList(path.nodes()));
            edgeList.addAll(IteratorUtils.asList(path.relationships()));
        });
        map.put("nodes",node2List((nodeList.stream().distinct().collect(Collectors.toList()))));
        map.put("edges",edge2List((edgeList.stream().distinct().collect(Collectors.toList()))));

        return map;
    }

    /**
     * nodes 转list
     *
     * @param nodes
     * @return
     */
    public static  List> node2List(List nodes) {
        List> maps = new ArrayList<>();
        nodes.forEach(node->{
            Map map = new HashMap<>();
            map.putAll(node.asMap());
            map.put("label", node.labels());
            map.put("id", node.id());
            maps.add(map);
        });

        return maps;
    }

    /**
     * Relationship 转list
     *
     * @param edges
     * @return
     */
    public static  List> edge2List(List edges) {
        List> maps = new ArrayList<>();

        edges.forEach(edge->{
            maps.add(edge2Map(edge));
        });

        return maps;
    }

    /**
     * Relationship 转 map
     *
     * @param edge
     * @return
     */
    public static  Map edge2Map(Relationship edge) {
        Map map = new HashMap<>();

        map.put("source", edge.startNodeId());
        map.put("relation", edge.type());
        map.put("target", edge.endNodeId());

        return map;
    }


}

 

你可能感兴趣的:(java,neo4j,neo4j)