13

我刚刚在我的 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”值。但是,这些标签 -<em></em>根本不会添加到结果中。我看到的只是field1像“ some text 23”,“ 23 another text”这样的原始值。这不是我期望看到的——“ some text <em>23</em>”、“ <em>23</em> another text”。那么,这有什么问题,我该如何解决?

4

1 回答 1

18

从手册

  1. pre_tagsand的值post_tags应该是一个数组(但是,如果您不想更改em标签,可以忽略它们,它们已经设置为默认值)。
  2. fieldsvalue 应该是一个数组,key 是字段名称,value 是一个带有字段选项的数组。

试试这个修复:

$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']

于 2016-11-02T01:15:12.130 回答