【问题标题】:Elastic JSON query to PHP associative array and empty objects对 PHP 关联数组和空对象的弹性 JSON 查询
【发布时间】:2016-05-21 09:45:33
【问题描述】:

我有这个工作正常的弹性搜索查询,但我无法将它完全转换为 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);

【问题讨论】:

  • 'fields' => [0=>'url']'fields' => ['content.content'=> '']。试试看
  • 谢谢!它几乎可以工作,错误消失了,但在 Elastic 的响应中,没有突出显示部分。也许是一个单独的问题?
  • 因为你的高亮部分没有价值,所以没有高亮部分
  • 当我使用 Sense Chrome 插件尝试 POST 时,一个空的 highlight 部分返回了突出显示的搜索词。

标签: php post elasticsearch associative-array


【解决方案1】:

您在 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 '{}' */
    ]
  ]
];

见:https://stackoverflow.com/a/8595884/118593

【讨论】:

  • highlight 中做'fields' => ['content.content'=> new stdClass] 有帮助!否则,highlight 部分不会出现在搜索结果中。 JSON 中这样的空对象,我从来不知道!
  • 感谢指出字符串没有被插值,我现在已经更正了
  • 考虑使用github.com/ongr-io/ElasticsearchDSL helper 来编写查询。删除了很多样板代码。
【解决方案2】:

只要做:

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 (
      ),
    ),
  ),
)

【讨论】:

  • 优雅,但搜索结果中没有 highlight 部分/来自 Elastic 的回复:(。
猜你喜欢
  • 1970-01-01
  • 2021-01-18
  • 2012-08-30
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 2014-10-29
  • 2016-01-11
相关资源
最近更新 更多