略微加速

略速 - 互联网笔记

一个Elasticsearch集群嵌套nested查询的实例

2020-12-22 leiting (4160阅读)

标签 Elasticsearch

创建索引和数据准备

PUT course
PUT course/_mapping/course
{

      "properties": {
        "course":{
          "type": "nested"
          , "properties": {
                "key1": {
                  "type": "text",
                  "analyzer": "ik_max_word"
                  },
                "key2": {
                  "type": "text",
                  "analyzer": "ik_max_word"
                },
                "course_score": {
                "type": "long"
                }
          }
        },
          "course_name": {
            "type": "text"
            , "analyzer": "ik_max_word"
          },
          "course_id": {
            "type": "long"
          }
      }
}
PUT course/course/1
{
  "course":[
    {
     "key1":"语文,高一,高二,高三",
     "key2":"高考作文",
     "course_score":15
    },
    {
      "key1":",语文,高二",
      "key2":"语文高考",
      "course_score":9
    },
    {
      "key1":",努力,学习",
      "key2":"高考",
      "course_score":9
    }
  ],
  "course_name":"语文高考基础题满分策略",
  "course_id":13
}

PUT course/course/2
{
  "course":[
    {
    "key1":",其他,高一,高二,高三",
    "key2":"鲁林希",
    "course_score":21
    },
    {
    "key1":",其他,高一",
    "key2":"高考",
    "course_score":11
    },
    {
    "key1":",其他,高二,高三",
    "key2":"高考",
    "course_score":2
    }
  ],
  "course_name":"师兄师姐来帮忙-方法篇",
  "course_id":220
}

PUT course/course/3
{
  "course":[
    {
    "key1":",其他,高一,高三",
    "key2":"高考",
    "course_score":21
    }
  ],
  "course_name":"师兄师姐来帮忙-自招全流程",
  "course_id":221
}

查询语句实例

GET course/course/_search
{
  
  "query": {
    "function_score": {
      "query": {
        "bool": {
          "must": [
            {
              "nested": {
                "path": "course",
                "score_mode": "sum", 
                "query": {
                  "function_score": {
                    "query": {
                      "bool": {
                        "must": [
                          {
                            "match": {
                              "course.key1": "高一,高二,高三"
                            }
                          },
                          {
                            "match": {
                              "course.key2": "高考"
                            }
                          }
                        ]
                      }
                    },
                    "script_score": {
                      "script": "doc['course.course_score'].value"
                    }
                  }
                }
              }
            }
          ]
        }
      }
      , "script_score": {
        "script": "_score"
      }
    }
  }
}


原理:

nested文档是独立的数据在nested查询内部,返回的分数作为根文档的评分,所以在nested查询内部再使用一次function_score将内部的数据作为评分传递到根文档。


北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3