弹性搜索查询中间结果 [英] Elasticsearch query with intermediate results
问题描述
-
教师
-
Class
-
TeacherClass
(整数字段teacher_id
和class_id
) -
事件
(整数字段teacher_class_id
)
所以结构看起来像这样:
___________ _______________ _________
|老师| _____ / | TeacherClass | \ _____ |类|
| _________ | \ | ______________ | / | _______ |
|
|
___ / _ \ ___
|事件|
| _______ |
我想获得与给定老师相关的活动数量。目前我正在做两个查询:
-
TeacherClass
获取TeacherClass
ids的数组 - 计数查询
事件
(计数事件与teacher_class_id
等于数组中的一个值。
在单个查询中有没有办法?
这里的关键是非规范化。您需要对数据进行非规范化,以便每个文档包含以下字段:
{
teacher_id:1,
teacher_name:John Math,
class_id:2,
class_name:Math,
event_id:3,
event_name:我的事件
}
然后,您可以将数据与术语
聚合 teacher_id
,并查看使用 value_count
sub-aggregation on event_id
。
{
query:{
match_all:{}
},
aggs:{
teachers:{
terms:{
field:teacher_id
},
aggs:{
events:{
value_count:{
:event_id
}
}
}
}
}
}
I'm new to elasticsearch and I have problem querying it efficiently. I have following types of objects:
Teacher
Class
TeacherClass
(with integer fieldsteacher_id
andclass_id
)Event
(with integer fieldteacher_class_id
)
So the structure looks like this:
___________ _______________ _________
| Teacher |_____/| TeacherClass |\_____| Class |
|_________| \|______________|/ |_______|
|
|
___/_\___
| Event |
|_______|
I want to get the number of events associated with given teacher. Currently I'm doing this with two queries:
- search query on
TeacherClass
(to get an array ofTeacherClass
ids) - count query on
Event
(to count events withteacher_class_id
equal to one of the values in the array).
Is there a way to do this in a single query?
The keyword here is denormalization. You need to denormalize your data so that each document contains the following fields:
{
"teacher_id": 1,
"teacher_name": "John Math",
"class_id": 2,
"class_name": "Math",
"event_id": 3,
"event_name": "My Event"
}
You can then aggregate your data with a terms
aggregation on teacher_id
and see how many different events you have using a value_count
sub-aggregation on event_id
.
{
"query": {
"match_all": {}
},
"aggs": {
"teachers": {
"terms": {
"field": "teacher_id"
},
"aggs": {
"events": {
"value_count": {
"field": "event_id"
}
}
}
}
}
}
这篇关于弹性搜索查询中间结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!