默认情况下,您正在执行的查询限制为合理数量的结果,这是 RavenDB 承诺的一部分,默认情况下是安全的,不会流回数百万条记录。
为了获取 yoru 数据库中特定类型文档的数量,您需要一个特殊的 map-reduce 索引,其工作是跟踪每种文档类型的计数。因为这种类型的索引直接处理文档元数据,所以在 Raven Studio 中定义它比尝试用代码创建它更容易。
该索引的来源在this question,但我将在此处复制:
// Index Name: Raven/DocumentCollections
// Map Query
from doc in docs
let Name = doc["@metadata"]["Raven-Entity-Name"]
where Name != null
select new { Name , Count = 1}
// Reduce Query
from result in results
group result by result.Name into g
select new { Name = g.Key, Count = g.Sum(x=>x.Count) }
然后,要在您的代码中访问它,您需要一个类来模仿 Map 和 Reduce 查询创建的匿名类型的结构:
public class Collection
{
public string Name { get; set; }
public int Count { get; set; }
}
然后,正如 Ayende 在previously linked question 的回答中所指出的,您可以从索引中获得如下结果:
session.Query<Collection>("Raven/DocumentCollections")
.Where(x => x.Name == "MyDocument")
.FirstOrDefault();
但是请记住,索引是异步更新的,因此在批量插入一堆文档后,索引可能会过时。您可以通过在.Query(...) 之后添加.Customize(x => x.WaitForNonStaleResults()) 来强制它等待。
Raven Studio 实际上是从每个数据库都存在的索引Raven/DocumentsByEntityName 中获取这些数据,方法是避开正常查询并获取索引上的元数据。你可以这样模拟:
QueryResult result = docStore.DatabaseCommands.Query("Raven/DocumentsByEntityName",
new Raven.Abstractions.Data.IndexQuery
{
Query = "Tag:MyDocument",
PageSize = 0
},
includes: null,
metadataOnly: true);
var totalDocsOfType = result.TotalResults;
那个 QueryResult 包含很多有用的数据:
{
Results: [ ],
Includes: [ ],
IsStale: false,
IndexTimestamp: "2013-11-08T15:51:25.6463491Z",
TotalResults: 3,
SkippedResults: 0,
IndexName: "Raven/DocumentsByEntityName",
IndexEtag: "01000000-0000-0040-0000-00000000000B",
ResultEtag: "BA222B85-627A-FABE-DC7C-3CBC968124DE",
Highlightings: { },
NonAuthoritativeInformation: false,
LastQueryTime: "2014-02-06T18:12:56.1990451Z",
DurationMilliseconds: 1
}
如果您请求统计信息,其中大部分与您在任何查询中获得的数据相同,如下所示:
RavenQueryStatistics stats;
Session.Query<Course>()
.Statistics(out stats)
// Rest of query