-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.js
83 lines (64 loc) · 3.43 KB
/
search.js
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module.exports = {
// Search through the user's highlights and return the most relevant posts
// PARAMETERS: MediumName, Keyword
Search: function (req, res) {
// require this stuff
var azure = require("azure-storage");
var MediumName = req.query.MediumName;
var Keyword = req.query.Keyword;
// Initialize Azure Table Service
var tableSvc = azure.createTableService();
tableSvc.retrieveEntity('MediumUsers', 'User', MediumName, function (error, result, response) {
if (!error) {
// Successful
var MediumUserID = result.MediumUserID['_'];
// Query to get user highlights from table
var query = new azure.TableQuery().where('PartitionKey eq ?', MediumUserID);
tableSvc.queryEntities('MediumHighlights', query, null, function (error, result, response) {
if (!error) {
// query was successful
//res.send(result.entries[0].PostName);
// Analyse and find 5 posts most relevant to the keyword
var relevanceScoreArray = [];
var highlightObjects = result.entries;
for (var i=0; i<highlightObjects.length; i++) {
var score = 1;
score += countOcurrences(highlightObjects[i].Paragraph['_'], Keyword);
score += countOcurrences(highlightObjects[i].PostName['_'], Keyword);
score += countOcurrences(highlightObjects[i].PostAuthor['_'], Keyword);
relevanceScoreObject = {
"index": i,
"score": score
}
relevanceScoreArray.push(relevanceScoreObject);
}
// Sorts the score array in descending order
// https://stackoverflow.com/a/979289/5640715
relevanceScoreArray.sort(function (a, b) {
return parseInt(b.score) - parseInt(a.score);
});
// Return upto top 5 results
var responseString = "";
for (var i=0; i < Math.min(5, highlightObjects.length); i++) {
responseString += "<h3>Post: " + highlightObjects[relevanceScoreArray[i].index].PostName['_'] +
"<br>Author: " + highlightObjects[relevanceScoreArray[i].index].PostAuthor['_'] +
"</h3><p>" + highlightObjects[relevanceScoreArray[i].index].Paragraph['_'] + "<br><br><br>";
//JSON.stringify(highlightObjects[relevanceScoreArray[i].index]);
}
res.set('Content-Type', 'text/html');
res.send(responseString + "</p>");
} else {
res.send(response);
}
});
} else {
res.send(response);
}
});
// https://stackoverflow.com/a/15891749/5640715
function countOcurrences(str, key) {
var regExp = new RegExp(key, "gi");
return (str.match(regExp) || []).length;
}
}
};