搜索
首页web前端js教程纯前端倒排全文搜索

原文链接:https://i18n.site/blog/tech/search

顺序

经过几周的开发,i18n.site(纯静态Markdown多语言翻译建站工具)现已支持纯前端全文搜索。

纯前端倒排全文搜索纯前端倒排全文搜索

本文将分享i18n.site纯前端全文搜索的技术实现。访问 i18n.site 体验搜索功能。

代码开源:搜索内核/交互界面

无服务器全文搜索解决方案概述

对于文档/个人博客等中小型纯静态网站,构建自建全文搜索后端过于繁重,无服务全文搜索是更常见的选择。

无服务器全文搜索解决方案分为两大类:

第一个涉及第三方搜索服务提供商,例如 algolia.com,它们提供用于全文搜索的前端组件。

此类服务需要根据搜索量付费,并且由于合规问题通常无法向中国大陆用户提供。

它们不能离线或在内联网上使用,并且有很大的局限性。本文不再详述。

第二类是纯前端全文检索。

目前常见的纯前端全文检索工具有lunrjs和ElasticLunr.js(基于lunrjs的二次开发)。

lunrjs 有两种构建索引的方法,但都有各自的问题。

  1. 预建索引文件

由于索引包含了文档中的所有单词,因此其尺寸较大。
每次添加或修改文档时,都必须加载新的索引文件。
这会增加用户等待时间并消耗大量带宽。

  1. 动态加载文档并构建索引

构建索引是一项计算密集型任务,每次访问时重建索引可能会导致明显的延迟,从而导致糟糕的用户体验。


除了lunrjs之外,还有其他全文搜索解决方案,例如:

fusejs,通过计算字符串之间的相似度进行搜索。

该方案性能较差,不适合全文检索(参考Fuse.js 查询时间长超过10秒,如何优化?)。

TinySearch使用布隆过滤器进行搜索,无法进行前缀搜索(例如输入goo搜索good或google),无法实现自动完成效果。

针对现有解决方案的缺陷,i18n.site开发了全新的纯前端全文搜索解决方案,具有以下特点:

  1. 支持多语言搜索,体积小巧;使用 gzip 打包后,搜索内核只有 6.9KB(相比之下,lunrjs 为 25KB)
  2. 基于IndexedDB构建倒排索引,内存占用低,性能快
  3. 添加/修改文档时,仅对添加或修改的文档重新索引,减少计算量
  4. 支持前缀搜索,用户输入时实时显示搜索结果
  5. 离线可用性

下面将介绍i18n.site技术实现的细节。

多语言分词

分词使用浏览器原生的Intl.Segmenter,所有主流浏览器都支持。

纯前端倒排全文搜索

分词的coffeescript代码如下:

SEG = new Intl.Segmenter 0, granularity: "word"

seg = (txt) =>
  r = []
  for {segment} from SEG.segment(txt)
    for i from segment.split('.')
      i = i.trim()
      if i and !'|`'.includes(i) and !/\p{P}/u.test(i)
        r.push i
  r

export default seg

export segqy = (q) =>
  seg q.toLocaleLowerCase()

地点:

  • /p{P}/ 是匹配标点符号的正则表达式,包括: ! " # $ % & ' ( ) * , - . / : ; ? @ [ ] ^ _ { | } ~. .
    • split('.' )是因为Firefox浏览器分词不分词。`.

    指数构建

    IndexedDB 中创建了 5 个对象存储表:

    • 单词:id - 单词
    • doc: id - 文档 URL - 文档版本号
    • docWord:文档 id - 单词 id 数组
    • prefix:前缀 - 单词 id 数组
    • rindex:单词 id - 文档 id - 行号数组

    通过传入文档 url 和版本号 ver 的数组,检查 doc 表中文档是否存在。如果不存在,则创建倒排索引。同时,未传入文档的倒排索引将被删除。

    此方法允许增量索引,减少计算负载。

    In the front-end interface, a progress bar for index loading can be displayed to avoid lag during the initial load. See "Animated Progress Bar, Based on a Single progress + Pure CSS Implementation" English / Chinese.

    IndexedDB High Concurrent Writing

    The project is developed based on the asynchronous encapsulation of IndexedDB, idb.

    IndexedDB reads and writes are asynchronous. When creating an index, documents are loaded concurrently to build the index.

    To avoid data loss due to concurrent writes, you can refer to the following coffeescript code, which adds a ing cache between reading and writing to intercept competitive writes.

    `coffee
    pusher = =>
    ing = new Map()
    (table, id, val)=>
    id_set = ing.get(id)
    if id_set
    id_set.add val
    return

    id_set = new Set([val])
    ing.set id, id_set
    pre = await table.get(id)
    li = pre?.li or []
    
    loop
      to_add = [...id_set]
      li.push(...to_add)
      await table.put({id,li})
      for i from to_add
        id_set.delete i
      if not id_set.size
        ing.delete id
        break
    return
    

    rindexPush = pusher()
    prefixPush = pusher()
    `

    Prefix Real-Time Search

    To display search results in real-time as the user types, for example, showing words like words and work that start with wor when wor is entered.

    纯前端倒排全文搜索

    The search kernel uses the prefix table for the last word after segmentation to find all words with that prefix and search sequentially.

    An anti-shake function, debounce (implemented as follows), is used in the front-end interaction to reduce the frequency of searches triggered by user input, thus minimizing computational load.

    js
    export default (wait, func) => {
    var timeout;
    return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(func.bind(this, ...args), wait);
    };
    }

    Precision and Recall

    The search first segments the keywords entered by the user.

    Assuming there are N words after segmentation, the results are first returned with all keywords, followed by results with N-1, N-2, ..., 1 keywords.

    The search results displayed first ensure query precision, while subsequent loaded results (click the "Load More" button) ensure recall.

    纯前端倒排全文搜索

    On-Demand Loading

    To improve response speed, the search uses the yield generator to implement on-demand loading, returning results after each limit query.

    Note that after each yield, a new IndexedDB query transaction must be opened for the next search.

    Prefix Real-Time Search

    To display search results in real-time as the user types, for example, showing words like words and work that start with wor when wor is entered.

    纯前端倒排全文搜索

    The search kernel uses the prefix table for the last word after segmentation to find all words with that prefix and search sequentially.

    An anti-shake function, debounce (implemented as follows), is used in the front-end interaction to reduce the frequency of searches triggered by user input, thus minimizing computational load.

    js
    export default (wait, func) => {
    var timeout;
    return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(func.bind(this, ...args), wait);
    };
    }

    Offline Availability

    The index table does not store the original text, only words, reducing storage space.

    Highlighting search results requires reloading the original text, and using service worker can avoid repeated network requests.

    Also, because service worker caches all articles, once a search is performed, the entire website, including search functionality, becomes offline available.

    Optimization for Displaying MarkDown Documents

    The pure front-end search solution provided by i18n.site is optimized for MarkDown documents.

    When displaying search results, the chapter name is shown, and clicking navigates to that chapter.

    纯前端倒排全文搜索

    Summary

    The pure front-end implementation of inverted full-text search, without the need for a server, is very suitable for small to medium-sized websites such as documents and personal blogs.

    i18n.site's open-source self-developed pure front-end search is compact, responsive, and addresses the various shortcomings of current pure front-end full-text search solutions, providing a better user experience.

以上是纯前端倒排全文搜索的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C和JavaScript:连接解释C和JavaScript:连接解释Apr 23, 2025 am 12:07 AM

C 和JavaScript通过WebAssembly实现互操作性。1)C 代码编译成WebAssembly模块,引入到JavaScript环境中,增强计算能力。2)在游戏开发中,C 处理物理引擎和图形渲染,JavaScript负责游戏逻辑和用户界面。

从网站到应用程序:JavaScript的不同应用从网站到应用程序:JavaScript的不同应用Apr 22, 2025 am 12:02 AM

JavaScript在网站、移动应用、桌面应用和服务器端编程中均有广泛应用。1)在网站开发中,JavaScript与HTML、CSS一起操作DOM,实现动态效果,并支持如jQuery、React等框架。2)通过ReactNative和Ionic,JavaScript用于开发跨平台移动应用。3)Electron框架使JavaScript能构建桌面应用。4)Node.js让JavaScript在服务器端运行,支持高并发请求。

Python vs. JavaScript:比较用例和应用程序Python vs. JavaScript:比较用例和应用程序Apr 21, 2025 am 12:01 AM

Python更适合数据科学和自动化,JavaScript更适合前端和全栈开发。1.Python在数据科学和机器学习中表现出色,使用NumPy、Pandas等库进行数据处理和建模。2.Python在自动化和脚本编写方面简洁高效。3.JavaScript在前端开发中不可或缺,用于构建动态网页和单页面应用。4.JavaScript通过Node.js在后端开发中发挥作用,支持全栈开发。

C/C在JavaScript口译员和编译器中的作用C/C在JavaScript口译员和编译器中的作用Apr 20, 2025 am 12:01 AM

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。 1)C 用于解析JavaScript源码并生成抽象语法树。 2)C 负责生成和执行字节码。 3)C 实现JIT编译器,在运行时优化和编译热点代码,显着提高JavaScript的执行效率。

JavaScript在行动中:现实世界中的示例和项目JavaScript在行动中:现实世界中的示例和项目Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

JavaScript和Web:核心功能和用例JavaScript和Web:核心功能和用例Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

了解JavaScript引擎:实施详细信息了解JavaScript引擎:实施详细信息Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:学习曲线和易用性Python vs. JavaScript:学习曲线和易用性Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。