Elasticsearch:嵌套查询中的脚本字段

时间:2018-08-14 20:18:02

标签: elasticsearch

是否可以在嵌套查询中使用“ script_fields”,将字段添加到返回的inner_hits中?示例:

{
   "nested": {
      "inner_hits": {},
      "path": "companies",
      "score_mode": "sum",
      "query": {},
      "script_fields": {
         "overlap" : {
            "script": {
               "source": "................................",
               "params": {
                   "from": "2012-01-01",
                    "to": "2015-06-30"
                }
            }
         }                
      }         
}

我执行n个嵌套查询,并将每个特定的参数传递给每个嵌套查询。想法是让源脚本根据提供的参数为每个内部匹配的重叠字段分配一个值。

Val建议在内部匹配中添加script_fields后进行更新

就像在同一嵌套路径上执行更多嵌套查询,定义不同的inner_hits使得ES剥离了inner_hits匹配项。示例:

{
       "nested": {
          "inner_hits": {
            "script_fields": {
               "overlap" : {
                  "script": {
                     "source": "................................",
                        "params": {
                           "from": "2012-01-01",
                           "to": "2015-06-30"
                         }
                      }
                   }                
                 } 
          },
          "path": "companies",
          "score_mode": "sum",
          "query": {},

    },
    {
       "nested": {
          "inner_hits": {
            "script_fields": {
               "overlap" : {
                  "script": {
                     "source": "................................",
                        "params": {
                           "from": "2012-01-01",
                           "to": "2015-06-30"
                         }
                      }
                   }                
                 } 
          },
          "path": "companies",
          "score_mode": "sum",
          "query": {},

    } 

如果像这样运行更多的嵌套查询,我将获得正确的匹配项,但不会返回所有预期的inner_hits。我可以获得所有匹配,只给不同的inner_hits随机命名,例如:

"inner_hits": {
   "name": [random name]
   "script_fields": {
      "overlap" : {
         ......
      }
    }
 }   

然后,我获得了正确的点击结果,但有一些缺点。我必须检查重复的结果,因为匹配已添加到不同的结果集中,并且不再唯一。我必须使用正则表达式解析结果以重建统一列表。

这听起来像个错误吗?

1 个答案:

答案 0 :(得分:3)

是的,这是可行的。您只需要在script_fields内移动inner_hits部分,就像这样:

{
   "nested": {
      "path": "companies",
      "score_mode": "sum",
      "query": {}.
      "inner_hits": {
         "script_fields": {
           "overlap" : {
             "script": {
               "source": "................................",
               "params": {
                   "from": "2012-01-01",
                    "to": "2015-06-30"
               }
             }
           }                
         }     
      }
   }              
}