Elasticsearch. Highlight search results

July 1, 2016 24 Yehor Rykhnov

Elasticsearch. Part 6, highlighting search results in Elasticsearch. Previous part: Elasticsearch. Full-text search.

Often the need to allocate a search phrase in the search results. Elasticsearch has built-in mechanisms for the selection and framing of the search result to HTML tags. An example of the highlighting of search results in Elasticsearch using CURL, PHP and Yii2.

Highlight of tags search results.

Command:

GET /megacorp/employee/_search
{ "query" : { "match_phrase" : { "about" : "rock climbing" } }, "highlight": { "fields" : { "about" : {} } } }

Highlighting of search results in CURL:

$curl -XPOST 'localhost:9200/megacorp/employee/_search?pretty' -d '
{
    "query" : 
    {
        "match_phrase" : 
        {
            "about" : "rock climbing"
        }
    },
    "highlight": 
    {
        "fields" : 
        {
            "about" : {}
        }
    }
}'

Highlighting of search results in PHP:

require '../vendor/autoload.php';
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
            'index' => 'megacorp',
            'type'  => 'employee',
            'body'  => [
                'query' => [
                    'match' => [
                        "about" => "rock climbing"
                    ],                
        ], 
        'highlight' => [
                    "pre_tags"  => "<em>",
                    "post_tags" => "</em>",
                    'fields'    => [
                       'about' => new \stdClass()
                    ]
                ],
            ]
        ];
try {            
    $response = $client->search($params);
} catch (Exception $e) {            
    var_dump($e->getMessage());        
}
var_dump($response);

'about' => new \stdClass() - stdClass it is used for the proper formation of JSON.

Highlighting of search results in Yii2:

$params = [
            'match' => [
                "about" => "rock climbing"
            ]
        ];
$model = Megacorp::find()
                ->query($params)
                ->highlight([
                    "pre_tags"  => "<em>",
                    "post_tags" => "</em>",
                    'fields'    => [
                        'about' => new \stdClass()
                    ]
                ])
                ->all();
var_dump($model);

Additionally

Detailed documentation https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-highlighting.html