在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
答案 0 :(得分:0)
我调查了这个,答案是肯定的,这可以做到。 IndexHits<T> query( String key, Object queryOrQueryObject )
中的第二个参数可以是可解析的(org.apache.lucene.queryParser.QueryParser
)字符串,org.apache.lucene.search.Query
或org.neo4j.index.lucene.QueryContext
这是一个代码段,允许要求&#34; EntityType&#34;具有特定值的属性,要求数字属性为非空白,并返回按数字属性排序的前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);
}