├── .github └── workflows │ ├── deploy-demo.yml │ ├── publish.yml │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── setup.py ├── sqlite_fts4 └── __init__.py └── tests ├── __init__.py ├── conftest.py └── test_sqlite_fts4.py /.github/workflows/deploy-demo.yml: -------------------------------------------------------------------------------- 1 | name: Deploy demo 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | deploy: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v3 11 | - name: Set up Python 12 | uses: actions/setup-python@v3 13 | with: 14 | python-version: '3.10' 15 | - uses: actions/cache@v2 16 | name: Configure pip caching 17 | with: 18 | path: ~/.cache/pip 19 | key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} 20 | restore-keys: | 21 | ${{ runner.os }}-publish-pip- 22 | - name: Publish demo 23 | env: 24 | GITHUB_SHA: ${{ env.GITHUB_SHA }} 25 | NOW_TOKEN: ${{ secrets.NOW_TOKEN }} 26 | run: |- 27 | curl --fail --silent -o 24ways-fts4.db https://static.simonwillison.net/static/2022/24ways-fts4.db 28 | pip install datasette datasette-publish-vercel 29 | datasette publish vercel 24ways-fts4.db \ 30 | --token $NOW_TOKEN \ 31 | --project datasette-sqlite-fts4 \ 32 | --install https://github.com/simonw/sqlite-fts4/archive/$GITHUB_SHA.zip \ 33 | --install datasette-sqlite-fts4 \ 34 | --install datasette-json-html \ 35 | --source_url=https://github.com/simonw/sqlite-fts4 36 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python Package 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | python-version: [3.6, 3.7, 3.8, 3.9] 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v2 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - uses: actions/cache@v2 20 | name: Configure pip caching 21 | with: 22 | path: ~/.cache/pip 23 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} 24 | restore-keys: | 25 | ${{ runner.os }}-pip- 26 | - name: Install dependencies 27 | run: | 28 | pip install -e '.[test]' 29 | - name: Run tests 30 | run: | 31 | pytest 32 | deploy: 33 | runs-on: ubuntu-latest 34 | needs: [test] 35 | steps: 36 | - uses: actions/checkout@v2 37 | - name: Set up Python 38 | uses: actions/setup-python@v2 39 | with: 40 | python-version: '3.9' 41 | - uses: actions/cache@v2 42 | name: Configure pip caching 43 | with: 44 | path: ~/.cache/pip 45 | key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} 46 | restore-keys: | 47 | ${{ runner.os }}-publish-pip- 48 | - name: Install dependencies 49 | run: | 50 | pip install setuptools wheel twine 51 | - name: Publish 52 | env: 53 | TWINE_USERNAME: __token__ 54 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 55 | run: | 56 | python setup.py sdist bdist_wheel 57 | twine upload dist/* 58 | - name: Publish demo 59 | env: 60 | GITHUB_SHA: ${{ env.GITHUB_SHA }} 61 | NOW_TOKEN: ${{ secrets.NOW_TOKEN }} 62 | run: |- 63 | curl --fail --silent -o 24ways-fts4.db https://static.simonwillison.net/static/2022/24ways-fts4.db 64 | pip install datasette datasette-publish-vercel 65 | datasette publish vercel 24ways-fts4.db \ 66 | --token $NOW_TOKEN \ 67 | --project datasette-sqlite-fts4 \ 68 | --install https://github.com/simonw/sqlite-fts4/archive/$GITHUB_SHA.zip \ 69 | --install datasette-sqlite-fts4 \ 70 | --install datasette-json-html \ 71 | --source_url=https://github.com/simonw/sqlite-fts4 72 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: [3.6, 3.7, 3.8, 3.9] 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Set up Python ${{ matrix.python-version }} 14 | uses: actions/setup-python@v2 15 | with: 16 | python-version: ${{ matrix.python-version }} 17 | - uses: actions/cache@v2 18 | name: Configure pip caching 19 | with: 20 | path: ~/.cache/pip 21 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} 22 | restore-keys: | 23 | ${{ runner.os }}-pip- 24 | - name: Install dependencies 25 | run: | 26 | pip install -e '.[test]' 27 | - name: Run tests 28 | run: | 29 | pytest 30 | 31 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | __pycache__ 3 | venv 4 | .eggs 5 | *.egg-info 6 | .vscode 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sqlite-fts4 2 | 3 | [![PyPI](https://img.shields.io/pypi/v/sqlite-fts4.svg)](https://pypi.org/project/sqlite-fts4/) 4 | [![Changelog](https://img.shields.io/github/v/release/simonw/sqlite-fts4?include_prereleases&label=changelog)](https://github.com/simonw/sqlite-fts4/releases) 5 | [![Tests](https://github.com/simonw/sqlite-fts4/workflows/Test/badge.svg)](https://github.com/simonw/sqlite-fts4/actions?query=workflow%3ATest) 6 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/sqlite-fts4/blob/main/LICENSE) 7 | 8 | Custom SQLite functions written in Python for ranking documents indexed using the FTS4 extension. 9 | 10 | Read [Exploring search relevance algorithms with SQLite](https://simonwillison.net/2019/Jan/7/exploring-search-relevance-algorithms-sqlite/) for further details on this project. 11 | 12 | ## Demo 13 | 14 | You can try out these SQL functions [using this interactive demo](https://datasette-sqlite-fts4.datasette.io/24ways-fts4?sql=select%0D%0A++++json_object%28%0D%0A++++++++"label"%2C+articles.title%2C+"href"%2C+articles.url%0D%0A++++%29+as+article%2C%0D%0A++++articles.author%2C%0D%0A++++rank_score%28matchinfo%28articles_fts%2C+"pcx"%29%29+as+score%2C%0D%0A++++rank_bm25%28matchinfo%28articles_fts%2C+"pcnalx"%29%29+as+bm25%2C%0D%0A++++json_object%28%0D%0A++++++++"pre"%2C+annotate_matchinfo%28matchinfo%28articles_fts%2C+"pcxnalyb"%29%2C+"pcxnalyb"%29%0D%0A++++%29+as+annotated_matchinfo%2C%0D%0A++++matchinfo%28articles_fts%2C+"pcxnalyb"%29+as+matchinfo%2C%0D%0A++++decode_matchinfo%28matchinfo%28articles_fts%2C+"pcxnalyb"%29%29+as+decoded_matchinfo%0D%0Afrom%0D%0A++++articles_fts+join+articles+on+articles.rowid+%3D+articles_fts.rowid%0D%0Awhere%0D%0A++++articles_fts+match+%3Asearch%0D%0Aorder+by+bm25&search=jquery+maps). 15 | 16 | ## Installation 17 | 18 | pip install sqlite-fts4 19 | 20 | ## Usage 21 | 22 | This module implements several custom SQLite3 functions. You can register them against an existing SQLite connection like so: 23 | 24 | ```python 25 | import sqlite3 26 | from sqlite_fts4 import register_functions 27 | 28 | conn = sqlite3.connect(":memory:") 29 | register_functions(conn) 30 | ``` 31 | 32 | If you only want a subset of the functions registered you can do so like this: 33 | 34 | ```python 35 | from sqlite_fts4 import rank_score 36 | 37 | conn = sqlite3.connect(":memory:") 38 | conn.create_function("rank_score", 1, rank_score) 39 | ``` 40 | 41 | if you want to use these functions with [Datasette](https://github.com/simonw/datasette) you can enable them by installing the [datasette-sqlite-fts4](https://github.com/simonw/datasette-sqlite-fts4) plugin: 42 | 43 | pip install datasette-sqlite-fts4 44 | 45 | ## rank_score() 46 | 47 | This is an extremely simple ranking function, based on [an example](https://www.sqlite.org/fts3.html#appendix_a) in the SQLite documentation. It generates a score for each document using the sum of the score for each column. The score for each column is calculated as the number of search matches in that column divided by the number of search matches for every column in the index - a classic [TF-IDF](https://en.wikipedia.org/wiki/Tf%E2%80%93idf) calculation. 48 | 49 | You can use it in a query like this: 50 | 51 | ```sql 52 | select *, rank_score(matchinfo(docs, "pcx")) as score 53 | from docs where docs match "dog" 54 | order by score desc 55 | ``` 56 | 57 | You *must* use the `"pcx"` matchinfo format string here, or you will get incorrect results. 58 | 59 | ## rank_bm25() 60 | 61 | An implementation of the [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) scoring algorithm. Use it in a query like this: 62 | 63 | ```sql 64 | select *, rank_bm25(matchinfo(docs, "pcnalx")) as score 65 | from docs where docs match "dog" 66 | order by score desc 67 | ``` 68 | 69 | You *must* use the `"pcnalx"` matchinfo format string here, or you will get incorrect results. If you see any `math domain` errors in your logs it may be because you did not use exactly the right format string here. 70 | 71 | ## decode_matchinfo() 72 | 73 | SQLite's [built-in matchinfo() function](https://www.sqlite.org/fts3.html#matchinfo) returns results as a binary string. This binary represents a list of 32 bit unsigned integers, but reading the binary results is not particularly human-friendly. 74 | 75 | The `decode_matchinfo()` function decodes the binary string and converts it into a JSON list of integers. 76 | 77 | Usage: 78 | 79 | ```sql 80 | select *, decode_matchinfo(matchinfo(docs, "pcx")) 81 | from docs where docs match "dog" 82 | ``` 83 | 84 | Example output: 85 | 86 | hello dog, [1, 1, 1, 1, 1] 87 | 88 | ## annotate_matchinfo() 89 | 90 | This function decodes the matchinfo document into a verbose JSON structure that describes exactly what each of the returned integers actually means. 91 | 92 | Full documentation for the different format string options can be found here: https://www.sqlite.org/fts3.html#matchinfo 93 | 94 | You need to call this function with the same format string as was passed to `matchinfo()` - for example: 95 | 96 | ```sql 97 | select annotate_matchinfo(matchinfo(docs, "pcxnal"), "pcxnal") 98 | from docs where docs match "dog" 99 | ``` 100 | 101 | The returned JSON will include a key for each letter in the format string. For example: 102 | 103 | ```json 104 | { 105 | "p": { 106 | "value": 1, 107 | "title": "Number of matchable phrases in the query" 108 | }, 109 | "c": { 110 | "value": 1, 111 | "title": "Number of user defined columns in the FTS table" 112 | }, 113 | "x": { 114 | "value": [ 115 | { 116 | "column_index": 0, 117 | "phrase_index": 0, 118 | "hits_this_column_this_row": 1, 119 | "hits_this_column_all_rows": 2, 120 | "docs_with_hits": 2 121 | } 122 | ], 123 | "title": "Details for each phrase/column combination" 124 | }, 125 | "n": { 126 | "value": 3, 127 | "title": "Number of rows in the FTS4 table" 128 | }, 129 | "a": { 130 | "title":"Average number of tokens in the text values stored in each column", 131 | "value": [ 132 | { 133 | "column_index": 0, 134 | "average_num_tokens": 2 135 | } 136 | ] 137 | }, 138 | "l": { 139 | "title": "Length of value stored in current row of the FTS4 table in tokens for each column", 140 | "value": [ 141 | { 142 | "column_index": 0, 143 | "length_of_value": 2 144 | } 145 | ] 146 | } 147 | } 148 | ``` 149 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import os 3 | 4 | VERSION = "1.0.3" 5 | 6 | 7 | def get_long_description(): 8 | with open( 9 | os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), 10 | encoding="utf8", 11 | ) as fp: 12 | return fp.read() 13 | 14 | 15 | setup( 16 | name="sqlite-fts4", 17 | description="Python functions for working with SQLite FTS4 search", 18 | long_description=get_long_description(), 19 | long_description_content_type="text/markdown", 20 | author="Simon Willison", 21 | url="https://github.com/simonw/sqlite-fts4", 22 | project_urls={ 23 | "Issues": "https://github.com/simonw/sqlite-fts4/issues", 24 | "CI": "https://github.com/simonw/sqlite-fts4/actions", 25 | "Changelog": "https://github.com/simonw/sqlite-fts4/releases", 26 | }, 27 | license="Apache License, Version 2.0", 28 | version=VERSION, 29 | packages=["sqlite_fts4"], 30 | extras_require={"test": ["pytest"]}, 31 | tests_require=["sqlite-fts4[test]"], 32 | ) 33 | -------------------------------------------------------------------------------- /sqlite_fts4/__init__.py: -------------------------------------------------------------------------------- 1 | import struct 2 | import math 3 | import json 4 | import traceback 5 | from functools import wraps 6 | 7 | 8 | def register_functions(conn): 9 | "Registers these custom functions against an SQLite connection" 10 | conn.create_function("rank_score", 1, rank_score) 11 | conn.create_function("decode_matchinfo", 1, decode_matchinfo_str) 12 | conn.create_function("annotate_matchinfo", 2, annotate_matchinfo) 13 | conn.create_function("rank_bm25", 1, rank_bm25) 14 | 15 | 16 | def wrap_sqlite_function_in_error_logger(fn): 17 | # Because SQLite swallows exceptions inside custom functions 18 | @wraps(fn) 19 | def wrapper(*args, **kwargs): 20 | try: 21 | return fn(*args, **kwargs) 22 | except Exception: 23 | traceback.print_exc() 24 | raise 25 | 26 | return wrapper 27 | 28 | 29 | def decode_matchinfo_str(buf): 30 | return str(list(decode_matchinfo(buf))) 31 | 32 | 33 | def decode_matchinfo(buf): 34 | # buf is a bytestring of unsigned integers, each 4 bytes long 35 | return struct.unpack("@" + ("I" * (len(buf) // 4)), buf) 36 | 37 | 38 | def _error(m): 39 | return {"error": m} 40 | 41 | 42 | @wrap_sqlite_function_in_error_logger 43 | def annotate_matchinfo(buf, format_string): 44 | return json.dumps(_annotate_matchinfo(buf, format_string), indent=2) 45 | 46 | 47 | def _annotate_matchinfo(buf, format_string): 48 | # See https://www.sqlite.org/fts3.html#matchinfo for detailed specification 49 | matchinfo = list(decode_matchinfo(buf)) 50 | if not matchinfo: 51 | return {} 52 | matchinfo_index = 0 53 | p_num_phrases = None 54 | c_num_columns = None 55 | 56 | def _next(): 57 | nonlocal matchinfo_index 58 | value = matchinfo[matchinfo_index] 59 | matchinfo_index += 1 60 | return value, matchinfo_index - 1 61 | 62 | results = {} 63 | for ch in format_string: 64 | if ch == "p": 65 | p_num_phrases, idx = _next() 66 | results["p"] = { 67 | "value": p_num_phrases, 68 | "title": "Number of matchable phrases in the query", 69 | "idx": idx, 70 | } 71 | elif ch == "c": 72 | c_num_columns, idx = _next() 73 | results["c"] = { 74 | "value": c_num_columns, 75 | "title": "Number of user defined columns in the FTS table", 76 | "idx": idx, 77 | } 78 | elif ch == "x": 79 | # Depends on p and c 80 | if None in (p_num_phrases, c_num_columns): 81 | return _error("'x' must be preceded by 'p' and 'c'") 82 | info = [] 83 | results["x"] = { 84 | "value": info, 85 | "title": "Details for each phrase/column combination", 86 | } 87 | # 3 * c_num_columns * p_num_phrases 88 | for phrase_index in range(p_num_phrases): 89 | for column_index in range(c_num_columns): 90 | hits_this_column_this_row, idx1 = _next() 91 | hits_this_column_all_rows, idx2 = _next() 92 | docs_with_hits, idx3 = _next() 93 | info.append( 94 | { 95 | "phrase_index": phrase_index, 96 | "column_index": column_index, 97 | "hits_this_column_this_row": hits_this_column_this_row, 98 | "hits_this_column_all_rows": hits_this_column_all_rows, 99 | "docs_with_hits": docs_with_hits, 100 | "idxs": [idx1, idx2, idx3], 101 | } 102 | ) 103 | elif ch == "y": 104 | if None in (p_num_phrases, c_num_columns): 105 | return _error("'y' must be preceded by 'p' and 'c'") 106 | info = [] 107 | results["y"] = { 108 | "value": info, 109 | "title": "Usable phrase matches for each phrase/column combination", 110 | } 111 | for phrase_index in range(p_num_phrases): 112 | for column_index in range(c_num_columns): 113 | hits_for_phrase_in_col, idx = _next() 114 | info.append( 115 | { 116 | "phrase_index": phrase_index, 117 | "column_index": column_index, 118 | "hits_for_phrase_in_col": hits_for_phrase_in_col, 119 | "idx": idx, 120 | } 121 | ) 122 | elif ch == "b": 123 | if None in (p_num_phrases, c_num_columns): 124 | return _error("'b' must be preceded by 'p' and 'c'") 125 | values = [] 126 | # We get back one integer for each 32 columns for each phrase 127 | num_32_column_chunks = (c_num_columns + 31) // 32 128 | decoded = {} 129 | for phrase_index in range(p_num_phrases): 130 | current_phrase_chunks = [] 131 | for _ in range(num_32_column_chunks): 132 | v = _next()[0] 133 | values.append(v) 134 | current_phrase_chunks.append(v) 135 | decoded["phrase_{}".format(phrase_index)] = "".join( 136 | [ 137 | "{:032b}".format(unsigned_integer)[::-1] 138 | for unsigned_integer in current_phrase_chunks 139 | ] 140 | ) 141 | results["b"] = { 142 | "title": "Bitfield showing which phrases occur in which columns", 143 | "value": values, 144 | # Each integer is a 32bit unsigned integer, least significant 145 | # bit is column 0, then column 1, then so on 146 | "decoded": decoded, 147 | } 148 | elif ch == "n": 149 | value, idx = _next() 150 | results["n"] = { 151 | "value": value, 152 | "title": "Number of rows in the FTS4 table", 153 | "idx": idx, 154 | } 155 | elif ch == "a": 156 | if c_num_columns is None: 157 | return _error("'a' must be preceded by 'c'") 158 | values = [] 159 | for i in range(c_num_columns): 160 | value, idx = _next() 161 | values.append( 162 | {"column_index": i, "average_num_tokens": value, "idx": idx} 163 | ) 164 | results["a"] = { 165 | "title": "Average number of tokens in each column across the whole table", 166 | "value": values, 167 | } 168 | elif ch == "l": 169 | if c_num_columns is None: 170 | return _error("'l' must be preceded by 'c'") 171 | values = [] 172 | for i in range(c_num_columns): 173 | value, idx = _next() 174 | values.append({"column_index": i, "num_tokens": value, "idx": idx}) 175 | results["l"] = { 176 | "title": "Number of tokens in each column of the current row of the FTS4 table", 177 | "value": values, 178 | } 179 | elif ch == "s": 180 | if c_num_columns is None: 181 | return _error("'s' must be preceded by 'c'") 182 | values = [] 183 | for i in range(c_num_columns): 184 | value, idx = _next() 185 | values.append( 186 | { 187 | "column_index": i, 188 | "length_phrase_subsequence_match": value, 189 | "idx": idx, 190 | } 191 | ) 192 | results["s"] = { 193 | "title": "Length of longest subsequence of phrase matching each column", 194 | "value": values, 195 | } 196 | return results 197 | 198 | 199 | @wrap_sqlite_function_in_error_logger 200 | def rank_score(raw_matchinfo): 201 | # Score using matchinfo called w/default args 'pcx' - based on example rank 202 | # function http://sqlite.org/fts3.html#appendix_a 203 | # The overall relevancy returned is the sum of the relevancies of each 204 | # column value in the FTS table. The relevancy of a column value is the 205 | # sum of the following for each reportable phrase in the FTS query: 206 | # ( / ) 207 | if not raw_matchinfo: 208 | return None 209 | matchinfo = _annotate_matchinfo(raw_matchinfo, "pcx") 210 | score = 0.0 211 | x_phrase_column_details = matchinfo["x"]["value"] 212 | for details in x_phrase_column_details: 213 | hits_this_column_this_row = details["hits_this_column_this_row"] 214 | hits_this_column_all_rows = details["hits_this_column_all_rows"] 215 | if hits_this_column_this_row > 0: 216 | score += float(hits_this_column_this_row) / hits_this_column_all_rows 217 | return -score 218 | 219 | 220 | @wrap_sqlite_function_in_error_logger 221 | def rank_bm25(raw_match_info): 222 | "Must be called with output of matchinfo 'pcnalx'" 223 | if not raw_match_info: 224 | return None 225 | match_info = _annotate_matchinfo(raw_match_info, "pcnalx") 226 | # How much should multiple matches in the same document increase the score? 227 | k = 1.2 228 | # How much should document length affect the score? (shorter docs = higher score) 229 | b = 0.75 230 | score = 0.0 231 | 232 | phrase_count = match_info["p"]["value"] 233 | column_count = match_info["c"]["value"] 234 | total_row_count = match_info["n"]["value"] 235 | 236 | for phrase_index in range(phrase_count): 237 | for column_index in range(column_count): 238 | average_num_tokens = match_info["a"]["value"][column_index][ 239 | "average_num_tokens" 240 | ] 241 | num_tokens = match_info["l"]["value"][column_index]["num_tokens"] 242 | if average_num_tokens == 0: 243 | d = 0 244 | else: 245 | d = 1 - b + (b * (float(num_tokens) / float(average_num_tokens))) 246 | 247 | phrase_column_x = [ 248 | v 249 | for v in match_info["x"]["value"] 250 | if v["column_index"] == column_index 251 | and v["phrase_index"] == phrase_index 252 | ][0] 253 | term_frequency = float(phrase_column_x["hits_this_column_this_row"]) 254 | docs_with_hits = float(phrase_column_x["docs_with_hits"]) 255 | 256 | # idf = inverse document frequency: is this term rare or common 257 | # across our entire corpus? 258 | idf = max( 259 | math.log( 260 | (total_row_count - docs_with_hits + 0.5) / (docs_with_hits + 0.5) 261 | ), 262 | 0, 263 | ) 264 | denom = term_frequency + (k * d) 265 | if denom == 0: 266 | rhs = 0 267 | else: 268 | rhs = (term_frequency * (k + 1)) / denom 269 | 270 | score += idf * rhs 271 | 272 | return -score 273 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonw/sqlite-fts4/f86b44933b3d0907f58c7db01411e7148b9f59dc/tests/__init__.py -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | 3 | 4 | def pytest_report_header(config): 5 | return "SQLite version: {}".format( 6 | sqlite3.connect(":memory:").execute("select sqlite_version()").fetchone()[0] 7 | ) 8 | -------------------------------------------------------------------------------- /tests/test_sqlite_fts4.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from sqlite_fts4 import register_functions, decode_matchinfo 3 | import pytest 4 | import json 5 | import sys 6 | 7 | 8 | sqlite_version = tuple( 9 | map( 10 | int, 11 | sqlite3.connect(":memory:") 12 | .execute("select sqlite_version()") 13 | .fetchone()[0] 14 | .split("."), 15 | ) 16 | ) 17 | 18 | 19 | @pytest.fixture 20 | def conn(): 21 | conn = sqlite3.connect(":memory:") 22 | register_functions(conn) 23 | conn.executescript( 24 | """ 25 | CREATE VIRTUAL TABLE search USING fts4(c0, c1); 26 | INSERT INTO search (c0, c1) VALUES ("this is about a dog", "more about that dog dog"); 27 | INSERT INTO search (c0, c1) VALUES ("this is about a cat", "stuff on that cat cat"); 28 | INSERT INTO search (c0, c1) VALUES ("something about a ferret", "yeah a ferret ferret"); 29 | INSERT INTO search (c0, c1) VALUES ("both of them", "both dog dog and cat here"); 30 | INSERT INTO search (c0, c1) VALUES ("not mammals", "maybe talk about fish"); 31 | """ 32 | ) 33 | return conn 34 | 35 | 36 | def test_fixture_sets_up_database(conn): 37 | assert 5 == conn.execute("select count(*) from search").fetchone()[0] 38 | 39 | 40 | @pytest.mark.parametrize( 41 | "search,expected", 42 | [ 43 | ("dog", [1, 2, 1, 1, 1, 2, 4, 2, 5, 4, 5, 5, 5]), 44 | ("cat", [1, 2, 1, 1, 1, 2, 3, 2, 5, 4, 5, 5, 5]), 45 | ], 46 | ) 47 | def test_decode_matchinfo(conn, search, expected): 48 | r = conn.execute( 49 | """ 50 | select decode_matchinfo(matchinfo(search, 'pcxnal')) 51 | from search where search match ? 52 | """, 53 | [search], 54 | ).fetchone()[0] 55 | assert expected == json.loads(r) 56 | 57 | 58 | @pytest.mark.parametrize( 59 | "buf,expected", 60 | [ 61 | ( 62 | b"\x01\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" 63 | if sys.byteorder == "little" 64 | else b"\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02", 65 | (1, 2, 2, 2), 66 | ) 67 | ], 68 | ) 69 | def test_underlying_decode_matchinfo(buf, expected): 70 | assert expected == decode_matchinfo(buf) 71 | 72 | 73 | def test_rank_bm25(conn): 74 | results = conn.execute( 75 | """ 76 | select c0, c1, rank_bm25(matchinfo(search, 'pcnalx')) as bm25 77 | from search where search match ? 78 | """, 79 | ["dog"], 80 | ).fetchall() 81 | assert ("this is about a dog", "more about that dog dog") == results[0][:2] 82 | assert pytest.approx(-1.459328) == results[0][2] 83 | assert ("both of them", "both dog dog and cat here") == results[1][:2] 84 | assert pytest.approx(-0.438011) == results[1][2] 85 | 86 | 87 | def test_rank_bm25_no_match(conn): 88 | results = conn.execute( 89 | """ 90 | select c0, c1, rank_bm25(matchinfo(search, 'pcnalx')) as bm25 91 | from search limit 1 92 | """ 93 | ).fetchall() 94 | assert None == results[0][2] 95 | 96 | 97 | def test_annotate_matchinfo(conn): 98 | r = conn.execute( 99 | """ 100 | select annotate_matchinfo(matchinfo(search, 'pcxnals'), 'pcxnals') 101 | from search where search match ? 102 | """, 103 | ["dog"], 104 | ).fetchone()[0] 105 | expected = { 106 | "p": { 107 | "value": 1, 108 | "title": "Number of matchable phrases in the query", 109 | "idx": 0, 110 | }, 111 | "c": { 112 | "value": 2, 113 | "title": "Number of user defined columns in the FTS table", 114 | "idx": 1, 115 | }, 116 | "x": { 117 | "value": [ 118 | { 119 | "phrase_index": 0, 120 | "column_index": 0, 121 | "hits_this_column_this_row": 1, 122 | "hits_this_column_all_rows": 1, 123 | "docs_with_hits": 1, 124 | "idxs": [2, 3, 4], 125 | }, 126 | { 127 | "phrase_index": 0, 128 | "column_index": 1, 129 | "hits_this_column_this_row": 2, 130 | "hits_this_column_all_rows": 4, 131 | "docs_with_hits": 2, 132 | "idxs": [5, 6, 7], 133 | }, 134 | ], 135 | "title": "Details for each phrase/column combination", 136 | }, 137 | "n": {"value": 5, "title": "Number of rows in the FTS4 table", "idx": 8}, 138 | "a": { 139 | "title": "Average number of tokens in each column across the whole table", 140 | "value": [ 141 | {"column_index": 0, "average_num_tokens": 4, "idx": 9}, 142 | {"column_index": 1, "average_num_tokens": 5, "idx": 10}, 143 | ], 144 | }, 145 | "l": { 146 | "title": "Number of tokens in each column of the current row of the FTS4 table", 147 | "value": [ 148 | {"column_index": 0, "num_tokens": 5, "idx": 11}, 149 | {"column_index": 1, "num_tokens": 5, "idx": 12}, 150 | ], 151 | }, 152 | "s": { 153 | "title": "Length of longest subsequence of phrase matching each column", 154 | "value": [ 155 | {"column_index": 0, "length_phrase_subsequence_match": 1, "idx": 13}, 156 | {"column_index": 1, "length_phrase_subsequence_match": 1, "idx": 14}, 157 | ], 158 | }, 159 | } 160 | assert expected == json.loads(r) 161 | 162 | 163 | def test_annotate_matchinfo_empty(conn): 164 | r = conn.execute( 165 | """ 166 | select annotate_matchinfo(matchinfo(search, 'pcxnals'), 'pcxnals') 167 | from search limit 1 168 | """ 169 | ).fetchone()[0] 170 | assert {} == json.loads(r) 171 | 172 | 173 | @pytest.mark.skipif( 174 | sqlite_version < (3, 8, 11), reason="matchinfo 'b' was added in SQLite 3.8.11" 175 | ) 176 | def test_annotate_matchinfo_b(conn): 177 | r = conn.execute( 178 | """ 179 | select annotate_matchinfo(matchinfo(search, 'pcb'), 'pcb') 180 | from search where search match ? 181 | """, 182 | ["something ferret"], 183 | ).fetchone()[0] 184 | expected = { 185 | "title": "Bitfield showing which phrases occur in which columns", 186 | "value": [1, 3], 187 | "decoded": { 188 | "phrase_0": "10000000000000000000000000000000", 189 | "phrase_1": "11000000000000000000000000000000", 190 | }, 191 | } 192 | assert expected == json.loads(r)["b"] 193 | 194 | 195 | @pytest.mark.skipif( 196 | sqlite_version < (3, 8, 10), reason="matchinfo 'y' was added in SQLite 3.8.10" 197 | ) 198 | def test_annotate_matchinfo_y(conn): 199 | r = conn.execute( 200 | """ 201 | select annotate_matchinfo(matchinfo(search, 'pcy'), 'pcy') 202 | from search where search match ? 203 | """, 204 | ["something ferret"], 205 | ).fetchone()[0] 206 | expected = { 207 | "value": [ 208 | { 209 | "phrase_index": 0, 210 | "column_index": 0, 211 | "hits_for_phrase_in_col": 1, 212 | "idx": 2, 213 | }, 214 | { 215 | "phrase_index": 0, 216 | "column_index": 1, 217 | "hits_for_phrase_in_col": 0, 218 | "idx": 3, 219 | }, 220 | { 221 | "phrase_index": 1, 222 | "column_index": 0, 223 | "hits_for_phrase_in_col": 1, 224 | "idx": 4, 225 | }, 226 | { 227 | "phrase_index": 1, 228 | "column_index": 1, 229 | "hits_for_phrase_in_col": 2, 230 | "idx": 5, 231 | }, 232 | ], 233 | "title": "Usable phrase matches for each phrase/column combination", 234 | } 235 | assert expected == json.loads(r)["y"] 236 | --------------------------------------------------------------------------------