匹配null应在Elasticsearch 2.3.0中查询

时间:2016-04-15 07:03:07

标签: elasticsearch

我有一个字段gender,它可以有三个值:

  • MALE
  • FEMALE

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 :(得分: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"
        }
     }