|
| 1 | +<?php |
| 2 | +namespace Flowpack\ElasticSearch\ContentRepositoryAdaptor\Eel; |
| 3 | + |
| 4 | +/* |
| 5 | + * This file is part of the Flowpack.ElasticSearch.ContentRepositoryAdaptor package. |
| 6 | + * |
| 7 | + * (c) Contributors of the Neos Project - www.neos.io |
| 8 | + * |
| 9 | + * This package is Open Source Software. For the full copyright and license |
| 10 | + * information, please view the LICENSE file which was distributed with this |
| 11 | + * source code. |
| 12 | + */ |
| 13 | + |
| 14 | +use TYPO3\Eel\ProtectedContextAwareInterface; |
| 15 | +use TYPO3\Flow\Annotations as Flow; |
| 16 | + |
| 17 | +/** |
| 18 | + * Eel Helper to process the ElasticSearch Query Result |
| 19 | + */ |
| 20 | +class SearchResultHelper implements ProtectedContextAwareInterface |
| 21 | +{ |
| 22 | + |
| 23 | + /** |
| 24 | + * The "didYouMean" operation processes the previously defined suggestion by extracting |
| 25 | + * and concatenating the best guess for each word given in the search term. |
| 26 | + * A threshold can be given as second parameter. If none of the suggestions reaches this |
| 27 | + * threshold, an empty string is returned. |
| 28 | + * |
| 29 | + * Example:: |
| 30 | + * |
| 31 | + * searchQuery = ${Search.query(site).fulltext('noes cms').termSuggestions('noes cms')} |
| 32 | + * didYouMean = ${SearchResult.didYouMean(this.searchQuery.execute(), 0.5)} |
| 33 | + * |
| 34 | + * @param ElasticSearchQueryResult $searchResult The result of an elastic search query |
| 35 | + * @param float $scoreThreshold The minimum required score to return the suggestion |
| 36 | + * @param string $suggestionName The suggestion name which was given in the suggestion definition |
| 37 | + * @return string |
| 38 | + */ |
| 39 | + public function didYouMean(ElasticSearchQueryResult $searchResult, $scoreThreshold = 0.7, $suggestionName = 'suggestions') |
| 40 | + { |
| 41 | + $maxScore = 0; |
| 42 | + $suggestionParts = []; |
| 43 | + |
| 44 | + foreach ($searchResult->getSuggestions()[$suggestionName] as $suggestion) { |
| 45 | + if (array_key_exists('options', $suggestion) && !empty($suggestion['options'])) { |
| 46 | + $bestSuggestion = current($suggestion['options']); |
| 47 | + $maxScore = $bestSuggestion['score'] > $maxScore ? $bestSuggestion['score'] : $maxScore; |
| 48 | + $suggestionParts[] = $bestSuggestion['text']; |
| 49 | + } else { |
| 50 | + $suggestionParts[] = $suggestion['text']; |
| 51 | + } |
| 52 | + } |
| 53 | + if ($maxScore >= $scoreThreshold) { |
| 54 | + return implode(' ', $suggestionParts); |
| 55 | + } |
| 56 | + |
| 57 | + return ''; |
| 58 | + } |
| 59 | + |
| 60 | + /** |
| 61 | + * @param string $methodName |
| 62 | + * @return boolean |
| 63 | + */ |
| 64 | + public function allowsCallOfMethod($methodName) |
| 65 | + { |
| 66 | + return true; |
| 67 | + } |
| 68 | +} |
0 commit comments