Spring Couchbase 的数据 - 数据库中的计数元素

Spring Data for Couchbase - Counting element in the DB

我刚开始使用 Spring Couchbase 数据,我定义了这个对象

public class Building {

    @NotNull
    @Id
    private String id;

    @NotNull
    @Field
    private String name;

    @NotNull
    @Field
    private String companyId;
}

我想通过Id统计DB中的所有元素,所以我创建了这个函数:

@Repository
@N1qlPrimaryIndexed
@ViewIndexed(designDoc = "building")
public interface BuildingRepository extends CouchbaseRepository<Building, String> {

    @Query("SELECT COUNT(*) AS count FROM #{#n1ql.bucket} WHERE #{#n1ql.filter} and id = ")
    Long countBuildings(String id);

}

但我得到的是 0,就在保存对象之后

我也试过了

@Query("#{#n1ql.selectEntity} WHERE #{#n1ql.filter} and id = ")
Long countBuildings(String id);

但我遇到了这个异常

org.springframework.data.couchbase.core.CouchbaseQueryExecutionException: Query returning a primitive type are expected to return exactly 1 result, got 0

如果你参考这个问题:

看起来您需要 return 对象,即构建查询 returning

你也可以参考spring-data-couchbase repoLine 204-209: https://github.com/spring-projects/spring-data-couchbase/blob/master/src/main/java/org/springframework/data/couchbase/repository/query/AbstractN1qlBasedQuery.java#L204

第 204-209 行

默认情况下,Couchbase N1QL 索引是异步更新的,因此如果您在插入一个项目后立即进行查询,索引可能还没有反映该添加的项目。

Couchbase 提供了两个可选级别'scan consistency',等待索引达到特定的一致性点,然后返回查询结果。它们是:

  • at_plus:它允许您提供一个或多个您需要在索引中的特定突变。这对于 'Read Your Own Writes' 场景非常有用。
  • request_plus:查询将暂停,直到查询时所有未完成的突变都在索引中。

(此处有更多详细信息:https://docs.couchbase.com/server/5.5/indexes/performance-consistency.html

至于如何在Spring的世界中应用这个,你可以这样指定扫描一致性:

@WithConsistency(ScanConsistency.REQUEST_PLUS)
@Query("SELECT COUNT(*) AS count FROM #{#n1ql.bucket} WHERE #{#n1ql.filter} and id = ")
Long countBuildings(String id);

详情请见https://docs.spring.io/spring-data/couchbase/docs/current/reference/html/#couchbase.repository.consistency