弹性 JSON 查询 PHP 关联数组和空对象

Elastic JSON query to PHP associative array and empty objects

我有这个 Elastic 搜索查询,它运行良好,但我无法将其完全转换为 PHP 关联数组。

POST /index/type/_search
{
  "fields": [
   "url"
   ],
  "query": {
     "query_string": {
         "default_field": "content.content",
         "query": "german"
      }
   },
  "highlight": {
      "fields": {
         "content.content": {}
       }
  }
}

上面 POST 中的 fieldshighlight 部分如何在 PHP 关联数组中表示?我在下面的尝试,除了 /* ERROR */

$params = [
  'index' => $index_name,
  'type' => 'type_name',
  'body' => [
    'fields' => 'url'      /* ERROR */ 
    'query' => [
        'query_string' => [
            'default_field' => 'content.content',
            'query' => $search_term
        ]
    ],
    'highlight' => [
        'fields' => ['content.content'=> []]   /*  ERROR */
    ]
  ]
];

当然有了上面的$params,我会做:

$results = Elastic_PHP_client->search($params);

就这样:

var_export(json_decode($json, true));

生成可用的 PHP 代码:

array (
  'fields' =>
  array (
    0 => 'url',
  ),
  'query' =>
  array (
    'query_string' =>
    array (
      'default_field' => 'content.content',
      'query' => 'german',
    ),
  ),
  'highlight' =>
  array (
    'fields' =>
    array (
      'content.content' =>
      array (
      ),
    ),
  ),
)

您在 PHP 中解决了 []{} 的区别问题。

如果客户端在某个时候json_encode,那么这样做:

$params = [
  'index' => $index_name,
  'type' => 'type_name',
  'body' => [
    'fields' => ['url'],
    'query' => [
        'query_string' => [
            'default_field' => 'content.content',
            'query' => '$search_term' /* Be carefull, not interpolated */
        ]
    ],
    'highlight' => [
        'fields' => ['content.content'=> new stdClass] /* Will give you '{}' */
    ]
  ]
];

参见: