【问题标题】:Filter on different fields on array of objects过滤对象数组上的不同字段
【发布时间】:2020-06-12 13:52:06
【问题描述】:

在 Elasticsearch 中,假设我有这样的文档:

{
  "id": "testId",
  "inputs": [
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-06-10T00:00:00.000Z"
    },
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
    },
    {
      "status": "ENDED",
      "lastUpdatedTime": "2020-06-11T00:00:00.000Z"
    }
  ]
}

现在,我想过滤所有文档,以便获得所有状态为 ENDED 的文档,并且 lastUpdatedTime 应该在输入数组中最高。例如。在上述情况下,它将将此文档返回为 2020-06-11T00:00:00.000Z > 2020-06-10T00:00:00.000Z 和 2020-05-11T00:00:00.000Z 并且状态为 ENDED。但是说,对于下面的文件,它不会返回:

{
  "id": "testId2",
  "inputs": [
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-06-10T00:00:00.000Z"
    },
    {
      "status": "STARTED",
      "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
    },
    {
      "status": "ENDED",
      "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
    }
  ]
}

这是因为在此文档中 STARTED 具有最大的 lastUpdatedTime。我怎样才能在 Elasticsearch 中轻松地进行这种过滤,或者不可能?

【问题讨论】:

    标签: elasticsearch elasticsearch-dsl


    【解决方案1】:

    这样,下面的查询你会得到这样的结果,lastUpdatedTime 应该是对应于STATUS="ENDED" 的输入数组中最高的

    但这仅解决了您答案的一部分,相同的查询不会为您提供所需的结果(即不适用于您的第二种情况,lastUpdatedTime 的最高值是STARTED

    映射:

    {
      "mappings": {
        "properties": {
          "inputs": {
            "type": "nested"
          },
          "lastUpdatedTime": { "type": "date" }
        }
      }
    }
    

    搜索查询:

    {
      "query": {
        "nested": {
          "path": "inputs",
          "query": {
            "match": {"inputs.status":"ENDED"}
          },
    
          "inner_hits": {
            "sort": [
        {
          "lastUpdatedTime": {
            "order": "desc"
          }
        }
      ],
      "size": 1
          } 
    
        }
      }
    }
    

    结果:

    "inner_hits": {
          "inputs": {
            "hits": {
              "total": {
                "value": 1,
                "relation": "eq"
              },
              "max_score": null,
              "hits": [
                {
                  "_index": "my_index",
                  "_type": "_doc",
                  "_id": "-s2KpnIBXf9A6l_vBbmP",
                  "_nested": {
                    "field": "inputs",
                    "offset": 2
                  },
                  "_score": null,
                  "_source": {
                    "status": "ENDED",
                    "lastUpdatedTime": "2020-05-11T00:00:00.000Z"
                  },
                  "sort": [
                    -9223372036854775808
                  ]
                }
              ]
            }
          }
        }
    

    【讨论】:

      猜你喜欢
      • 2015-07-10
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多