首页 > 解决方案 > How to check in elasticsearch if a JSON object has a key using the DSL?

问题描述

If I have two documents within an index of the following format, I just want to weed out the ones which have an empty JSON instead of my expected key.

A

{ 
  "search": { 
      "gold": [1,2,3,4]
}

B

{
  "search":{}
}

I should just get A json and not B json.

I've tried the exists query to search for "gold" but it just checks for non null values and returns the list. Note: The following doesn't do what I want.

GET test/_search
{
  "query": {
    "bool": {
    "must": [
        { 
           "exists": { "field": "search.gold" }}
       ]
     }
   }
}

This is a simple question but I'm unable to find a way to do it even after searching through their docs. If someone can help me do this it would be really great.

The simplified mapping of the index is :

"test": {
    "mappings": {
    "carts": {
        "dynamic": "true",
        "_all": {
        "enabled": false
        },
        "properties": {
        "line_items": {
            "properties": {
            "line_items_dyn_arr": {
                "type": "nested",
                "properties": {
                "dynamic_key": {
                    "type": "keyword"
                }
                }
            }
            }
        }
        }
    }
    }
}

标签: jsonelasticsearchdsl

解决方案


您是否在搜索字段中存储完整的 json ?如果不是这种情况,请分享您的索引和示例数据的映射。

更新:查询嵌套字段:

{
  "query": {
    "nested": {
      "path": "search",
      "query": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "search.gold"
              }
            }
          ]
        }
      }
    }
  }
}

对于嵌套类型字段,我们需要指定要在嵌套字段上执行的路径查询,因为嵌套字段被索引为子文档。

弹性文档:嵌套查询

基于所添加的映射的更新问:

{
  "query": {
    "nested": {
      "path": "line_items.line_items_dyn_arr",
      "query": {
        "exists": {
          "field": "line_items.line_items_dyn_arr"
        }
      }
    }
  }
}

请注意,我们使用了"path": "line_items.line_items_dyn_arr". 我们需要提供完整路径的原因是因为nested字段line_items_dyn_arr本身在 line_items 对象下。必须line_items_dyn_arr是映射的属性,而不是前一个查询的属性objectnested字段。


推荐阅读