用户定义的聚合函数

用户自定义聚合函数 是对数据进行聚合并返回单一结果的函数。有关用户自定义过程、函数和聚合函数的比较,请参阅 Neo4j 定制代码

调用聚合函数

用户自定义聚合函数的调用方式与其他 Cypher 聚合函数相同。函数名称必须是完全限定的,因此在包 org.neo4j.examples 中定义的名为 longestString 的函数可以使用以下方式调用

MATCH (p: Person) WHERE p.age = 36
RETURN org.neo4j.examples.longestString(p.name)

编写用户自定义聚合函数

用户自定义聚合函数使用 @UserAggregationFunction 注解。被注解的函数必须返回一个聚合器类的实例。聚合器类包含一个使用 @UserAggregationUpdate 注解的方法以及一个使用 @UserAggregationResult 注解的方法。带 @UserAggregationUpdate 注解的方法会被多次调用,以实现数据的聚合。当聚合完成后,带 @UserAggregationResult 注解的方法会被调用一次,并返回聚合结果。

特别注意事项

  • 所有函数均使用 @UserAggregationFunction 注解。

  • 聚合函数名称必须带有命名空间,并且不能使用保留命名空间。

  • 如果在已弃用的命名空间中注册的用户自定义聚合函数与内置函数同名,则该内置函数会被遮蔽。

有关值和类型的详细信息,请参阅 值与类型

欲了解更多细节,请参阅 Neo4j Javadoc 中的 org.neo4j.procedure.UserAggregationFunction

在聚合函数内部发出错误信号的正确方式是抛出 RuntimeException

package example;

import org.neo4j.procedure.Description;
import org.neo4j.procedure.Name;
import org.neo4j.procedure.UserAggregationFunction;
import org.neo4j.procedure.UserAggregationResult;
import org.neo4j.procedure.UserAggregationUpdate;

public class LongestString
{
    @UserAggregationFunction
    @Description( "org.neo4j.function.example.longestString(string) - aggregates the longest string found" )
    public LongStringAggregator longestString()
    {
        return new LongStringAggregator();
    }

    public static class LongStringAggregator
    {
        private int longest;
        private String longestString;

        @UserAggregationUpdate
        public void findLongest(
                @Name( "string" ) String string )
        {
            if ( string != null && string.length() > longest)
            {
                longest = string.length();
                longestString = string;
            }
        }

        @UserAggregationResult
        public String result()
        {
            return longestString;
        }
    }
}

集成测试

用户自定义聚合函数的测试创建方式与普通用户自定义函数相同。

用于测试查找最长字符串的用户自定义聚合函数的模板。
package example;

import org.junit.Rule;
import org.junit.Test;
import org.neo4j.driver.v1.*;
import org.neo4j.harness.junit.Neo4jRule;

import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;

public class LongestStringTest
{
    // This rule starts a Neo4j instance
    @Rule
    public Neo4jRule neo4j = new Neo4jRule()

            // This is the function to test
            .withAggregationFunction( LongestString.class );

    @Test
    public void shouldAllowIndexingAndFindingANode() throws Throwable
    {
        // This is in a try-block, to make sure you close the driver after the test
        try( Driver driver = GraphDatabase.driver( neo4j.boltURI() , Config.build().withEncryptionLevel( Config.EncryptionLevel.NONE ).toConfig() ) )
        {
            // Given
            Session session = driver.session();

            // When
            String result = session.run( "UNWIND ["abc", "abcd", "ab"] AS string RETURN example.longestString(string) AS result").single().get("result").asString();

            // Then
            assertThat( result, equalTo( "abcd" ) );
        }
    }
}

保留和已弃用的函数命名空间

请注意,已弃用的函数命名空间将在下一个主要的 Cypher 版本中搬迁为保留命名空间。有关 Neo4j 与 Cypher 版本控制的更多信息,请参阅 Operations manual → Introduction

表 1. 保留和已弃用的函数命名空间及名称概览
保留 自 Neo4j 2025.11 起在 Cypher 25 中弃用

*

abac.*

date

builtin.*

date.realtime

cdc.*

date.statement

coll.*

date.transaction

date.*

date.truncate

datetime.*

datetime

db.*

datetime.fromepoch

dbms.*

datetime.fromepochmillis

duration.*

datetime.realtime

graph.*

datetime.statement

internal.*

datetime.transaction

localdatetime.*

datetime.truncate

localtime.*

db.nameFromElementId

math.*

duration

plugin.*

duration.between

point.*

duration.inDays

stored.*

duration.inMonths

string.*

duration.inSeconds

time.*

graph.byElementId

tx.*

graph.byName

unsupported.*

graph.names

vector.*

graph.propertiesByName

localdatetime

localdatetime.realtime

localdatetime.statement

localdatetime.transaction

localdatetime.truncate

localtime

localtime.realtime

localtime.statement

localtime.transaction

localtime.truncate

point.distance

point.withinBBox

time

time.realtime

time.statement

time.transaction

time.truncate

vector.similarity.cosine

vector.similarity.euclidean