在Neo4j中,如果我想查找具有最高或最低属性值的节点,可以使用Cypher关键字Order By和Limit。我想使用嵌入式API来完成相同的任务。我知道Lucene可以支持此功能,但是看不到如何使用Neo的API做到这一点。
public TopFieldDocs search(Query query, int n, Sort sort)
https://neo4j.com/docs/java-reference/current/javadocs/org/neo4j/graphdb/index/ReadableIndex.html
我调查了一下,答案是肯定的,可以做到的。中的第二个参数IndexHits<T> query( String key, Object queryOrQueryObject )
可以是可解析的(by org.apache.lucene.queryParser.QueryParser
)字符串,aorg.apache.lucene.search.Query
或aorg.neo4j.index.lucene.QueryContext
这是一个代码段,允许要求“ EntityType”属性具有特定值,要求数字属性为非空白,并返回按数字属性排序的前n个匹配。
...
List<TopNValue> values = new ArrayList<>();
QueryContext queryContext = getQueryContext(entityType, property, propertyType, n, true);
try (IndexHits<Node> indexHits = nodeIndex.query(property, queryContext))
{
for (Node node : indexHits)
{
values.add(node);
}
}
...
private static QueryContext getQueryContext(String entityType, String property, String type, int n, boolean reversed)
{
NumericRangeQuery propertyQuery;
int fieldType;
switch (type)
{
case GraphTypes.LONG:
propertyQuery = NumericRangeQuery.newLongRange(property, Long.MIN_VALUE, Long.MAX_VALUE, true, true);
fieldType = SortField.LONG;
break;
case GraphTypes.DOUBLE:
propertyQuery = NumericRangeQuery.newDoubleRange(property, Double.MIN_VALUE, Double.MAX_VALUE, true, true);
fieldType = SortField.DOUBLE;
break;
case GraphTypes.FLOAT:
propertyQuery = NumericRangeQuery.newFloatRange(property, Float.MIN_VALUE, Float.MAX_VALUE, true, true);
fieldType = SortField.FLOAT;
break;
case GraphTypes.INT:
propertyQuery = NumericRangeQuery.newIntRange(property, Integer.MIN_VALUE, Integer.MAX_VALUE, true, true);
fieldType = SortField.INT;
break;
default:
throw new IllegalArgumentException("Cannot create NumericRangeQuery for type: " + type);
}
Query query;
if (entityType == null)
{
query = propertyQuery;
}
else
{
TermQuery entityTypeQuery = new TermQuery(new Term("EntityType", entityType));
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(entityTypeQuery, BooleanClause.Occur.MUST);
booleanQuery.add(propertyQuery, BooleanClause.Occur.MUST);
query = booleanQuery;
}
Sort sorting = new Sort(new SortField(property, fieldType, reversed));
return new QueryContext(query).sort(sorting).top(n);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句