You are here

function apachesolr_autocomplete_suggest_word_completion in Apache Solr Autocomplete 6

Same name and namespace in other branches
  1. 7.2 apachesolr_autocomplete.module \apachesolr_autocomplete_suggest_word_completion()
  2. 7 apachesolr_autocomplete.module \apachesolr_autocomplete_suggest_word_completion()

Helper function that suggests ways to complete partial words.

For example, if $keys = "learn", this might return suggestions like: learn, learning, learner, learnability. The suggested terms are returned in order of frequency (most frequent first).

1 call to apachesolr_autocomplete_suggest_word_completion()
apachesolr_autocomplete_callback in ./apachesolr_autocomplete.module
Callback for url apachesolr_autocomplete/autocomplete.

File

./apachesolr_autocomplete.module, line 216
Alters search forms to suggest terms using Apache Solr using AJAX. Thanks to robertDouglass who contributed some of the code.

Code

function apachesolr_autocomplete_suggest_word_completion($keys, $suggestions_to_return = 5) {

  /**
   * Split $keys into two:
   *  $first_part will contain all complete words (delimited by spaces). Can be empty.
   *  $last_part is the (assumed incomplete) last word. If this is empty, don't suggest.
   * Example:
   *  $keys = "learning dis" : $first_part = "learning", $last_part = "dis"
   */
  preg_match('/^(:?(.* |))([^ ]+)$/', $keys, $matches);
  $first_part = @$matches[2];

  // Make sure $last_part contains meaningful characters
  $last_part = preg_replace('/[' . PREG_CLASS_SEARCH_EXCLUDE . ']+/u', '', $matches[3]);
  if ($last_part == '') {
    return array();
  }

  // Ask Solr to return facets that begin with $last_part; these will be the suggestions.
  $params = apachesolr_autocomplete_basic_params($suggestions_to_return);
  $params['facet.prefix'] = $last_part;

  // Get array of themed suggestions.
  $result = apachesolr_autocomplete_suggest($first_part, $params, $keys, $suggestions_to_return);
  if ($result && $result['suggestions']) {
    return $result['suggestions'];
  }
  else {
    return array();
  }
}