我需要将linq查询转换为NEST。那就是我的linq查询的样子:
var result = studentList
.GroupBy(student => student.Name)
.Select(group => group.OrderByDescending(student => student.grade).Take(3))
.SelectMany(p => p);
这应该:
它与linq一起工作,但是如何使用NEST做到这一点?
我正在尝试聚合,子聚合,分类存储桶,但没有成功。
我知道如何按名称分组,但是接下来呢?
client.Search<Students>(s => s
.Aggregations(a => a
.Terms("group_by_name", ts => ts
.Field(o => o.Name))));
如何订购每个小组,如何从每个小组中选拔顶尖学生?
最佳答案
假设模型像
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Grade { get; set; }
}
以下将按学生姓名分组,然后按成绩降序获得各组中的热门x命中值
private static void Main()
{
var defaultIndex = "students";
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(pool)
.DefaultIndex(defaultIndex);
var client = new ElasticClient(settings);
if (client.IndexExists(defaultIndex).Exists)
client.DeleteIndex(defaultIndex);
var createIndexResponse = client.CreateIndex(defaultIndex, c => c
.Settings(s => s
.NumberOfShards(1)
.NumberOfReplicas(0)
)
.Mappings(m => m
.Map<Student>(mm => mm
.AutoMap()
)
)
);
var students = Enumerable.Range(1, 20).Select(i =>
new Student
{
Id = i,
Name = i % 2 == 0 ? "Foo" : "Bar",
Grade = i
}
);
var bulkResponse = client.Bulk(b => b
.IndexMany(students)
.Refresh(Refresh.WaitFor) // refresh, so that documents indexed are available to search immediately
);
var topX = 10;
var searchResponse = client.Search<Student>(s => s
.Aggregations(a => a
.Terms("student_name", t => t
.Field(f => f.Name.Suffix("keyword"))
.Aggregations(aa => aa
.TopHits("top_grades", th => th
.Sort(so => so
.Descending(f => f.Grade)
)
.Size(topX)
)
)
)
)
);
var studentNames = searchResponse.Aggregations.Terms("student_name");
foreach(var bucket in studentNames.Buckets)
{
var header = $"Student Name: {bucket.Key}";
Console.WriteLine(header);
Console.WriteLine(new string('-', header.Length));
foreach(var hit in bucket.TopHits("top_grades").Documents<Student>())
{
Console.WriteLine($"Id: {hit.Id}, Grade: {hit.Grade}");
}
Console.WriteLine();
}
}
打印出来
Student Name: Bar
-----------------
Id: 19, Grade: 19
Id: 17, Grade: 17
Id: 15, Grade: 15
Id: 13, Grade: 13
Id: 11, Grade: 11
Id: 9, Grade: 9
Id: 7, Grade: 7
Id: 5, Grade: 5
Id: 3, Grade: 3
Id: 1, Grade: 1
Student Name: Foo
-----------------
Id: 20, Grade: 20
Id: 18, Grade: 18
Id: 16, Grade: 16
Id: 14, Grade: 14
Id: 12, Grade: 12
Id: 10, Grade: 10
Id: 8, Grade: 8
Id: 6, Grade: 6
Id: 4, Grade: 4
Id: 2, Grade: 2
关于c# - ElasticSearch NEST-先按GroupBy再按OrderBy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54491500/