2016-04-15 118 views
1

我有一個字段gender它可以有三個值:匹配空在應Elasticsearch查詢2.3.0

  • MALE

gender的映射:

"gender": { 
    "type": "string", 
    "index": "not_analyzed" 
} 

匹配null我跟隨this

我用這個查詢與gendernull發出文件:

{ 
    "query": { 
     "bool": { 
      "must_not": { 
       "exists": { 
        "field": "gender" 
       } 
      } 
     } 
    } 
} 

我想建立一個should查詢,以便搜索結果可能返回具有gender領域的任何文件:

{ 
    "query": { 
    "bool": { 
     "should": { 
     "bool": { 
      "should": [ 
      { 
       "match": { 
       "gender": { 
        "query": "MALE", 
        "type": "boolean" 
       } 
       } 
      }, 
      { 
       "match": { 
       "gender": { 
        "query": "FEMALE", 
        "type": "boolean" 
       } 
       } 
      } 
      ], 
      "must_not": { 
      "exists": { 
       "field": "gender" 
      } 
      } 
     } 
     } 
    } 
    } 
} 

上面的查詢給我0次點擊。我應該如何爲此構建正確的查詢?

+1

因爲你用你得到0結果'必須'同時具有'男性'和'女性'的值。它應該是「應該」而不是「必須」。我不明白你用'must_not'和'exists'做了什麼。 –

+0

如何將「gender」爲'null'的文檔匹配?我正在關注[this](https://www.elastic.co/guide/en/elasticsearch/reference/2.3/query-dsl-exists-query.html#_literal_missing_literal_query) –

+0

「gender」字段的映射是什麼? –

回答

2
{ 
    "query": { 
    "bool": { 
     "should": [ 
     { 
      "match": { 
      "gender": { 
       "query": "MALE", 
       "type": "boolean" 
      } 
      } 
     }, 
     { 
      "match": { 
      "gender": { 
       "query": "FEMALE", 
       "type": "boolean" 
      } 
      } 
     }, 
     { 
      "bool": { 
      "must_not": { 
       "exists": { 
       "field": "gender" 
       } 
      } 
      } 
     } 
     ] 
    } 
    } 
} 

,如果我不明白的問題很好,在你想gender之間從文檔場在那裏完全缺失的分化的事實,但有null,你需要別的東西,這需要稍微改變一下映射:

"gender": { 
     "type": "string", 
     "index": "not_analyzed", 
     "null_value": "_null_" 
    } 

,在這種情況下,查詢是:

"query": { 
    "bool": { 
     "should": [ 
     { 
      "match": { 
      "gender": { 
       "query": "MALE" 
      } 
      } 
     }, 
     { 
      "match": { 
      "gender": { 
       "query": "FEMALE" 
      } 
      } 
     }, 
     { 
      "term": { 
      "gender": "_null_" 
      } 
     } 
     ] 
    } 
    } 

在這種情況下,如果指數:

{"index":{}} 
{"gender":"MALE"} 
{"index":{}} 
{"gender":"FEMALE"} 
{"index":{}} 
{"gender":null} 
{"index":{}} 
{"gender2":"MALE"} 
{"index":{}} 
{"gender":"whatever"} 

它會給你回:

 { 
     "_score": 0.2826735, 
     "_source": { 
      "gender": "MALE" 
     } 
    }, 
    { 
     "_score": 0.2826735, 
     "_source": { 
      "gender": null 
     } 
    }, 
    { 
     "_score": 0.021688733, 
     "_source": { 
      "gender": "FEMALE" 
     } 
    } 
相關問題