【问题标题】:Sort parent type based on one field within an array of nested Object in elasticsearch根据elasticsearch中嵌套对象数组中的一个字段对父类型进行排序
【发布时间】:2016-07-19 22:55:48
【问题描述】:

我的索引中有以下映射:

{
"testIndex": {
    "mappings": {
        "type1": {
            "properties": {
                "text": {
                    "type": "string"
                },
                "time_views": {
                    "properties": {
                        "timestamp": {
                            "type": "long"
                        },
                        "views": {
                            "type": "integer"
                        }
                    }
                }
            }
        }
    }
}
}

“time_views”实际上是一个数组,但内部属性不是数组。

我想根据每个 type1 记录的“views”属性的最大值对我的 type1 记录进行排序。我阅读了 elasticsearch 排序文档,它为排序基于单个嵌套对象的字段(单个或数组)的用例提供了解决方案。但我想要的是不同的。我想为每个文档选择“视图”的最大值并根据这些值对文档进行排序

我做了这个 json 查询

{
"size": 10,
"query": {
   "range": {
     "timeStamp": {
       "gte": 1468852617347,
       "lte": 1468939017347
     }
   }
 },
 "from": 0,
 "sort": [
    {
      "time_views.views": {
        "mode": "max",
        "nested_path": "time_views",
        "order": "desc"
      }
    }
 ]
}

但我收到了这个错误

{
  "error": {
    "phase": "query",
    "failed_shards": [
    {
    "node": "n4rxRCOuSBaGT5xZoa0bHQ",
    "reason": {
      "reason": "[nested] nested object under path [time_views] is not of nested type",
      "col": 136,
      "line": 1,
      "index": "data",
      "type": "query_parsing_exception"
    },
    "index": "data",
    "shard": 0
  }
],
"reason": "all shards failed",
"grouped": true,
"type": "search_phase_execution_exception",
"root_cause": [
  {
    "reason": "[nested] nested object under path [time_views] is not of nested type",
    "col": 136,
    "line": 1,
    "index": "data",
    "type": "query_parsing_exception"
  }
]
},
 "status": 400
}

正如我上面提到的 time_views 是一个数组,我猜这个错误是因为这个。 即使我不能使用基于数组字段功能的排序,因为“time_views”不是原始类型。 我认为我最后的机会是通过脚本编写自定义排序,但我不知道如何。 如果可以实现我想要的,请告诉我我的错误,否则给我一个简单的脚本示例。

tnx :)

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    错误消息在很大程度上解释了查询的问题。实际上,问题在于映射。而且我认为您打算使用 nested 字段,因为您使用的是嵌套查询。

    您只需将time_views 字段设为nested

      "mappings": {
        "type1": {
          "properties": {
            "text": {
              "type": "string"
            },
            "time_views": {
              "type": "nested", 
              "properties": {
                "timestamp": {
                  "type": "long"
                },
                "views": {
                  "type": "integer"
                }
              }
            }
          }
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2015-12-18
      • 1970-01-01
      相关资源
      最近更新 更多