【问题标题】:How to sort search results by relevance in javascript如何在javascript中按相关性对搜索结果进行排序
【发布时间】:2020-09-03 13:00:30
【问题描述】:

我正在构建一个自定义搜索,截至目前,如果我输入“The R”,我会首先获得 The Fellowship of the Ring 的结果列表,因为它的 .text 中包含短语“the ring”。我希望王者归来是第一。有没有一种方法可以让 .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"
  }
]

【问题讨论】:

  • 这个问题没有明确的答案。您可以采用不同的策略来评估相关性。
  • 无论优先考虑名称然后是文本的解决方案,我都可以。
  • 按匹配/不匹配对您来说是否足够,或者您需要更花哨的东西?
  • 我正在尝试按相关性对它们进行排序,因此,首先是名称,然后是文本。或者,我也尝试从字符串的开头进行搜索,我使用了 RegExp(^${searchText}, 'gi');但如果我只写“国王”,我将不会得到任何结果。
  • 你不应该只使用这样的正则表达式,因为正则表达式使用特殊字符。相反,比较string.toLowerCase().includes(searchText.toLowerCase())

标签: javascript arrays json sorting search


【解决方案1】:

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

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);

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

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

【讨论】:

  • 它可以工作,但它有一个问题,由于某种原因,某些结果有 4 分。因此,如果我写了字母“a”但某些结果在文本中有更多匹配项,即使它的名称以字母“c”开头,它也会在上面。
  • 如果你使用我发布的代码,这是不可能的。
  • 我刚刚在比赛中重命名了rankedIndex,因为脚本使用了它。我没有做任何其他修改。
猜你喜欢
  • 2012-01-28
  • 2011-11-26
  • 2014-05-24
  • 2010-11-04
  • 1970-01-01
  • 2018-12-24
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
相关资源
最近更新 更多