2016-02-26 100 views
3

我使用ES 2.1,並具有以下映射:結合嵌套查詢與過濾

"startDate": { 
    "type": "date", 
    "format": "yyyy-MM-dd HH:mm:ss:SSS||yyyy-MM-dd HH:mm:ss", 
    "index": "not_analyzed", 
    "store": true 
},"identities": { 
    "type": "nested", 
    "properties": { 
    "identityatt": { "type": "integer", "index": "not_analyzed", "store": true }, 
    "identitykey": { "type": "string", "index": "not_analyzed", "store": true }, 
    "identityval": { "type": "string", "index": "not_analyzed", "store": true }, 
    "identitytype": { "type": "integer", "index": "not_analyzed", "store": true } 
    } 
} 

下列查詢是個好人,他們回到我所期望的:

{ "size": 50, 
    "query": { 
    "filtered": { 
     "filter": { 
     "range": { 
      "startDate": { 
      "from": "2016-02-19 11:11:25", 
      "to": "2016-02-27 11:11:25", 
      "include_lower": true, 
      "include_upper": true 
      } 
}}}}} 

這一個過濾器通過一個時間範圍,並與下一個我想檢索所有具有特殊的身份類型

{ 
    "size": 50, 
    "query": { 
    "nested": { 
     "path": "identities", 
     "filter": { 
     "term": { 
      "identities.identitytype": "2" 
     } 
}}}} 

但我似乎沒有ge將這兩者結合起來進行查詢。

我試着將時間範圍查詢添加到嵌套過濾器中的過濾器,將兩個過濾器都嵌套在一個bool過濾器中,我也試着用filtered查詢,但沒有把這兩個過程結合起來。

查看https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-nested-query.html的示例,它也包含一個範圍查詢,不同之處在於它位於嵌套對象內,而我的startDate未包含在嵌套對象中。

有關如何組合這些查詢的任何想法?

編輯

我也試了一下在此建議:Combined non-Nested and Nested Query in Elasticsearch並且得到錯誤"No query registered for [filter]"

{ 
    "size": 50, 
    "query": { 
    "bool": { 
    "must": [ 
    {"filter": { 
     "range": { 
      "startDate": { 
      "from": "2016-02-19 11:11:25", 
      "to": "2016-02-27 11:11:25", 
      "include_lower": true, 
      "include_upper": true 
      } 
     } 
     }}, 
     {"nested": { 
     "path": "identities", 
     "filter": { "bool": { "must": [{ 
     "term": { 
      "identities.identitytype": "2" 
     }, 
     "range": { 
      "startDate": { 
      "from": "2016-02-19 11:11:25", 
      "to": "2016-02-27 11:11:25", 
      "include_lower": true, 
      "include_upper": true 
      } 
     }}]} 
     } 
    } 
     } 
    ] 
    }}} 

回答

2

下面的查詢應該工作。您不能在nested之內嵌套range查詢,您需要將其保留在bool/must之外的同一級別。

{ 
    "size": 50, 
    "query": { 
    "filtered": { 
     "filter": { 
     "bool": { 
      "must": [ 
      { 
       "range": { 
       "startDate": { 
        "from": "2016-02-19 11:11:25", 
        "to": "2016-02-27 11:11:25", 
        "include_lower": true, 
        "include_upper": true 
       } 
       } 
      }, 
      { 
       "nested": { 
       "path": "identities", 
       "filter": { 
        "term": { 
        "identities.identitytype": "2" 
        } 
       } 
       } 
      } 
      ] 
     } 
     } 
    } 
    } 
}