我正在研究一个程序,该程序应该使用Dijkstra算法找到两个节点之间的最低加权路径。该过程应仅返回所有节点与特定条件匹配的路径(即,所有节点应具有具有特定值的属性)。如果路径中至少有一个节点与条件不匹配,则路径变为无效,算法应查找下一个最低加权路径。
为了实现这一目标,我使用了PathExpanderBuilder
节点过滤器,但他们似乎无法过滤任何内容。
这是我的代码:
public class Demo {
@Procedure
@Description("apoc.algo.dijkstraWithFilters(startNode, endNode, " +
"'distance', 10, 'prop1', 2, 'prop2', [100, 200], 'prop3') " +
" YIELD path, weight - run dijkstra with relationship property name as cost function" +
" and a default weight if the property does not exist")
public Stream<WeightedPathResult> dijkstraWithFilters(
@Name("startNode") Node startNode,
@Name("endNode") Node endNode,
@Name("weightPropertyName") String weightPropertyName,
@Name("defaultWeight") double defaultWeight,
@Name("longPropName") String longPropName,
@Name("longPropValue") long longPropValue,
@Name("listPropName") String listPropName,
@Name("listPropValues") List<Long> listPropValues,
@Name("boolPropName") String boolPropName) {
PathFinder<WeightedPath> algo = GraphAlgoFactory.dijkstra(
buildPathExpanderByPermissions(longPropName, longPropValue, listPropName, listPropValues, boolPropName),
(relationship, direction) -> convertToDouble(relationship.getProperty(weightPropertyName, defaultWeight))
);
return WeightedPathResult.streamWeightedPathResult(startNode, endNode, algo);
}
private double convertToDouble(Object property) {
if (property instanceof Double)
return (double) property;
else if (property instanceof Long)
return ((Long) property).doubleValue();
else if (property instanceof Integer)
return ((Integer) property).doubleValue();
return 1;
}
private PathExpander<Object> buildPathExpanderByPermissions(
String longPropName,
long longPropValue,
String listPropName,
List<Long> listPropValue,
String boolPropName
) {
PathExpanderBuilder builder = PathExpanderBuilder.allTypesAndDirections();
builder.addNodeFilter(
node -> !node.hasProperty(longPropName) ||
node.getProperty(longPropName) instanceof Long &&
(long) node.getProperty(longPropName) < longPropValue
);
builder.addNodeFilter(
node -> {
try {
return !node.hasProperty(listPropName) ||
(boolean) node.getProperty(boolPropName, false) ||
!Collections.disjoint((List<Long>) node.getProperty(listPropName), listPropValue);
}
catch (Exception e){
return false;
}
}
);
return builder.build();
}
}
我在这里缺少什么?我是否错误地使用了PathExpanderBuilder
?
答案 0 :(得分:0)
PathExpanderBuilder是不可变的,因此调用例如addNodeFilter返回一个带有添加过滤器的新PathExpanderBuilder,因此您需要为返回的实例重新分配builder
。