Suggestions while the visitor types: after a short pause, the page asks your index for titles that start like the typed text.
01 · The request
Send it to the /autocomplete handler of your index. The handler has no settings of its own, so every request names the fields; /select answers the same request too.
https://YOUR_INDEX_HOST/solr/YOUR_INDEX/autocomplete
q={!edismax qf="title_tags title_tags_ws tags tags_ws" v=$uq}
uq=solar pan
fl=title,uri
rows=7
fq=content_type:text*
wt=json
02 · The four fields
| Field | Holds | Matches |
|---|---|---|
title_tags | The title, as one value | Titles that start with the typed text |
title_tags_ws | The title, word by word | Typing pan finds Solar Panels on its second word |
tags | The title, the description and the first words of the text, as one value | The same, on more text |
tags_ws | The same text, word by word | Any of those words by its beginning |
Opensolr fills them for every page it indexes. They match beginnings of 1 to 25 characters and are not sent back, so fl asks for title and uri. How they are analysed: text analysis.
03 · In the page
Wait about 150 to 200 ms after the last key and at least 2 characters, then call an endpoint on your own server that adds the credentials and forwards the request. Put the titles in the page as text, never as HTML.
var timer; input.addEventListener('input', function () { clearTimeout(timer); var text = input.value.trim(); if (text.length < 2) { list.replaceChildren(); return; } timer = setTimeout(function () { fetch('/suggest.php?q=' + encodeURIComponent(text)) .then(function (r) { return r.json(); }) .then(function (data) { list.replaceChildren(); ((data.response && data.response.docs) || []).forEach(function (doc) { var a = document.createElement('a'); if (/^https?:\/\//i.test(doc.uri || '')) a.href = doc.uri; a.textContent = doc.title; var li = document.createElement('li'); li.appendChild(a); list.appendChild(li); }); }); }, 180); });
<?php // suggest.php?q=solar+pan : forwards one autocomplete request to the index $q = mb_substr(trim((string)($_GET['q'] ?? '')), 0, 100); header('Content-Type: application/json'); if (mb_strlen($q) < 2) { echo '{"response":{"docs":[]}}'; exit; } $body = http_build_query([ 'q' => '{!edismax qf="title_tags title_tags_ws tags tags_ws" v=$uq}', 'uq' => $q, 'fl' => 'title,uri', 'rows' => 7, 'fq' => 'content_type:text*', 'echoParams' => 'none', 'wt' => 'json', ]); $ch = curl_init('https://YOUR_INDEX_HOST/solr/YOUR_INDEX/autocomplete'); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_USERPWD => 'opensolr:YOUR_API_KEY', CURLOPT_TIMEOUT => 3, ]); $result = curl_exec($ch); echo ($result !== false && curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200) ? $result : '{"response":{"docs":[]}}';
04 · Next
Spelling corrections after a search.
Suggestions there come from popular searches and from your titles, with nothing to set up.