结果中的记录数导致 -> 对象引用未设置为对象的实例 - Azure Cosmos Db

Number of records in the result causes -> Object reference not set to an instance of an object - Azure Cosmos Db

使用 java 从 cosmos db 检索数据时出现以下错误。

com.mongodb.MongoQueryException: Query failed with error code 1 and error message '[ActivityId=92f973a7-c33f-xxxx-xxxx-xxxxxxxxxxxxx] 
Error=1, Details='Response status code does not indicate success: InternalServerError (500); 
Substatus: 0; ActivityId: 00000000-0000-0000-0000-000000000000; 
Reason: (Object reference not set to an instance of an object.);' on server xxxx-xxxx-westus.mongo.cosmos.azure.com:10255

下面是获取数据的方法

public List<T> getData(String orKey,
                          String[] orValues,
                          LinkedHashMap<String, Object> andProperties,
                          String orderByKey, int offset, int limit) {

Bson[] orFilers = new Bson[orValues.length];
int counter = 0;
if (orValues.length > 0) {
  for (String s : orValues) {
    orFilers[counter++] = eq(orKey, s.trim());
  }
}

Bson[] andFilers = new Bson[andProperties.size()];
counter = 0;
if (andProperties.size() > 0) {
  for (Map.Entry<String, Object> entry : andProperties.entrySet()) {
    andFilers[counter++] = eq(entry.getKey(), entry.getValue());
  }
}

ArrayList<T> results = new ArrayList<>();
collection.find(and(or(orFilers), and(andFilers)))
        .skip(offset)
        .limit(limit)
        .sort(descending(orderByKey))
        .forEach((Consumer<T>) t -> {
          results.add(t);
        });
return results;

}

我做了一些调试,发现当 results 列表有 102 条或更多条记录时,就会出现此错误。我通过更改 limitoffset 值找到它。

当,

offset = 0 & limit = 101 => success
offset = 0 & limit = 102 => error
offset = 1 & limit = 102 => error
offset = 1 & limit = 105 => error
offset = 1 & limit = 101 => success

注意:给定查询有 113 条有效记录。

您是否设置了MaxItemCount计数值?

对于 Cosmosdb 的分页,默认值为 100。

You can specify the maximum number of items returned by a query by setting the MaxItemCount. The MaxItemCount is specified per request and tells the query engine will to return that number of items or fewer. You can set MaxItemCount to -1 if you don't want to place a limit on the number of results per query execution.

您可以设置maxItemCount再尝试执行。

问题出在索引字段上。我已经用 Date 类型字段创建了一个索引,并且一些记录对该字段具有空值。

public void createIndex(String keyString) {
    Document key = new Document(keyString, 1);
    this.collection.createIndex(key, new IndexOptions());
}

将其更改为长类型字段,问题得到解决。为什么之前的查询在 102 计数时给出错误是我找不到的。