Search code examples
phpsearchelasticsearchhighlightingfoselasticabundle

FOSElastica Bundle : retrieving highlights for results


I'm trying to have highlights returned with a global index search with the FOSElastica Bundle.

I have a global index finder in my configuration (yml file):

fos_elastica:
  clients:
    default: { host: %elastic_host%, port: %elastic_port% }
  indexes:
    myIndex:
      client: default
      finder: ~
      types: 
       # different types here

and I use it as per the doc (here) :

$finder = $this->container->get('fos_elastica.finder.myIndex');

// Returns a mixed array of any objects mapped
$results = $finder->find('whatever');

That works perfectly and returns the expected results. Now I would like to highlight the words found in the results using for instance the fast vector highlighter of ES. But I did not find any example or any documentation to do so.

I guess I need to define a more proper \Query object with something like :

$query = new \Elastica\Query();
$query->setHighlights(array("whatever"));
$query->setTerm("whatever");

$results = $finder->find($query);

But I cannot find any information. Any hint ?

Thanks a lot !!


Solution

  • Write the query in JSON first:

    {
        "query" : {
            "match" : {
                "content" : "this is a test"
            }
        },
        "highlight" : {
            "fields" : {
                "content" : {}
            }
        }
    }
    

    When it works, translate to Elastica:

    $matchQuery = new \Elastica\Query\Match();
    $matchQuery->setField('content', 'this is a test');
    
    $searchQuery = new \Elastica\Query();
    $searchQuery->setQuery($matchQuery);
    
    $searchQuery->setHighlight(array(
        "fields" => array("content" => new \stdObject())
    ));