You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ArangoRepository扩展类使用@Query注解COLLECT分组统计不生效问题

问题原因与修复方案

1. 修正AQL语句的写法

你当前写在@Query注解中的AQL有硬换行,Java字符串硬换行可能会引入不可见的空格/换行符导致AQL语法校验失败,建议要么用字符串拼接换行,要么用Java15+的文本块语法,同时不需要额外转义JSON的双引号:

// Java 8-14 写法
@Query("FOR u IN users COLLECT country = u.country WITH COUNT INTO length RETURN {country: country, count: length}")
Iterable<CountryAndNumUsers> getListOfCountryAndNumUsers();

// Java15+ 文本块写法
@Query("""
FOR u IN users 
COLLECT country = u.country WITH COUNT INTO length 
RETURN {country: country, count: length}
""")
Iterable<CountryAndNumUsers> getListOfCountryAndNumUsers();

修正前先到ArangoDB Web控制台直接运行该AQL,确认能正常返回统计结果,先排除AQL本身的语法错误。

2. 检查投影类CountryAndNumUsers的定义

这是返回null最常见的原因,Spring Data ArangoDB对自定义查询的非实体返回类有严格的映射要求:

  • 属性名必须和AQL返回的字段名完全一致,必须包含country和count两个属性,大小写不能错
  • 必须提供公共无参构造方法
  • 必须为所有属性提供对应的getter、setter方法

正确的类定义示例:

public class CountryAndNumUsers {
    private String country;
    private Long count;

    // 必须保留无参构造
    public CountryAndNumUsers() {}

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public Long getCount() {
        return count;
    }

    public void setCount(Long count) {
        this.count = count;
    }
}

如果使用Lombok,直接加@Data、@NoArgsConstructor注解即可。

3. 可选调试配置

如果还是无法解决,可在配置文件中开启ArangoDB的操作日志,查看实际执行的AQL和返回的原始结果,快速定位问题:

# application.properties 配置
logging.level.com.arangodb.springframework=DEBUG
logging.level.com.arangodb=DEBUG

内容的提问来源于stack exchange,提问作者Njuacha Hubert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 01:15:02