-
Notifications
You must be signed in to change notification settings - Fork 11
/
PostRanker.cs
56 lines (51 loc) · 2.04 KB
/
PostRanker.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using Opw.PineBlog.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Opw.PineBlog.Posts.Search
{
// TODO: add more test for ranking (hits count)
public class PostRanker : IPostRanker
{
public IEnumerable<Post> Rank(IEnumerable<Post> posts, string query)
{
if (posts == null || !posts.Any())
{
return new List<Post>();
}
var terms = query.ParseTerms();
var rankedPosts = new List<Tuple<Post, int>>();
foreach (var post in posts)
{
var rank = 0;
foreach (var term in terms)
{
int hits;
if (!string.IsNullOrWhiteSpace(post.Title) && post.Title.ToLower().Contains(term))
{
hits = Regex.Matches(post.Title.ToLower(), term).Count;
rank += hits * 10;
}
if (!string.IsNullOrWhiteSpace(post.Categories) && post.Categories.ToLower().Contains(term))
{
hits = Regex.Matches(post.Categories.ToLower(), term).Count;
rank += hits * 10;
}
if (!string.IsNullOrWhiteSpace(post.Description) && post.Description.ToLower().Contains(term))
{
hits = Regex.Matches(post.Description.ToLower(), term).Count;
rank += hits * 3;
}
if (!string.IsNullOrWhiteSpace(post.Content) && post.Content.ToLower().Contains(term))
{
hits = Regex.Matches(post.Content.ToLower(), term).Count;
rank += hits * 1;
}
}
rankedPosts.Add(new Tuple<Post, int>(post, rank));
}
return rankedPosts.OrderByDescending(t => t.Item2).Select(t => t.Item1).ToList();
}
}
}