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

Java中如何在Azure Cosmos @Query的IN语句中传入列表?

Azure Cosmos Query注解实现ID列表匹配查询的正确方式

问题根源

你之前手动将List转为带引号的逗号分隔字符串,Azure Cosmos会把这个完整字符串当成单个查询值——比如传入"'111'"时,实际查询条件是c.id IN ("'111'"),而文档的id是"111",因字符串内容多了一层单引号导致匹配失败。

正确实现方案

不需要手动拼接字符串,直接传递List类型参数,利用Spring Data Cosmos的参数自动处理能力,两种常用写法如下:

方案1:使用IN子句直接传递List

在Repository接口中定义方法,参数直接用List<String>,查询语句保持IN (@ids)即可:

import com.azure.spring.data.cosmos.repository.CosmosRepository;
import com.azure.spring.data.cosmos.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

public interface YourEntityRepository extends CosmosRepository<YourEntity, String> {
    @Query("SELECT * FROM c WHERE c.id IN (@ids)")
    List<YourEntity> getItemsByIds(@Param("ids") List<String> ids);
}

调用时直接传入ID列表:

List<String> idList = Arrays.asList("111", "222", "333");
List<YourEntity> result = yourEntityRepository.getItemsByIds(idList);

方案2:使用ARRAY_CONTAINS(推荐处理大量ID场景)

当ID列表过长时,IN子句会有参数数量限制,改用ARRAY_CONTAINS更稳妥,它会检查文档id是否存在于传入的数组中:

public interface YourEntityRepository extends CosmosRepository<YourEntity, String> {
    @Query("SELECT * FROM c WHERE ARRAY_CONTAINS(@ids, c.id)")
    List<YourEntity> getItemsByIds(@Param("ids") List<String> ids);
}

调用方式和方案1完全一致,框架会自动将List转为Cosmos SQL支持的数组参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:36:29