【问题标题】:Elasticsearch - object type, search nested elementsElasticsearch - 对象类型,搜索嵌套元素
【发布时间】:2020-11-21 01:23:30
【问题描述】:

我使用的是 Elasticsearch 7.2.0 版,并且在我的映射中具有以下类型:

"status_change": {
  "type": "object",
  "enabled": false
},

该字段内的数据示例:

"before": {
  "status_type": "Status One"
},
"after": {
  "status_type": "Status Two"
}

有各种状态类型,我正在尝试创建一个查询来识别从状态类型之前指定到状态类型之后指定的更改。我正在努力通过这些嵌套元素进行查询,但以下查询失败:

{
  "query": {
    "bool": {
       "must": {
          "match_all": {}
       },
       "filter": {
         "nested": {
           "path": "status_change",
           "query": {
              "term": {
                 "status_change.before": "the_before_status"
              }
           }
         }
       }
     }
   }
 }

与:

"caused_by" : {
  "type" : "illegal_state_exception",
  "reason" : "[nested] nested object under path [status_change] is not of nested type"
}

这是不言自明的,因为 status_change 不是“嵌套”字段。我曾尝试通过嵌套元素来搜索对象,但没有找到解决方案。

有没有办法让我像这样搜索嵌套的对象元素?

【问题讨论】:

    标签: elasticsearch


    【解决方案1】:

    您使用的不是nested 类型,而是object 类型。有区别,我建议您浏览上述链接。

    如果您使用的是嵌套类型

    将您的映射更改为以下内容:

    "status_change": {
      "type": "nested"
    }
    

    一旦您这样做,然后重新索引文档,您的查询将简单地返回包含 status_change.before: the_before_status 的文档列表,而不管您在文档中 status_change.after 下的值是什么。

    要基于status_change.after 进行进一步过滤,请在该字段中添加另一个must 子句以返回您正在查找的文档。

    如果您使用的是对象类型

    只需从映射中删除字段 enabled: false 并将查询更改为以下内容:

    POST <your_index_name>/_search
    {
      "query": {
        "bool": {
          "filter": [
            {
              "match": {
                "status_change.before.status_type": "the_before_status"
              }
            }
          ]
        }
      }
    }
    

    希望有帮助!

    【讨论】:

    • 如果 OP 不打算将对象数组索引到字段中,则无需使用嵌套类型。一个简单的对象类型(没有启用=false,并映射每个属性)就足够了。请参阅此处的示例elastic.co/guide/en/elasticsearch/reference/current/object.html
    • @DoronYaacoby 抱歉,我仍在使用您提到的替代选项更新我的答案。
    • 干杯,这是我对大约 10 亿条记录的集群所担心的,但感谢您的确认 :)
    猜你喜欢
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多