You are here

function apachesolr_autocomplete_suggest_word_completion in Apache Solr Autocomplete 7

Same name and namespace in other branches
  1. 6 apachesolr_autocomplete.module \apachesolr_autocomplete_suggest_word_completion()
  2. 7.2 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).

Parameters

string $keys: Keys to search for.

int $suggestions_to_return: Number of suggestions to return.

array $search_page: Search page.

Return value

array Suggestions array.

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 334
Alters search forms to suggest terms using Apache Solr using AJAX. Thanks to: robertDouglass who contributed some of the code. sch4lly for contributing to D7 version

Code

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

  /**
   * 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_UNICODE_WORD_BOUNDARY . ']+/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, $search_page);
  $params['facet.prefix'] = strtolower($last_part);

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