순수 프런트엔드 역전체 텍스트 검색
元のリンク: https://i18n.site/blog/tech/search
順序
数週間の開発を経て、i18n.site (純粋な静的マークダウン多言語翻訳および Web サイト構築ツール) は、純粋なフロントエンド全文検索をサポートするようになりました。
この記事では、i18n.site の純粋なフロントエンド全文検索の技術的な実装について共有します。 i18n.site にアクセスして検索機能を体験してください。
コードはオープンソースです: 検索カーネル / インタラクティブ インターフェイス
サーバーレス全文検索ソリューションの概要
ドキュメントや個人のブログなど、中小規模の純粋に静的な Web サイトの場合、独自に構築した全文検索バックエンドを構築するのは重すぎるため、サービス不要の全文検索がより一般的な選択肢です。
サーバーレス全文検索ソリューションは、次の 2 つの主要カテゴリに分類されます。
1 つ目は、全文検索用のフロントエンド コンポーネントを提供する algolia.com などのサードパーティの検索サービス プロバイダーです。
このようなサービスは検索ボリュームに基づいて料金を支払う必要があり、コンプライアンスの問題により中国本土のユーザーは利用できないことがよくあります。
オフラインやイントラネットでは使用できず、重大な制限があります。この記事ではこれ以上詳しく説明しません。
2 番目のカテゴリは、純粋なフロントエンド全文検索です。
現在、一般的な純粋なフロントエンド全文検索ツールには、lunrjs および ElasticLunr.js (lunrjs に基づく二次開発) が含まれます。
lunrjs にはインデックスを構築するための 2 つの方法があり、どちらも独自の問題があります。
- 事前に構築されたインデックス ファイル
索引には文書のすべての単語が含まれているため、サイズが大きくなります。
ドキュメントが追加または変更されるたびに、新しいインデックス ファイルをロードする必要があります。
これにより、ユーザーの待ち時間が増加し、大量の帯域幅が消費されます。
- ドキュメントを読み込み、その場でインデックスを構築する
インデックスの構築は計算集約型のタスクであり、アクセスのたびにインデックスを再構築すると顕著な遅延が発生し、ユーザー エクスペリエンスの低下につながる可能性があります。
lunrjs に加えて、次のような他の全文検索ソリューションもあります。
fusejs、文字列間の類似性を計算して検索します。
このソリューションはパフォーマンスが低く、全文検索には適していません (Fuse.js の長いクエリに 10 秒以上かかる、最適化する方法を参照してください)。
検索にブルーム フィルターを使用する TinySearch は、接頭辞検索 (例: goo を入力して Good または Google を検索する) を実行できず、オートコンプリート効果も実現できません。
既存のソリューションには欠点があるため、i18n.site は次の機能を備えた新しい純粋なフロントエンド全文検索ソリューションを開発しました。
- コンパクトなサイズで多言語検索をサポートします。検索カーネルは、gzip でパッケージ化した場合、わずか 6.9 KB です (比較すると、lunrjs は 25 KB)
- メモリ使用量が少なく、パフォーマンスが高速な IndexedDB に基づいた転置インデックスを構築します
- ドキュメントが追加/変更されると、追加または変更されたドキュメントのみが再インデックス化されるため、計算量が削減されます
- 接頭辞検索をサポートし、ユーザーの入力に応じて検索結果をリアルタイムに表示できます
- オフラインでの利用可能
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: prefix - 単語 ID の配列
- rindex: 単語 ID - ドキュメント ID - 行番号の配列
ドキュメント URL とバージョン番号 ver の配列を渡すことにより、ドキュメント テーブルでドキュメントの存在がチェックされます。存在しない場合は、転置インデックスが作成されます。同時に、渡されなかったドキュメントの逆索引は削除されます。
この方法では、増分インデックス作成が可能になり、計算負荷が軽減されます。
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
returnid_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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

각각의 엔진의 구현 원리 및 최적화 전략이 다르기 때문에 JavaScript 엔진은 JavaScript 코드를 구문 분석하고 실행할 때 다른 영향을 미칩니다. 1. 어휘 분석 : 소스 코드를 어휘 단위로 변환합니다. 2. 문법 분석 : 추상 구문 트리를 생성합니다. 3. 최적화 및 컴파일 : JIT 컴파일러를 통해 기계 코드를 생성합니다. 4. 실행 : 기계 코드를 실행하십시오. V8 엔진은 즉각적인 컴파일 및 숨겨진 클래스를 통해 최적화하여 Spidermonkey는 유형 추론 시스템을 사용하여 동일한 코드에서 성능이 다른 성능을 제공합니다.

Python은 부드러운 학습 곡선과 간결한 구문으로 초보자에게 더 적합합니다. JavaScript는 가파른 학습 곡선과 유연한 구문으로 프론트 엔드 개발에 적합합니다. 1. Python Syntax는 직관적이며 데이터 과학 및 백엔드 개발에 적합합니다. 2. JavaScript는 유연하며 프론트 엔드 및 서버 측 프로그래밍에서 널리 사용됩니다.

C/C에서 JavaScript로 전환하려면 동적 타이핑, 쓰레기 수집 및 비동기 프로그래밍으로 적응해야합니다. 1) C/C는 수동 메모리 관리가 필요한 정적으로 입력 한 언어이며 JavaScript는 동적으로 입력하고 쓰레기 수집이 자동으로 처리됩니다. 2) C/C를 기계 코드로 컴파일 해야하는 반면 JavaScript는 해석 된 언어입니다. 3) JavaScript는 폐쇄, 프로토 타입 체인 및 약속과 같은 개념을 소개하여 유연성과 비동기 프로그래밍 기능을 향상시킵니다.

웹 개발에서 JavaScript의 주요 용도에는 클라이언트 상호 작용, 양식 검증 및 비동기 통신이 포함됩니다. 1) DOM 운영을 통한 동적 컨텐츠 업데이트 및 사용자 상호 작용; 2) 사용자가 사용자 경험을 향상시키기 위해 데이터를 제출하기 전에 클라이언트 확인이 수행됩니다. 3) 서버와의 진실한 통신은 Ajax 기술을 통해 달성됩니다.

실제 세계에서 JavaScript의 응용 프로그램에는 프론트 엔드 및 백엔드 개발이 포함됩니다. 1) DOM 운영 및 이벤트 처리와 관련된 TODO 목록 응용 프로그램을 구축하여 프론트 엔드 애플리케이션을 표시합니다. 2) Node.js를 통해 RESTFULAPI를 구축하고 Express를 통해 백엔드 응용 프로그램을 시연하십시오.

보다 효율적인 코드를 작성하고 성능 병목 현상 및 최적화 전략을 이해하는 데 도움이되기 때문에 JavaScript 엔진이 내부적으로 작동하는 방식을 이해하는 것은 개발자에게 중요합니다. 1) 엔진의 워크 플로에는 구문 분석, 컴파일 및 실행; 2) 실행 프로세스 중에 엔진은 인라인 캐시 및 숨겨진 클래스와 같은 동적 최적화를 수행합니다. 3) 모범 사례에는 글로벌 변수를 피하고 루프 최적화, Const 및 Lets 사용 및 과도한 폐쇄 사용을 피하는 것이 포함됩니다.

Python과 JavaScript는 커뮤니티, 라이브러리 및 리소스 측면에서 고유 한 장점과 단점이 있습니다. 1) Python 커뮤니티는 친절하고 초보자에게 적합하지만 프론트 엔드 개발 리소스는 JavaScript만큼 풍부하지 않습니다. 2) Python은 데이터 과학 및 기계 학습 라이브러리에서 강력하며 JavaScript는 프론트 엔드 개발 라이브러리 및 프레임 워크에서 더 좋습니다. 3) 둘 다 풍부한 학습 리소스를 가지고 있지만 Python은 공식 문서로 시작하는 데 적합하지만 JavaScript는 MDNWebDocs에서 더 좋습니다. 선택은 프로젝트 요구와 개인적인 이익을 기반으로해야합니다.

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.
