【问题标题】:Highlighting does not work in Elasticsearch and PHP突出显示在 Elasticsearch 和 PHP 中不起作用
【发布时间】:2023-03-10 11:45:01
【问题描述】:

我刚刚在我的 Windows 机器上下载并安装了最新版本的 Elasticsearch。我做了第一次搜索查询,一切似乎都正常。然而。当我尝试突出显示搜索结果时,我失败了。所以,这就是我的查询的样子:

$params = [
    'index' => 'test_index',
    'type' => 'test_index_type',
    'body' => [
        'query' => [
            'bool' => [
                'should' => [ 'match' => [ 'field1' => '23' ] ]
            ]
        ],
        'highlight' => [
            'pre_tags' => "<em>", 
            'post_tags' => "</em>",
            'fields' => (object)Array('field1' => new stdClass),
            'require_field_match' => false
        ]
     ]     
]

$res = $client->search($params);

总的来说,查询本身运行良好 - 结果被过滤。在我看到的控制台中,所有文档的field1 字段中确实包含“23”值。但是,这些标签 - &lt;em&gt;&lt;/em&gt; 根本不会添加到结果中。我看到的只是field1 中的原始值,例如“some text 23”、“23 another text”。这不是我期望看到的——“some text &lt;em&gt;23&lt;/em&gt;”、“&lt;em&gt;23&lt;/em&gt; another text”。那么,这有什么问题,我该如何解决呢?

【问题讨论】:

  • 看起来pre_tagspost_tags 可能需要一个数组...您可以尝试将这两个字符串都包装在em 中的[] 中吗?
  • 您是否尝试在 PHP 之外运行该查询? (例如使用 Kibana 中的 Sense 插件或简单的 curl 命令。)突出显示是否有效?
  • @Andrei Stefan。不,我还没有尝试过。
  • @Sam。它没有帮助。我检查了它。我得到过滤结果,但没有任何突出显示
  • @Andrei Stefan。我尝试了 curl,但它在 Windows 上的效果非常糟糕。我无法发出包含 -d 标志和一些 json 正文的请求 - 在这种情况下,在 Windows 上我遇到了一些解析错误。

标签: php elasticsearch elasticsearch-5


【解决方案1】:

From the manual:

  1. pre_tagspost_tags 的值应该是一个数组(但是如果您不想更改 em 标记可以忽略它们,它们已经设置为默认值)。
  2. fields 值应该是一个数组,键是字段名,值是一个包含字段选项的数组。

试试这个修复:

$params = [
    'index' => 'test_index',
    'type' => 'test_index_type',
    'body' => [
        'query' => [
            'bool' => [
                'should' => [ 'match' => [ 'field1' => '23' ] ]
            ]
        ],
        'highlight' => [
            // 'pre_tags' => ["<em>"], // not required
            // 'post_tags' => ["</em>"], // not required
            'fields' => [
                'field1' => new \stdClass()
            ],
            'require_field_match' => false
        ]
     ]     
];

$res = $client->search($params);
var_dump($res['hits']['hits'][0]['highlight']);

更新

  1. 仔细检查,fields数组中的字段值应该是一个对象(这是一个要求,与其他选项不完全相同)。
  2. pre/post_tags 也可以是字符串(而不是数组)。
  3. 您是否检查了正确的响应? $res['hits']['hits'][0]['highlight']

需要注意的重要一点是,highligted 结果进入highlight 数组 - $res['hits']['hits'][0]['highlight']

【讨论】:

  • 谢谢!我会在一分钟内检查它。
  • 不幸的是,它不起作用。现在我收到此错误消息[highlight_field] Expected START_OBJECT but was: START_ARRAY。所以,我认为,在您的示例中 'field1' =&gt; [] 存在一些问题。顺便说一句,在文档中它看起来像"fields" : { "content" : {} }。我在这里看不到数组。
  • 虽然,这个结构正在工作 - 'fields' =&gt; ['field1' =&gt; (object)[]]。但是,无论是默认的 pre_tags 和 post_tags(当我忽略它们时),还是隐含的 'pre_tags' =&gt; ['&lt;em&gt;'], 'post_tags' =&gt; ['&lt;/em&gt;'] 都不起作用。
  • @Jacobian,请检查更新。你用的是哪个版本的php库?
  • 我用 composer 安装了这个库。该文件看起来像{"require": { "elasticsearch/elasticsearch": "~5.0" }}
猜你喜欢
  • 2012-08-08
  • 2017-01-02
  • 2011-10-09
  • 2016-02-24
  • 2019-12-08
  • 1970-01-01
  • 2016-05-25
  • 2016-01-16
  • 1970-01-01
相关资源
最近更新 更多