Spring 数据 | Neo4J |以正确的顺序查询路径

Spring Data | Neo4J | Querying for the path in the correct order

版本:

<dependency>
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-core</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency> <!-- If you're using the HTTP driver -->
            <groupId>org.neo4j</groupId>
            <artifactId>neo4j-ogm-http-driver</artifactId>
            <version>2.1.1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-neo4j -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-neo4j</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>

这是我的实体:

@Data
@NodeEntity
@EqualsAndHashCode(exclude = {"operatedByBuses"})
@ToString(of = {"name"})
public class BusStop {
    @GraphId
    private Long graphId;

    @Index(unique = true, primary = true)
    private String name;

    private String pincode;

    private String landmark;

    private String[] latlong;

    @Relationship(type = "OPERATED_BY")
    private Set<OperatedByBus> operatedByBuses = new HashSet<>();
}

@Data
@RelationshipEntity(type = "OPERATED_BY")
@ToString(of = "displayName")
public class OperatedByBus {

    @GraphId
    private Long id;

    @StartNode
    private BusStop origin;

    @EndNode
    private BusStop destination;
}

我正在尝试获取 A 和 D 之间的路线,为此我需要按正确顺序将结果作为 A、B、C 和 D,然后我将获取每个对象中的公共汽车。

这是我的密码:

String findBuses = "MATCH p=shortestPath((o:BusStop)-[buses*1..40]->(d:BusStop))\n" +
                "WHERE o.name =~ '(?i).*ABC Bus Stand.*'\n" +
                "  AND d.name =~ '(?i).*XYZ Bus Stand.*'\n" +
                "RETURN p";

        Iterable<BusStop> busstops = session.query(BusStop.class, findBuses, Collections.emptyMap());
        System.out.println(busstops);

        for (BusStop busStop : busstops) {
            System.out.println(busStop.getName());
            System.out.println("\t " + busStop.getOperatedByBuses());
        }

但是结果顺序不对。我将结果视为 D、C、A、B(或某种随机顺序),而不是 A、B、C、D。

我能想到的一种方法是向 OperatedByBus 添加一个属性,比如 int legId,然后在我的查询中按 legId 排序。不确定这是否是最好的方法。

有什么我想念的吗?

修改您的查询如下:

MATCH p=shortestPath((o:BusStop)-[buses*1..40]->(d:BusStop))
WHERE 
  o.name =~ '(?i).*ABC Bus Stand.*' AND
  d.name =~ '(?i).*XYZ Bus Stand.*'
RETURN nodes(p) as busStops,relationships(p)

请注意,当 where 子句匹配多个节点时,您的查询可能 return 多行。

然后改用session.query(findBuses, Collections.emptyMap());。结果类型为 org.neo4j.ogm.model.Result,使用以下获取单个结果:

Iterable<Map<String, Object>> result.queryResults();
.. iterate over results
   // to get a `busStops` for single path as collection, which should be in order
   .. (Collection<BusStop>) item.get("busStops");