如何在javascript中按相关性对搜索结果进行排序

阿耳emi弥斯

我正在建立一个自定义搜索,到目前为止,如果我输入“ The R”,我首先会获得“指环王”的搜索结果列表,因为短语“ the ring”在其.text中。我希望《王者归来》成为第一位。有没有一种方法可以赋予.name字段更多相关性,或者根据名称.field和输入文本对匹配数组进行排序?

的HTML

<section class="container-fluid px-0 justify-content-center">
  <div class="row no-gutters">
    <div class="col d-flex justify-content-center search">
      <form class="form-inline position-relative">
        <input id="search" class="form-control form-control-search" type="text" placeholder="Search..." aria-label="Search">
      </form>
      <div id="match-list" class="d-none"></div>
    </div>
  </div>
</section>

JAVASCRIPT

const searchIndex = async searchText => {
 const res = await fetch('/data/index.json');
 const index = await res.json();

  matchList.classList.remove("d-none");
 // Get matches to current text input
 let matches = index.filter(index => {
  const regex = new RegExp(`${searchText}`, 'gi');
  return index.name.match(regex) || index.text.match(regex);
 });

 // Clear when input or matches are empty
 if (searchText.length === 0) {
   clearSearch();
 }

 outputHtml(matches);
};

function clearSearch(){
  matches = [];
  matchList.classList.add("d-none");
}

// Show results in HTML
const outputHtml = matches => {
 if (matches.length > 0) {
  const html = matches.map(function(match){
      return `<a href="${match.url}">
      <div class="media mb-2">
        <div class="component-icon-slot my-auto" style="background-image: url('/img/${match.url}/icon.png"></div>
          <div class="media-body pl-2">
            <h3 class="mt-0 mb-0">${match.name}</h3>
            <b>${match.type}</b><br/>
            <i>Found in <b>${match.product}</b></i><br/>
            ${match.text}
          </div>
        </div></a>`
    }
}).join('');
  matchList.innerHTML = html;
 }
};

index.JSON

 [
  {
    "name": "The Fellowship of the Rings",
    "type": "book",
    "text": "Bilbo reveals that he intends to leave the Shire for one last adventure, and he leaves his inheritance, including the Ring, to his nephew Frodo. Gandalf investigates...",
    "url": "books/the-fellowship-of-the-rings",
    "product": "Books"
  },
  {
    "name": "The Two Towers",
    "type": "book",
    "text": "Awakening from a dream of Gandalf fighting the Balrog in Moria, Frodo Baggins and Samwise Gamgee find themselves lost in the Emyn Muil near Mordor and discover they are being tracked by Gollum, a former bearer of the One Ring.",
    "url": "books/the-two-towers",
    "product": "Books"
  },
  {
    "name": "The Return of the King",
    "type": "book",
    "text": "Gandalf flies in with eagles to rescue the Hobbits, who awaken in Minas Tirith and are reunited with the surviving Fellowship.",
    "url": "books/the-return-of-the-king",
    "product": "Books"
  }
]
盗窃罗伯克

您可以映射数据以包括相关点:

const index = await res.json();
const searchTextLowercased = searchText.toLowerCase();

const rankedIndex = index.map(entry => {
    let points = 0;

    if (entry.name.toLowerCase().includes(searchTextLowercased)) {
        points += 2;
    }

    if (entry.text.toLowerCase().includes(searchTextLowercased)) {
        points += 1;
    }

    return {...entry, points};
}).sort((a, b) => b.points - a.points);

这样,您就可以在rankedIndexconst中对结果进行排名

请记住,您的代码可能需要进行一些重构,因为您需要在每次搜索时获取数据。我假设searchIndex()每次按键或类似操作都会呼叫

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

JavaScript 中的模糊搜索,结果按相关性排序

如何使用 PHP 和 MySQLI 按相关性对结果进行排序?

搜索CommentThreads时使用“相关性”对结果进行排序时,没有返回任何项目

如何将MySQL搜索结果与相关性排序?

Python:如何按子字符串相关性对字符串列表进行排序?

使用“匹配依据”进行全文搜索-将“按相关性”放到工作中

在 Algolia 中无需过滤即可按相关性对结果进行排序

根据mysql中的相关性对结果进行排名

如何在MySQL中按日期对相关结果进行分组和排序

SOLR按相关性排序

如何简化此LINQ查询,以字符串形式搜索关键字并按相关性对其进行排序?

如何在R中运行多个相关性测试并根据函数结果创建新表

MySQL全文搜索布尔模式按相关性而不是我要的顺序排序(短语匹配)

以编程方式搜索pypi软件包(最好按相关性排序)

MongoDB全文搜索和多个单词按相关性排序

弹性搜索中的邻近相关性

Solr中的相关性搜索

如何按组计算相关性

如何在 SQLAlchemy 中按降序对结果进行排序?

Sitecore内容按字段和相关性搜索

MySQL全文搜索按布尔模式顺序的相关性

SOLR搜索按相关性得分筛选

Neo4j - 按相关性排序

使用 ElasticSearch 进行相关性评分和排序

在 MySQLi 中按相关性排序 - 如果在某行中找到关键字,则首先按此排序

如何将相关性分析结果放入R中的CSV表格中

如何在JavaScript中对按顺序编号的文件进行排序?

如何在JavaScript中按日期对数组进行排序?

如何在Javascript中按属性对数组进行排序