首页 > 解决方案 > 必须为此操作提供 PartitionKey 值

问题描述

我正在尝试从 Azure Cosmos Db 集合中检索文档。我遇到了一个错误

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.UnsupportedOperationException: PartitionKey value must be supplied for this operation.] with root cause
java.lang.UnsupportedOperationException: PartitionKey value must be supplied for this operation.

我试图在网上查找如何向函数 findById() 提供分区键值,但似乎“Azure Spring 数据 cosmosdb”没有为 java 函数提供分区键的选项执行

orderTransactionRepository.findById("id").get

标签: javaazure-cosmosdbazure-cosmosdb-sqlapi

解决方案


搜索了spring-data-cosmos主页中提到的分区集合findById方法的测试代码

@Test
    public void testFindByIdForPartitionedCollection() {
        final List<Address> addresses = repository.findByPostalCode(TestConstants.POSTAL_CODE);

        assertThat(addresses.size()).isEqualTo(2);
        assertThat(addresses.get(0).getPostalCode().equals(TestConstants.POSTAL_CODE));
        assertThat(addresses.get(1).getPostalCode().equals(TestConstants.POSTAL_CODE));
    }

你可以在这里找到这些陈述:

对于分区集合,如果要通过 findById(id) 查询记录,会抛出异常。

// Incorrect for partitioned collection, exception will be thrown
   Address result = repository.findById(id);  // Caution: Works for non-partitioned collection

相反,您可以使用自定义查询按 ID 字段名称查询记录。

// Correct, postalCode is the ID field in Address domain
   @Repository
   public interface AddressRepository extends DocumentDbRepository<Address, String> {
      List<Address> findByPostalCode(String postalCode);
   }

   // Query
   List<Address> result = repository.findByPostalCode(postalCode);

另一种方法我发现你仍然可以在 spring-data-cosmos 包中使用 Document DB 普通 sdk,你只需要以简单的方式封装该方法。请参考此示例代码


就总结而言,这基本上是由于 Spring data commons 更改了 querylookupstrategy 正在实现的接口名称。你需要回到以前的版本cosmos-db i.e. 2.0.5!这是说明问题的链接 github.com/Microsoft/spring-data-cosmosdb/issues/304


推荐阅读