diff options
| author | Jake Mannens <jake@asger.xyz> | 2023-08-19 00:36:30 +1000 |
|---|---|---|
| committer | Jake Mannens <jake@asger.xyz> | 2025-08-18 17:03:21 +1000 |
| commit | d7bc8b58f750c1a5c629915ed2097e477d204a67 (patch) | |
| tree | c46146abd1261f28319f5973ad9182da57276347 /Services | |
| parent | 7dcc15cb52c29cc1c0112e3af2cf985b26cd7653 (diff) | |
Added basic search engine functionality
Diffstat (limited to 'Services')
| -rw-r--r-- | Services/SearchService.cs | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/Services/SearchService.cs b/Services/SearchService.cs new file mode 100644 index 0000000..8a109ea --- /dev/null +++ b/Services/SearchService.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; + +namespace HyperBooru.Services; + +public interface ISearchService { + public Media[] Search(string query); +} + +public class SearchService : ISearchService { + private IDbContextFactory<HBContext> dbFactory; + + public SearchService(IDbContextFactory<HBContext> dbFactory) => + this.dbFactory = dbFactory; + + public Media[] Search(string query) { + var db = dbFactory.CreateDbContext(); + + query = query.ToLower(); + + var matchedTag = db.TagDefinitions + .FirstOrDefault(td => td.Name.ToLower() == query)?.Guid; + + Guid[] guids; + + if(matchedTag is not null) { + guids = new[] { (Guid) matchedTag }; + } else { + guids = db.TagDefinitions + .Where(td => td.Name.ToLower().Contains(query)) + .Select(td => td.Guid) + .ToArray(); + } + + return db.Media + .Include(m => m.Tags) + .ThenInclude(m => m.TagDefinition) + .AsEnumerable() + .Where(m => m.Tags.IntersectBy(guids, t => t.TagDefinition.Guid).Any()) + .Concat(db.Media + .Where(m => + (m.ShortDescription != null && m.ShortDescription.ToLower().Contains(query)) || + (m.LongDescription != null && m.LongDescription.ToLower().Contains(query)))) + .DistinctBy(m => m.Guid) + .ToArray(); + } +} |
