From f919dab0e9677788745671515640223dc7ed20f0 Mon Sep 17 00:00:00 2001 From: bach Date: Mon, 15 Aug 2022 17:54:32 +0200 Subject: [PATCH] #1661 added phrase query before and then or querys of solr search --- .../materio_sapi/src/Controller/Base.php | 47 ++++++++++++++++++- 1 file changed, 45 insertions(+), 2 deletions(-) diff --git a/web/modules/custom/materio_sapi/src/Controller/Base.php b/web/modules/custom/materio_sapi/src/Controller/Base.php index d413e578..5d9a8528 100644 --- a/web/modules/custom/materio_sapi/src/Controller/Base.php +++ b/web/modules/custom/materio_sapi/src/Controller/Base.php @@ -44,6 +44,44 @@ class Base extends ControllerBase { 'nids' => [] ]; + // PHRASE QUERY + // (to match exact materials names (like "wood-skin")) + $this->phrase_query = $this->index->query(['offset'=>0,'limit'=>10000]); + // set parse mode and conjunction + $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode') + ->createInstance('phrase'); + $parse_mode->setConjunction('AND'); + $this->phrase_query->setParseMode($parse_mode); + // Set fulltext search keywords and fields. + if ($this->keys) { + $this->phrase_query->keys(implode(' ', $this->keys)); + } + $this->phrase_query->setFulltextFields(['title']); + + // Restrict the search to specific languages. + $this->phrase_query->setLanguages([$lang]); + + // Do paging. + // $this->and_query->range($this->offset, $this->limit); + // retrieve all results + // $this->and_query->range(0, -1); + + // Add sorting. + $this->phrase_query->sort('search_api_relevance', 'DESC'); + + // Set one or more tags for the query. + // @see hook_search_api_query_TAG_alter() + // @see hook_search_api_results_TAG_alter() + $this->phrase_query->addTag('materio_sapi_search_phrase_query'); + + $phrase_results = $this->phrase_query->execute(); + + foreach ($phrase_results as $result) { + $this->results['uuids'][] = $result->getField('uuid')->getValues()[0]; + $this->results['nids'][] = $result->getField('nid')->getValues()[0]; + } + + // AND QUERY $this->and_query = $this->index->query(['offset'=>0,'limit'=>10000]); // set parse mode and conjunction @@ -141,10 +179,15 @@ class Base extends ControllerBase { $and_results = $this->and_query->execute(); foreach ($and_results as $result) { - $this->results['uuids'][] = $result->getField('uuid')->getValues()[0]; - $this->results['nids'][] = $result->getField('nid')->getValues()[0]; + // !! have to remove duplicates from phrase query + $nid = $result->getField('nid')->getValues()[0]; + if ( !in_array($nid, $this->results['nids']) ) { + $this->results['uuids'][] = $result->getField('uuid')->getValues()[0]; + $this->results['nids'][] = $result->getField('nid')->getValues()[0]; + } } + $this->exactematch_count = count($this->results['nids']);