PHP 呼叫 ES API 小插曲

yourself發表於2018-09-07

描述

kibana測試語句

GET products/products/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "category_id": "1"
          }
        }
      ]
    }
  },
  "aggs": {
    "single_category_avg_price": {
      "avg": {
        "field": "price"
      }
    },
    "all":{
      "global": {},
      "aggs": {
        "all_brand_avg_price": {
          "avg": {
            "field": "price"
          }
        }
      }
    }
  }
}

複製到php執行,結果額~~~,弱型別語言的悲劇

$result = Product::searchRaw( [
            "query" => [
                "bool" => [
                    "must" => [
                        [
                            "match" => [
                                "category_id" => $categoryId
                            ]
                        ]
                    ]
                ]
            ],
            "aggs"  => [
                "single_category_avg_price" => [
                    "avg" => [
                        "field" => "price"
                    ]
                ],
                "all"                       => [
                    "global" =>[],
                    "aggs"   => [
                        "all_category_avg_price" => [
                            "avg" => [
                                "field" => "price"
                            ]
                        ]
                    ]
                ]
            ]
        ] );

報錯global應該是一個物件

{
    "error": {
        "root_cause": [{
            "type": "parsing_exception",
            "reason": "Expected [START_OBJECT] under [global], but got a [START_ARRAY] in [all]",
            "line": 1,
            "col": 139
        }],
        "type": "parsing_exception",
        "reason": "Expected [START_OBJECT] under [global], but got a [START_ARRAY] in [all]",
        "line": 1,
        "col": 139
    },
    "status": 400
}

修改程式碼解決

$result = Product::searchRaw( [
            "query" => [
                "bool" => [
                    "must" => [
                        [
                            "match" => [
                                "category_id" => $categoryId
                            ]
                        ]
                    ]
                ]
            ],
            "aggs"  => [
                "single_category_avg_price" => [
                    "avg" => [
                        "field" => "price"
                    ]
                ],
                "all"                       => [
                    "global" =>new \stdClass(),//修改這裡 傳遞物件
                    "aggs"   => [
                        "all_category_avg_price" => [
                            "avg" => [
                                "field" => "price"
                            ]
                        ]
                    ]
                ]
            ]
        ] );

相關文章