弹性搜索查询中间结果 [英] Elasticsearch query with intermediate results

查看:120
本文介绍了弹性搜索查询中间结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚进入弹性搜索,我有问题查询它有效率。我有以下类型的对象:




  • 教师

  • 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 fields teacher_id and class_id)
  • Event (with integer field teacher_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 of TeacherClass ids)
  • count query on Event (to count events with teacher_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆