js前端搜索组件lunr.js使用

lunr.js也是一个可以提供搜索的组件,只是不支持中文搜索和模糊搜索。也提供了匹配度分数。
<script src="../plugins/lunr-js/lunr.js"></script>
<script>
  //不支持中文检索和模糊检索
  //英文支持检索,不区分大小写,整个单词匹配
  const documents = [
    {
      name: "Lunr",
      text: "Like Solr, but much smaller, and not as bright.",
    },
    {
      name: "React",
      text: "A JavaScript library for building user interfaces.",
    },
    {
      name: "Lodash",
      text: "A modern JavaScript utility library delivering modularity, performance & extras.",
    },
  ];

  const index = lunr(function () {
    this.ref("name");
    this.field("text");

    documents.forEach(function (doc) {
      this.add(doc);
    }, this);
  });

  const arr = ["javascript", "performance", "small"];
  for (let str of arr) {
    console.log(str, index.search(str));
  }
  console.log("-----------------");

  //javascript [{ref:"React",score:0.504},{ref:""Lodash"",score:0.39}]
  //performance [{ref:""Lodash"",score:0.814}]
  //small []
</script>

 

posted @ 2024-12-06 09:11  carol2014  阅读(32)  评论(0编辑  收藏  举报