gpt4 book ai didi

c# - RavenDB 在单个属性上选择 Distinct

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:32 24 4
gpt4 key购买 nike

我在 RavenDB 中存储了一个对象,它具有三个属性:ID、Score、Date。

我想创建一个索引来检索给定日期范围内的前 5 个分数。但是,我只想为每个 ID 检索一条记录。如果单个 ID 在最高分中出现不止一次,我只想检索该 ID 的最高分,然后转到下一个 ID。

示例分数:

Score____ID____
1000 1
950 1
900 1
850 2
800 2
750 3
700 4
650 5
600 6
550 7

想要的查询结果:

Score____ID____
1000 1
850 2
750 3
700 4
650 5

我已经创建了一个类似于此的显式索引(为简单起见进行了调整):

            Map = docs => from doc in docs
orderby doc.Score descending
select new
{
Score = doc.Score,
ID = doc.ID,
Date = doc.Date
};

我使用与此类似的代码调用我的查询(为简单起见进行了调整):

                    HighScores = RavenSession.Query<Score, Scores_ByDate>()
.Customize(x => x.WaitForNonStaleResultsAsOfNow())
.Where(x => x.Date > StartDate)
.Where(x => x.Date < EndDate)
.OrderByDescending(x => x.Score)
.Take(5)
.ToList();

我不知道怎么说“只给我一次列表中每个 ID 的结果。”

最佳答案

所以一些提示:

  • 不要在 Map 函数中排序。 map 旨在将文档转储出来。
  • 使用 Reduce 进行分组,因为这是他们设计的工作方式
  • 向 RavenDB 添加一个提示,表明特定列将在代码中排序,以及它是什么类型的字段。

默认情况下,map/reduce 假定排序是针对文本的,即使它是一个数字 - (I learned this the hard way 并获得了帮助。)

所以..

像平常一样定义Map/Reduce索引,在末尾添加排序条件,像这样:

public class Score_TopScoringIndex : AbstractIndexCreationTask<Score, Score>
{
public Score_TopScoringIndex()
{
Map = docs => from doc in docs
select new
{
Score = doc.Score,
ID = doc.ID,
Date = doc.Date
};

Reduce = results => from result in results
group result by result.ID into g
select new
{
Score = g.First().Score,
ID = g.Key,
Date = g.First().Date
};

Sort(x=>x.Score, SortOptions.Int);
}
}

确保索引在数据库中,方法是在应用程序启动时使用:

IndexCreation.CreateIndexes(typeof(Score_TopScoringIndex).Assembly, documentStore);

现在,当您查询 OrderByDescending 时,它会非常快。

using(var session = store.OpenSession())
{
var highScores = session.Query<Score>("Scores/TopScoringIndex")
.OrderByDescending(x=>x.Score)
.Take(5);
}

关于c# - RavenDB 在单个属性上选择 Distinct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23942270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com