Skip to content

Instantly share code, notes, and snippets.

@LuceCarter
Created February 26, 2024 10:58
Show Gist options
  • Save LuceCarter/fa43ea5a4c28c43aa27d5e54f88079f4 to your computer and use it in GitHub Desktop.
Save LuceCarter/fa43ea5a4c28c43aa27d5e54f88079f4 to your computer and use it in GitHub Desktop.
Atlas Full-Text Search with .NET Blazor Snippets
@code {
//...
string searchTerm;
Timer debounceTimer;
int debounceInterval = 200;
//...
private void SearchMovies()
{
if (string.IsNullOrWhiteSpace(searchTerm))
{
movies = MongoDBService.GetAllMovies();
}
else
{
movies = MongoDBService.MovieSearchByText(searchTerm);
}
}
void DebounceSearch(object state)
{
if (string.IsNullOrWhiteSpace(searchTerm))
{
SearchMovies();
}
else
{
InvokeAsync(() =>
{
SearchMovies();
StateHasChanged();
});
}
}
void OnSearchInput(ChangeEventArgs e)
{
searchTerm = e.Value.ToString();
debounceTimer?.Dispose();
debounceTimer = new Timer(DebounceSearch, null, debounceInterval, Timeout.Infinite);
}
}
//...
<div class="form-inline search-bar">
<input class="form-control mr-sm-2"
type="search" placeholder="Search"
aria-label="Search"
@oninput="OnSearchInput" @bind="searchTerm">
</div>
//...
public IEnumerable<Movie> MovieSearchByText (string textToSearch);
using SeeSharpMovies.Models;
using MongoDB.Driver;
using MongoDB.Driver.Search;
//...
public IEnumerable<Movie> MovieSearchByText(string textToSearch)
{
// define fuzzy options
SearchFuzzyOptions fuzzyOptions = new SearchFuzzyOptions()
{
MaxEdits = 1,
PrefixLength = 1,
MaxExpansions = 256
};
// define and run pipeline
var movies = _movies.Aggregate().Search(Builders<Movie>.Search.Autocomplete(movie => movie.Title,
textToSearch, fuzzy: fuzzyOptions), indexName: "title").Project<Movie>(Builders<Movie>.Projection
.Exclude(movie => movie.Id)).ToList();
return movies;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment