pax_global_header00006660000000000000000000000064142711026150014511gustar00rootroot0000000000000052 comment=f86b44933b3d0907f58c7db01411e7148b9f59dc sqlite-fts4-1.0.3/000077500000000000000000000000001427110261500136715ustar00rootroot00000000000000sqlite-fts4-1.0.3/.github/000077500000000000000000000000001427110261500152315ustar00rootroot00000000000000sqlite-fts4-1.0.3/.github/workflows/000077500000000000000000000000001427110261500172665ustar00rootroot00000000000000sqlite-fts4-1.0.3/.github/workflows/deploy-demo.yml000066400000000000000000000021521427110261500222270ustar00rootroot00000000000000name: Deploy demo on: workflow_dispatch: jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v3 with: python-version: '3.10' - uses: actions/cache@v2 name: Configure pip caching with: path: ~/.cache/pip key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} restore-keys: | ${{ runner.os }}-publish-pip- - name: Publish demo env: GITHUB_SHA: ${{ env.GITHUB_SHA }} NOW_TOKEN: ${{ secrets.NOW_TOKEN }} run: |- curl --fail --silent -o 24ways-fts4.db https://static.simonwillison.net/static/2022/24ways-fts4.db pip install datasette datasette-publish-vercel datasette publish vercel 24ways-fts4.db \ --token $NOW_TOKEN \ --project datasette-sqlite-fts4 \ --install https://github.com/simonw/sqlite-fts4/archive/$GITHUB_SHA.zip \ --install datasette-sqlite-fts4 \ --install datasette-json-html \ --source_url=https://github.com/simonw/sqlite-fts4 sqlite-fts4-1.0.3/.github/workflows/publish.yml000066400000000000000000000041041427110261500214560ustar00rootroot00000000000000name: Publish Python Package on: release: types: [created] jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: [3.6, 3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - uses: actions/cache@v2 name: Configure pip caching with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} restore-keys: | ${{ runner.os }}-pip- - name: Install dependencies run: | pip install -e '.[test]' - name: Run tests run: | pytest deploy: runs-on: ubuntu-latest needs: [test] steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.9' - uses: actions/cache@v2 name: Configure pip caching with: path: ~/.cache/pip key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} restore-keys: | ${{ runner.os }}-publish-pip- - name: Install dependencies run: | pip install setuptools wheel twine - name: Publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | python setup.py sdist bdist_wheel twine upload dist/* - name: Publish demo env: GITHUB_SHA: ${{ env.GITHUB_SHA }} NOW_TOKEN: ${{ secrets.NOW_TOKEN }} run: |- curl --fail --silent -o 24ways-fts4.db https://static.simonwillison.net/static/2022/24ways-fts4.db pip install datasette datasette-publish-vercel datasette publish vercel 24ways-fts4.db \ --token $NOW_TOKEN \ --project datasette-sqlite-fts4 \ --install https://github.com/simonw/sqlite-fts4/archive/$GITHUB_SHA.zip \ --install datasette-sqlite-fts4 \ --install datasette-json-html \ --source_url=https://github.com/simonw/sqlite-fts4 sqlite-fts4-1.0.3/.github/workflows/test.yml000066400000000000000000000012631427110261500207720ustar00rootroot00000000000000name: Test on: [push] jobs: test: runs-on: ubuntu-latest strategy: matrix: python-version: [3.6, 3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - uses: actions/cache@v2 name: Configure pip caching with: path: ~/.cache/pip key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} restore-keys: | ${{ runner.os }}-pip- - name: Install dependencies run: | pip install -e '.[test]' - name: Run tests run: | pytest sqlite-fts4-1.0.3/.gitignore000066400000000000000000000000601427110261500156550ustar00rootroot00000000000000*.pyc __pycache__ venv .eggs *.egg-info .vscode sqlite-fts4-1.0.3/LICENSE000066400000000000000000000261351427110261500147050ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. sqlite-fts4-1.0.3/README.md000066400000000000000000000136011427110261500151510ustar00rootroot00000000000000# sqlite-fts4 [![PyPI](https://img.shields.io/pypi/v/sqlite-fts4.svg)](https://pypi.org/project/sqlite-fts4/) [![Changelog](https://img.shields.io/github/v/release/simonw/sqlite-fts4?include_prereleases&label=changelog)](https://github.com/simonw/sqlite-fts4/releases) [![Tests](https://github.com/simonw/sqlite-fts4/workflows/Test/badge.svg)](https://github.com/simonw/sqlite-fts4/actions?query=workflow%3ATest) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/sqlite-fts4/blob/main/LICENSE) Custom SQLite functions written in Python for ranking documents indexed using the FTS4 extension. Read [Exploring search relevance algorithms with SQLite](https://simonwillison.net/2019/Jan/7/exploring-search-relevance-algorithms-sqlite/) for further details on this project. ## Demo 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). ## Installation pip install sqlite-fts4 ## Usage This module implements several custom SQLite3 functions. You can register them against an existing SQLite connection like so: ```python import sqlite3 from sqlite_fts4 import register_functions conn = sqlite3.connect(":memory:") register_functions(conn) ``` If you only want a subset of the functions registered you can do so like this: ```python from sqlite_fts4 import rank_score conn = sqlite3.connect(":memory:") conn.create_function("rank_score", 1, rank_score) ``` 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: pip install datasette-sqlite-fts4 ## rank_score() 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. You can use it in a query like this: ```sql select *, rank_score(matchinfo(docs, "pcx")) as score from docs where docs match "dog" order by score desc ``` You *must* use the `"pcx"` matchinfo format string here, or you will get incorrect results. ## rank_bm25() An implementation of the [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) scoring algorithm. Use it in a query like this: ```sql select *, rank_bm25(matchinfo(docs, "pcnalx")) as score from docs where docs match "dog" order by score desc ``` 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. ## decode_matchinfo() 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. The `decode_matchinfo()` function decodes the binary string and converts it into a JSON list of integers. Usage: ```sql select *, decode_matchinfo(matchinfo(docs, "pcx")) from docs where docs match "dog" ``` Example output: hello dog, [1, 1, 1, 1, 1] ## annotate_matchinfo() This function decodes the matchinfo document into a verbose JSON structure that describes exactly what each of the returned integers actually means. Full documentation for the different format string options can be found here: https://www.sqlite.org/fts3.html#matchinfo You need to call this function with the same format string as was passed to `matchinfo()` - for example: ```sql select annotate_matchinfo(matchinfo(docs, "pcxnal"), "pcxnal") from docs where docs match "dog" ``` The returned JSON will include a key for each letter in the format string. For example: ```json { "p": { "value": 1, "title": "Number of matchable phrases in the query" }, "c": { "value": 1, "title": "Number of user defined columns in the FTS table" }, "x": { "value": [ { "column_index": 0, "phrase_index": 0, "hits_this_column_this_row": 1, "hits_this_column_all_rows": 2, "docs_with_hits": 2 } ], "title": "Details for each phrase/column combination" }, "n": { "value": 3, "title": "Number of rows in the FTS4 table" }, "a": { "title":"Average number of tokens in the text values stored in each column", "value": [ { "column_index": 0, "average_num_tokens": 2 } ] }, "l": { "title": "Length of value stored in current row of the FTS4 table in tokens for each column", "value": [ { "column_index": 0, "length_of_value": 2 } ] } } ``` sqlite-fts4-1.0.3/setup.py000066400000000000000000000016401427110261500154040ustar00rootroot00000000000000from setuptools import setup import os VERSION = "1.0.3" def get_long_description(): with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), encoding="utf8", ) as fp: return fp.read() setup( name="sqlite-fts4", description="Python functions for working with SQLite FTS4 search", long_description=get_long_description(), long_description_content_type="text/markdown", author="Simon Willison", url="https://github.com/simonw/sqlite-fts4", project_urls={ "Issues": "https://github.com/simonw/sqlite-fts4/issues", "CI": "https://github.com/simonw/sqlite-fts4/actions", "Changelog": "https://github.com/simonw/sqlite-fts4/releases", }, license="Apache License, Version 2.0", version=VERSION, packages=["sqlite_fts4"], extras_require={"test": ["pytest"]}, tests_require=["sqlite-fts4[test]"], ) sqlite-fts4-1.0.3/sqlite_fts4/000077500000000000000000000000001427110261500161325ustar00rootroot00000000000000sqlite-fts4-1.0.3/sqlite_fts4/__init__.py000066400000000000000000000237271427110261500202560ustar00rootroot00000000000000import struct import math import json import traceback from functools import wraps def register_functions(conn): "Registers these custom functions against an SQLite connection" conn.create_function("rank_score", 1, rank_score) conn.create_function("decode_matchinfo", 1, decode_matchinfo_str) conn.create_function("annotate_matchinfo", 2, annotate_matchinfo) conn.create_function("rank_bm25", 1, rank_bm25) def wrap_sqlite_function_in_error_logger(fn): # Because SQLite swallows exceptions inside custom functions @wraps(fn) def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception: traceback.print_exc() raise return wrapper def decode_matchinfo_str(buf): return str(list(decode_matchinfo(buf))) def decode_matchinfo(buf): # buf is a bytestring of unsigned integers, each 4 bytes long return struct.unpack("@" + ("I" * (len(buf) // 4)), buf) def _error(m): return {"error": m} @wrap_sqlite_function_in_error_logger def annotate_matchinfo(buf, format_string): return json.dumps(_annotate_matchinfo(buf, format_string), indent=2) def _annotate_matchinfo(buf, format_string): # See https://www.sqlite.org/fts3.html#matchinfo for detailed specification matchinfo = list(decode_matchinfo(buf)) if not matchinfo: return {} matchinfo_index = 0 p_num_phrases = None c_num_columns = None def _next(): nonlocal matchinfo_index value = matchinfo[matchinfo_index] matchinfo_index += 1 return value, matchinfo_index - 1 results = {} for ch in format_string: if ch == "p": p_num_phrases, idx = _next() results["p"] = { "value": p_num_phrases, "title": "Number of matchable phrases in the query", "idx": idx, } elif ch == "c": c_num_columns, idx = _next() results["c"] = { "value": c_num_columns, "title": "Number of user defined columns in the FTS table", "idx": idx, } elif ch == "x": # Depends on p and c if None in (p_num_phrases, c_num_columns): return _error("'x' must be preceded by 'p' and 'c'") info = [] results["x"] = { "value": info, "title": "Details for each phrase/column combination", } # 3 * c_num_columns * p_num_phrases for phrase_index in range(p_num_phrases): for column_index in range(c_num_columns): hits_this_column_this_row, idx1 = _next() hits_this_column_all_rows, idx2 = _next() docs_with_hits, idx3 = _next() info.append( { "phrase_index": phrase_index, "column_index": column_index, "hits_this_column_this_row": hits_this_column_this_row, "hits_this_column_all_rows": hits_this_column_all_rows, "docs_with_hits": docs_with_hits, "idxs": [idx1, idx2, idx3], } ) elif ch == "y": if None in (p_num_phrases, c_num_columns): return _error("'y' must be preceded by 'p' and 'c'") info = [] results["y"] = { "value": info, "title": "Usable phrase matches for each phrase/column combination", } for phrase_index in range(p_num_phrases): for column_index in range(c_num_columns): hits_for_phrase_in_col, idx = _next() info.append( { "phrase_index": phrase_index, "column_index": column_index, "hits_for_phrase_in_col": hits_for_phrase_in_col, "idx": idx, } ) elif ch == "b": if None in (p_num_phrases, c_num_columns): return _error("'b' must be preceded by 'p' and 'c'") values = [] # We get back one integer for each 32 columns for each phrase num_32_column_chunks = (c_num_columns + 31) // 32 decoded = {} for phrase_index in range(p_num_phrases): current_phrase_chunks = [] for _ in range(num_32_column_chunks): v = _next()[0] values.append(v) current_phrase_chunks.append(v) decoded["phrase_{}".format(phrase_index)] = "".join( [ "{:032b}".format(unsigned_integer)[::-1] for unsigned_integer in current_phrase_chunks ] ) results["b"] = { "title": "Bitfield showing which phrases occur in which columns", "value": values, # Each integer is a 32bit unsigned integer, least significant # bit is column 0, then column 1, then so on "decoded": decoded, } elif ch == "n": value, idx = _next() results["n"] = { "value": value, "title": "Number of rows in the FTS4 table", "idx": idx, } elif ch == "a": if c_num_columns is None: return _error("'a' must be preceded by 'c'") values = [] for i in range(c_num_columns): value, idx = _next() values.append( {"column_index": i, "average_num_tokens": value, "idx": idx} ) results["a"] = { "title": "Average number of tokens in each column across the whole table", "value": values, } elif ch == "l": if c_num_columns is None: return _error("'l' must be preceded by 'c'") values = [] for i in range(c_num_columns): value, idx = _next() values.append({"column_index": i, "num_tokens": value, "idx": idx}) results["l"] = { "title": "Number of tokens in each column of the current row of the FTS4 table", "value": values, } elif ch == "s": if c_num_columns is None: return _error("'s' must be preceded by 'c'") values = [] for i in range(c_num_columns): value, idx = _next() values.append( { "column_index": i, "length_phrase_subsequence_match": value, "idx": idx, } ) results["s"] = { "title": "Length of longest subsequence of phrase matching each column", "value": values, } return results @wrap_sqlite_function_in_error_logger def rank_score(raw_matchinfo): # Score using matchinfo called w/default args 'pcx' - based on example rank # function http://sqlite.org/fts3.html#appendix_a # The overall relevancy returned is the sum of the relevancies of each # column value in the FTS table. The relevancy of a column value is the # sum of the following for each reportable phrase in the FTS query: # ( / ) if not raw_matchinfo: return None matchinfo = _annotate_matchinfo(raw_matchinfo, "pcx") score = 0.0 x_phrase_column_details = matchinfo["x"]["value"] for details in x_phrase_column_details: hits_this_column_this_row = details["hits_this_column_this_row"] hits_this_column_all_rows = details["hits_this_column_all_rows"] if hits_this_column_this_row > 0: score += float(hits_this_column_this_row) / hits_this_column_all_rows return -score @wrap_sqlite_function_in_error_logger def rank_bm25(raw_match_info): "Must be called with output of matchinfo 'pcnalx'" if not raw_match_info: return None match_info = _annotate_matchinfo(raw_match_info, "pcnalx") # How much should multiple matches in the same document increase the score? k = 1.2 # How much should document length affect the score? (shorter docs = higher score) b = 0.75 score = 0.0 phrase_count = match_info["p"]["value"] column_count = match_info["c"]["value"] total_row_count = match_info["n"]["value"] for phrase_index in range(phrase_count): for column_index in range(column_count): average_num_tokens = match_info["a"]["value"][column_index][ "average_num_tokens" ] num_tokens = match_info["l"]["value"][column_index]["num_tokens"] if average_num_tokens == 0: d = 0 else: d = 1 - b + (b * (float(num_tokens) / float(average_num_tokens))) phrase_column_x = [ v for v in match_info["x"]["value"] if v["column_index"] == column_index and v["phrase_index"] == phrase_index ][0] term_frequency = float(phrase_column_x["hits_this_column_this_row"]) docs_with_hits = float(phrase_column_x["docs_with_hits"]) # idf = inverse document frequency: is this term rare or common # across our entire corpus? idf = max( math.log( (total_row_count - docs_with_hits + 0.5) / (docs_with_hits + 0.5) ), 0, ) denom = term_frequency + (k * d) if denom == 0: rhs = 0 else: rhs = (term_frequency * (k + 1)) / denom score += idf * rhs return -score sqlite-fts4-1.0.3/tests/000077500000000000000000000000001427110261500150335ustar00rootroot00000000000000sqlite-fts4-1.0.3/tests/__init__.py000066400000000000000000000000001427110261500171320ustar00rootroot00000000000000sqlite-fts4-1.0.3/tests/conftest.py000066400000000000000000000002661427110261500172360ustar00rootroot00000000000000import sqlite3 def pytest_report_header(config): return "SQLite version: {}".format( sqlite3.connect(":memory:").execute("select sqlite_version()").fetchone()[0] ) sqlite-fts4-1.0.3/tests/test_sqlite_fts4.py000066400000000000000000000155451427110261500207170ustar00rootroot00000000000000import sqlite3 from sqlite_fts4 import register_functions, decode_matchinfo import pytest import json import sys sqlite_version = tuple( map( int, sqlite3.connect(":memory:") .execute("select sqlite_version()") .fetchone()[0] .split("."), ) ) @pytest.fixture def conn(): conn = sqlite3.connect(":memory:") register_functions(conn) conn.executescript( """ CREATE VIRTUAL TABLE search USING fts4(c0, c1); INSERT INTO search (c0, c1) VALUES ("this is about a dog", "more about that dog dog"); INSERT INTO search (c0, c1) VALUES ("this is about a cat", "stuff on that cat cat"); INSERT INTO search (c0, c1) VALUES ("something about a ferret", "yeah a ferret ferret"); INSERT INTO search (c0, c1) VALUES ("both of them", "both dog dog and cat here"); INSERT INTO search (c0, c1) VALUES ("not mammals", "maybe talk about fish"); """ ) return conn def test_fixture_sets_up_database(conn): assert 5 == conn.execute("select count(*) from search").fetchone()[0] @pytest.mark.parametrize( "search,expected", [ ("dog", [1, 2, 1, 1, 1, 2, 4, 2, 5, 4, 5, 5, 5]), ("cat", [1, 2, 1, 1, 1, 2, 3, 2, 5, 4, 5, 5, 5]), ], ) def test_decode_matchinfo(conn, search, expected): r = conn.execute( """ select decode_matchinfo(matchinfo(search, 'pcxnal')) from search where search match ? """, [search], ).fetchone()[0] assert expected == json.loads(r) @pytest.mark.parametrize( "buf,expected", [ ( b"\x01\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00" if sys.byteorder == "little" else b"\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x02", (1, 2, 2, 2), ) ], ) def test_underlying_decode_matchinfo(buf, expected): assert expected == decode_matchinfo(buf) def test_rank_bm25(conn): results = conn.execute( """ select c0, c1, rank_bm25(matchinfo(search, 'pcnalx')) as bm25 from search where search match ? """, ["dog"], ).fetchall() assert ("this is about a dog", "more about that dog dog") == results[0][:2] assert pytest.approx(-1.459328) == results[0][2] assert ("both of them", "both dog dog and cat here") == results[1][:2] assert pytest.approx(-0.438011) == results[1][2] def test_rank_bm25_no_match(conn): results = conn.execute( """ select c0, c1, rank_bm25(matchinfo(search, 'pcnalx')) as bm25 from search limit 1 """ ).fetchall() assert None == results[0][2] def test_annotate_matchinfo(conn): r = conn.execute( """ select annotate_matchinfo(matchinfo(search, 'pcxnals'), 'pcxnals') from search where search match ? """, ["dog"], ).fetchone()[0] expected = { "p": { "value": 1, "title": "Number of matchable phrases in the query", "idx": 0, }, "c": { "value": 2, "title": "Number of user defined columns in the FTS table", "idx": 1, }, "x": { "value": [ { "phrase_index": 0, "column_index": 0, "hits_this_column_this_row": 1, "hits_this_column_all_rows": 1, "docs_with_hits": 1, "idxs": [2, 3, 4], }, { "phrase_index": 0, "column_index": 1, "hits_this_column_this_row": 2, "hits_this_column_all_rows": 4, "docs_with_hits": 2, "idxs": [5, 6, 7], }, ], "title": "Details for each phrase/column combination", }, "n": {"value": 5, "title": "Number of rows in the FTS4 table", "idx": 8}, "a": { "title": "Average number of tokens in each column across the whole table", "value": [ {"column_index": 0, "average_num_tokens": 4, "idx": 9}, {"column_index": 1, "average_num_tokens": 5, "idx": 10}, ], }, "l": { "title": "Number of tokens in each column of the current row of the FTS4 table", "value": [ {"column_index": 0, "num_tokens": 5, "idx": 11}, {"column_index": 1, "num_tokens": 5, "idx": 12}, ], }, "s": { "title": "Length of longest subsequence of phrase matching each column", "value": [ {"column_index": 0, "length_phrase_subsequence_match": 1, "idx": 13}, {"column_index": 1, "length_phrase_subsequence_match": 1, "idx": 14}, ], }, } assert expected == json.loads(r) def test_annotate_matchinfo_empty(conn): r = conn.execute( """ select annotate_matchinfo(matchinfo(search, 'pcxnals'), 'pcxnals') from search limit 1 """ ).fetchone()[0] assert {} == json.loads(r) @pytest.mark.skipif( sqlite_version < (3, 8, 11), reason="matchinfo 'b' was added in SQLite 3.8.11" ) def test_annotate_matchinfo_b(conn): r = conn.execute( """ select annotate_matchinfo(matchinfo(search, 'pcb'), 'pcb') from search where search match ? """, ["something ferret"], ).fetchone()[0] expected = { "title": "Bitfield showing which phrases occur in which columns", "value": [1, 3], "decoded": { "phrase_0": "10000000000000000000000000000000", "phrase_1": "11000000000000000000000000000000", }, } assert expected == json.loads(r)["b"] @pytest.mark.skipif( sqlite_version < (3, 8, 10), reason="matchinfo 'y' was added in SQLite 3.8.10" ) def test_annotate_matchinfo_y(conn): r = conn.execute( """ select annotate_matchinfo(matchinfo(search, 'pcy'), 'pcy') from search where search match ? """, ["something ferret"], ).fetchone()[0] expected = { "value": [ { "phrase_index": 0, "column_index": 0, "hits_for_phrase_in_col": 1, "idx": 2, }, { "phrase_index": 0, "column_index": 1, "hits_for_phrase_in_col": 0, "idx": 3, }, { "phrase_index": 1, "column_index": 0, "hits_for_phrase_in_col": 1, "idx": 4, }, { "phrase_index": 1, "column_index": 1, "hits_for_phrase_in_col": 2, "idx": 5, }, ], "title": "Usable phrase matches for each phrase/column combination", } assert expected == json.loads(r)["y"]