add scoring and sort to search plugin
This commit is contained in:
parent
78f5564a30
commit
bc1d8e4bda
1 changed files with 13 additions and 14 deletions
|
|
@ -96,29 +96,27 @@ export function search(query) {
|
||||||
|
|
||||||
for (let i = 0; i < data.length; i++) {
|
for (let i = 0; i < data.length; i++) {
|
||||||
const post = data[i]
|
const post = data[i]
|
||||||
let isMatch = false
|
let matchesScore = 0
|
||||||
let resultStr = ''
|
let resultStr = ''
|
||||||
const postTitle = post.title && post.title.trim()
|
const postTitle = post.title && post.title.trim()
|
||||||
const postContent = post.body && post.body.trim()
|
const postContent = post.body && post.body.trim()
|
||||||
const postUrl = post.slug || ''
|
const postUrl = post.slug || ''
|
||||||
|
|
||||||
if (postTitle && postContent) {
|
if (postTitle) {
|
||||||
keywords.forEach(keyword => {
|
keywords.forEach( keyword => {
|
||||||
// From https://github.com/sindresorhus/escape-string-regexp
|
// From https://github.com/sindresorhus/escape-string-regexp
|
||||||
const regEx = new RegExp(
|
const regEx = new RegExp(
|
||||||
keyword.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'),
|
keyword.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'),
|
||||||
'gi'
|
'gi'
|
||||||
)
|
);
|
||||||
let indexTitle = -1
|
let indexTitle = -1
|
||||||
let indexContent = -1
|
let indexContent = -1
|
||||||
|
|
||||||
indexTitle = postTitle && postTitle.search(regEx)
|
indexTitle = postTitle ? postTitle.search(regEx) : -1
|
||||||
indexContent = postContent && postContent.search(regEx)
|
indexContent = postContent ? postContent.search(regEx) : -1
|
||||||
|
|
||||||
if (indexTitle < 0 && indexContent < 0) {
|
if (indexTitle >= 0 || indexContent >= 0) {
|
||||||
isMatch = false
|
matchesScore += indexTitle >= 0 ? 3 : indexContent >= 0 ? 2 : 0;
|
||||||
} else {
|
|
||||||
isMatch = true
|
|
||||||
if (indexContent < 0) {
|
if (indexContent < 0) {
|
||||||
indexContent = 0
|
indexContent = 0
|
||||||
}
|
}
|
||||||
|
|
@ -144,11 +142,12 @@ export function search(query) {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
if (isMatch) {
|
if (matchesScore > 0) {
|
||||||
const matchingPost = {
|
const matchingPost = {
|
||||||
title: escapeHtml(postTitle),
|
title: escapeHtml(postTitle),
|
||||||
content: resultStr,
|
content: postContent ? resultStr : '',
|
||||||
url: postUrl
|
url: postUrl,
|
||||||
|
score: matchesScore
|
||||||
}
|
}
|
||||||
|
|
||||||
matchingResults.push(matchingPost)
|
matchingResults.push(matchingPost)
|
||||||
|
|
@ -156,7 +155,7 @@ export function search(query) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return matchingResults
|
return matchingResults.sort((r1, r2) => r2.score - r1.score);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function init(config, vm) {
|
export function init(config, vm) {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue