D.A BLOG PROJECTS NOW DATA NOTES

How to implement a search engine in SvelteKit

Allowing users to search within your website may be necessary to make navigation easier for them. Wow, it’s not that difficult in SvelteKit!

Date: 17 Oct 2024 · 6 min read

Premessa: This article was written after I had implemented the following guide: How To Make A Blazing Fast SvelteKit Search. This article is a translation and adaptation of the content in that guide, following my implementation on my own website.

Motore di ricerca

Example of a search engine in SvelteKit

Dependencies

To implement a search engine in SvelteKit, we’ll need just one dependency: flexsearch. This library will enable us to search within our website based on the content of our articles or pages.

npm install flexsearch

File system structure

The structure we need for the search engine to work is as follows:

src/
├── lib/
│   └── search.ts
└── routes/
    ├── search.json/
    │   └── +server.ts
    └── +page.svelte

Where:

  • search.ts is the file that will contain the index and the search function.
  • search.json is an endpoint we’ll use to pre-render the search results as a json, and this will allow us to avoid having to save a file json manually.
  • +page.svelte This is the page that will contain our search engine; you can then display it wherever you like.

Implementation

search.ts

import type { Element } from '$lib/types';
import { json } from '@sveltejs/kit';


export const prerender = true

export async function GET({fetch}) {

    // Fetch dei post
    const response = await fetch('api/posts');
    const posts: Element[] = await response.json();

    // Aggiunta poiché ho 2 tipi di pagine
    posts.forEach(post => {
        post.slug = 'pagine/' + post.slug;
    });

    // Fetch dei progetti
    const res2 = await fetch('api/progetti');
    const progetti: Element[] = await res2.json();

    progetti.forEach(post => {
        post.slug = 'progetti/' + post.slug;
    });


    // Ritorno dei dati come JSON
    return json({ posts, progetti});
}

Nota: I already have an endpoint that returns all posts and projects, so I used that one. If you don’t have a similar endpoint, you can create a file api/posts.ts and api/progetti.ts that return the posts and projects, as my files containing the posts are in Markdown and are saved as plain text files .md, I don’t fetch them from any external API.

search.json

import FlexSearch from 'flexsearch'
import type { Element } from '$lib/types';


let postsIndex: FlexSearch.Index
let posts: Element[]

export function createIndex(data: any) {
    // Crea un indice di ricerca per i post

    // Tokenize 'forward' per accettare anche le ricerche parziali
    // mentre per le ricerche esatte si può usare 'strict'
    postsIndex = new FlexSearch.Index({ tokenize: 'forward' })


    // Join perché ho sia i post che i progetti
    data = data.posts.concat(data.progetti);
    
    data.forEach((post: { title: any; description: any; }, i: FlexSearch.Id) => {

        // Crea un item con il titolo e la descrizione del post
        const item = `${post.title} ${post.description}`

        // Aggiungi l'item all'indice
        postsIndex.add(i, item)
    })

    posts = data
}

    export function searchPostsIndex(searchTerm: string) {
    // escape special regex characters
    const match = searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    // return matching post indexes 💪
    const results = postsIndex.search(match)

    return results
        // filter the posts based on the matched index
        .map((index) => posts[index as number])
        // you can do whatever you want at this point 👌
        .map(({ slug, title, description }) => {
            return {
                slug,
                // replace match in title with a marker
                title: replaceTextWithMarker(title, match),
                // match words in post and replace matches with marker
                content: getMatches(description, match, 3)
            }
        })
}


function getMatches(text: string, searchTerm: string, limit = 1) {
    // Regex per la ricerca
    const regex = new RegExp(searchTerm, 'gi')
    // Indici
    const indexes = []
    // Matches
    let matches = 0
    // Loop per trovare i match
    let match
    while ((match = regex.exec(text)) !== null && matches < limit) {
        // Aggiungi l'indice
        indexes.push(match.index)
        // Incrementa i match
        matches++
    }

    // Ritorna l'array di indici
    return indexes.map((index) => {
        // Vai indietro di 20 caratteri
        const start = index - 20
        // Vai avanti di 80 caratteri
        const end = index + 80
        // Estrai il testo
        const excerpt = text.substring(start, end).trim()
        // Ritorna l'estratto con i match
        return `...${replaceTextWithMarker(excerpt, searchTerm)}...`
    })
}

function replaceTextWithMarker(text: string, match: string) {
    // Regex per la ricerca
    const regex = new RegExp(match, 'gi')
    // Ritorna il testo con il match evidenziato
    return text.replaceAll(regex, (match) => `<mark>${match}</mark>`)
}

Essentially, what happens is this:

  1. We create a search index for posts and projects.
  2. We create a function that allows us to search within the index.
  3. We create a function that allows us to highlight matches within the text.
  4. We create a function that allows us to retrieve the matches within the text.
  5. We return the results.

Componente di ricerca



<div class="search-icon">
	<button on:click={() => (showModal = !showModal)}>
		<span class="material-symbols-outlined"> search </span>
	</button>
</div>


<Modal bind:dialog={dialog} bind:showModal isSearch={true}>
	{#if search === 'ready'}
		<div class="search">
			<input
				bind:value={searchTerm}
				placeholder="Cerca..."
				autocomplete="off"
				spellcheck="false"
				type="search"
			/>

			<div class="results">
				{#if results}
					<ul>
						{#each results as result (result.slug)}
							<div
								on:click={() => {
									goto("/" + result.slug);
									showModal = false;
									searchTerm = '';
									dialog.close();
								}}
								class="link"
								transition:fade={{
									duration: 20
								}}
							>
								<h3>
									{@html result.title}
								</h3>
								<p>{@html result.content}</p>
							</div>
						{/each}
					</ul>
				{/if}
			</div>
		</div>
	{/if}
</Modal>

<style>
	.search {
		padding: 1em;
	}

	.search-icon{
		transform: translateY(0);
	}

	@media (min-width: 1300px) {
		.search-icon{
			transform: translateY(-10px);
		}
	}

	button {
		background-color: var(--automataBlackO);
		color: var(--automataWhite);
		border: none;
		padding: 0.5em;
		cursor: pointer;
		border-radius: 100%;
	}

	input {
		width: 100%;
		padding: 0.5em;
		font-size: 1em;
		background-color: var(--automataBlackO);
		color: var(--automataWhite);
	}

	h3 {
		margin: 0;
		color: var(--automataWhite);
	}

	/* input placeholder */
	::placeholder {
		color: var(--automataWhite);
	}

	.results {
		margin-top: 1em;
	}

	.results ul {
		list-style: none;
		padding: 0;
	}

	ul {
		list-style: none;
		display: flex;
		flex-direction: column;
		gap: 2em;
	}

	.link {
		cursor: pointer;
		background-color: var(--automataBlackOpacity);
		color: var(--automataWhite);
		padding: 1em;
		transition: background-color 0.3s;
	}

	.link:hover {
		background-color: var(--automataBlackO);
	}

	.results p {
		margin-top: 0.5em;
	}
</style>

I’ve kept the styling I use for my component, which won’t work for you, as I also use a modal within it to carry out the search without taking over the page. What’s important is the logic of the search engine.

The component’s logic is very simple:

  1. When the component is mounted, we fetch the posts from our endpoint and create the search index.
  2. When the component is ready, we search the index based on our query.
  3. We display the results.

Conclusions

In his article, Joy Of Code also includes a section on using a Web Worker to boost the search engine’s performance, but I haven’t implemented this as I haven’t experienced any performance issues. If you do encounter performance issues, I’d recommend taking a look at his article, as you won’t find anything on this subject here for the time being.

There may also be cases where, even with just a single letter, the search engine returns results; however, this is because I chose to perform a partial search rather than an exact match. If you wish to perform an exact search, you can change the parameter tokenize within the file search.ts from forward to strict as mentioned earlier.

Risultati ricerca

Search results are a bit excessive

At the moment, I don’t think the search engine is working optimally, because I haven’t yet implemented searching by tags or by content within the posts, as I haven’t yet restructured certain parts of the data to make them accessible without too much fiddling about. Who knows, perhaps I’ll implement it in the future, but now is certainly not the time.

Author

Daniele lovaion Avolio

Developer, video game lover 🎮 and fan of Japanese pop culture 🗾