检查 Elasticsearch 文档中是否存在某个字段的最佳方法

Best way to check if a field exist in an Elasticsearch document

检查 elasticsearch 中文档字段是否存在的最佳方法是什么?我在文档中找不到任何内容。

例如,如果此文档没有 field/key“价格”,我不想在结果中 return。

{
    "updated": "2015/09/17 11:27:27",
     "name": "Eye Shadow",
     "format": "1.5 g / 0.05 oz",
}

我能做什么?

您可以像这样使用 exists filter combined with a bool/must filter

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "price"
              }
            },
            ...     <-- your other constraints, if any
          ]
        }
      }
    }
  }
}

已弃用(自 ES5 起) 您还可以使用 missing filter combined with a bool/must_not filter:

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must_not": [
            {
              "missing": {
                "field": "price"
              }
            }
          ]
        }
      }
    }
  }
}

您可以使用存在过滤器:

{
  "query": {
    "filtered": {
      "filter": {
        "exists": {
          "field": "status"
        }
      },
      "query": {
        "match_all": {}
      }
    }
  }
}

此致, 阿兰

exists 过滤器已被 ES 2.1 中的 exists query 取代,尽管它们的工作原理是相同的。此外,删除了缺少的过滤器并弃用了缺少的查询。

要获取具有特定字段的所有文档,

"bool": {
    "must": {
        "exists": {
            "field": "my_field"
        }
    }
}

并获取所有没有特定字段的文档,将其与 must_not 一起使用

"bool": {
    "must_not": {
        "exists": {
            "field": "my_field"
        }
    }
}

弹性文档:https://www.elastic.co/guide/en/elasticsearch/reference/2.3/query-dsl-missing-query.html

你可以直接做

{
    "query": {
        "exists": {
            "field": "fieldName"
        }
    }
}

如果你也想添加一些匹配,那么你可以去

{
    "query": {
        "bool": {
            "must": [{
                "match": {
                    "fieldName": "value"
                }
            },
            {
                "exists": {
                    "field": "fieldName"
                }
            }]
        }
    }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html

GET /_search
{
    "query": {
        "exists" : { "field" : "price" }
    }
}

来源:https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html