Created
February 26, 2024 10:58
-
-
Save LuceCarter/fa43ea5a4c28c43aa27d5e54f88079f4 to your computer and use it in GitHub Desktop.
Atlas Full-Text Search with .NET Blazor Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//... | |
<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> | |
//... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public IEnumerable<Movie> MovieSearchByText (string textToSearch); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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