简体   繁体   中英

MongoDB+Doctrine: How to sort the query by text search score

I have a code like this that searches by the text index:

$expr = $queryBuilder->expr()->operator('$text', ['$search' => $this->value]);
$result = $queryBuilder->equals($expr)->getQuery()->execute();

But the result is not sorted by the relevance, which I want.

I found some info here but could not figure out how to add field score to search result using Doctrine.

I guess it would be easy from there just adding:

$queryBuilder->sort('score');

I could not find relevant documentation, but I did find this issue on the project's Github repo. The issue has a milestone of 1.2.0 release, but it seems it has already been released in the 1.1.x branch. The issue has been closed via this commit .

From the commit, it seems that all you need to sort your results by the textScore metadata info is one extra method call on the query builder:

$result = $queryBuilder
    ->equals($expr)
    ->sortMeta('fieldToSearch', 'textScore') // <- this
    ->getQuery()
    ->execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM