N1QL 二级索引不适用于参数化 IN 子句

N1QL secondary index not working with parameterized IN clause

使用 com.couchbase.client, java-client 版本 2.2.7 我无法使使用参数化 IN 子句的 n1ql 二级索引正常工作。请参阅下面的示例索引、查询和 java 代码

Index

CREATE INDEX `indexName` ON `bucketName`(id,docType) USING GSI ;

Query

public static final String COUNT_STATEMENT = "select count(*) as count " +
            "from bucketName " +
            "where docType = 'docId' " +
            "and id IN $ids " + 
            "and publishTimestamp between $startTime and $endTime";

Code to submit Query

public int getCountForDuration(Long startTime, Long endTime, Collection<String> ids){
    List<String> idList = new ArrayList<>(ids);
    JsonObject placeHolders = JsonObject.create()
                                        .put("ids", JsonArray.from(idList))
                                        .put("startTime", startTime)
                                        .put("endTime", endTime);
    N1qlQuery query = N1qlQuery.parameterized(COUNT_STATEMENT, placeHolders)            
    N1qlQueryResult result = bucket.query(query);
    ...
}

在添加参数化之前,我的查询正确使用了这个二级索引。如果我使用主索引,我的查询也有效。

My question is this how do I create a secondary index which will be used by my query.

我通过添加额外的 is not missing 子句解决了这个问题,出于某种原因,这解决了这个问题。同样的解决方案在我的通行证中起作用。这是更新后的查询:

public static final String COUNT_STATEMENT = "select count(*) as count " +
        "from bucketName " +
        "where id is not missing " + 
        "and docType = 'docId' " +
        "and id IN $ids " + 
        "and publishTimestamp between $startTime and $endTime";

@Ben Wilde comment -

"The reason the "is missing" is required is because the first entry in an index (in 'this' case id) cannot be missing. So documents that have a missing id will not be in the index so if you do not use a field that is already constrained by conditions set by your index, then you will have to specify that it is not missing to ensure that can go to your secondary index"

索引中的第一个条目(在您的情况下 id)不能丢失。因此缺少 id 的文档不会出现在索引中。因此,如果您不使用已经受索引条件约束的字段,则必须指定它不丢失以确保可以转到您的二级索引。

例如您可以使用 type="entityType"

查询以下索引

CREATE INDEX `indexName` ON `bucketName`(type) WHERE `type`="entityType"