# 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
}
]
}
}
```
Raw data
{
"_id": null,
"home_page": "https://github.com/simonw/sqlite-fts4",
"name": "sqlite-fts4",
"maintainer": "",
"docs_url": null,
"requires_python": "",
"maintainer_email": "",
"keywords": "",
"author": "Simon Willison",
"author_email": "",
"download_url": "https://files.pythonhosted.org/packages/c2/6d/9dad6c3b433ab8912ace969c66abd595f8e0a2ccccdb73602b1291dbda29/sqlite-fts4-1.0.3.tar.gz",
"platform": null,
"description": "# sqlite-fts4\n\n[![PyPI](https://img.shields.io/pypi/v/sqlite-fts4.svg)](https://pypi.org/project/sqlite-fts4/)\n[![Changelog](https://img.shields.io/github/v/release/simonw/sqlite-fts4?include_prereleases&label=changelog)](https://github.com/simonw/sqlite-fts4/releases)\n[![Tests](https://github.com/simonw/sqlite-fts4/workflows/Test/badge.svg)](https://github.com/simonw/sqlite-fts4/actions?query=workflow%3ATest)\n[![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/sqlite-fts4/blob/main/LICENSE)\n\nCustom SQLite functions written in Python for ranking documents indexed using the FTS4 extension.\n\nRead [Exploring search relevance algorithms with SQLite](https://simonwillison.net/2019/Jan/7/exploring-search-relevance-algorithms-sqlite/) for further details on this project.\n\n## Demo\n\nYou 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).\n\n## Installation\n\n pip install sqlite-fts4\n\n## Usage\n\nThis module implements several custom SQLite3 functions. You can register them against an existing SQLite connection like so:\n\n```python\nimport sqlite3\nfrom sqlite_fts4 import register_functions\n\nconn = sqlite3.connect(\":memory:\")\nregister_functions(conn)\n```\n\nIf you only want a subset of the functions registered you can do so like this:\n\n```python\nfrom sqlite_fts4 import rank_score\n\nconn = sqlite3.connect(\":memory:\")\nconn.create_function(\"rank_score\", 1, rank_score)\n```\n\nif 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:\n\n pip install datasette-sqlite-fts4\n\n## rank_score()\n\nThis 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.\n\nYou can use it in a query like this:\n\n```sql\nselect *, rank_score(matchinfo(docs, \"pcx\")) as score\nfrom docs where docs match \"dog\"\norder by score desc\n```\n\nYou *must* use the `\"pcx\"` matchinfo format string here, or you will get incorrect results.\n\n## rank_bm25()\n\nAn implementation of the [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) scoring algorithm. Use it in a query like this:\n\n```sql\nselect *, rank_bm25(matchinfo(docs, \"pcnalx\")) as score\nfrom docs where docs match \"dog\"\norder by score desc\n```\n\nYou *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.\n\n## decode_matchinfo()\n\nSQLite'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.\n\nThe `decode_matchinfo()` function decodes the binary string and converts it into a JSON list of integers.\n\nUsage:\n\n```sql\nselect *, decode_matchinfo(matchinfo(docs, \"pcx\"))\nfrom docs where docs match \"dog\"\n```\n\nExample output:\n\n hello dog, [1, 1, 1, 1, 1]\n\n## annotate_matchinfo()\n\nThis function decodes the matchinfo document into a verbose JSON structure that describes exactly what each of the returned integers actually means.\n\nFull documentation for the different format string options can be found here: https://www.sqlite.org/fts3.html#matchinfo\n\nYou need to call this function with the same format string as was passed to `matchinfo()` - for example:\n\n```sql\nselect annotate_matchinfo(matchinfo(docs, \"pcxnal\"), \"pcxnal\")\nfrom docs where docs match \"dog\"\n```\n\nThe returned JSON will include a key for each letter in the format string. For example:\n\n```json\n{\n \"p\": {\n \"value\": 1,\n \"title\": \"Number of matchable phrases in the query\"\n },\n \"c\": {\n \"value\": 1,\n \"title\": \"Number of user defined columns in the FTS table\"\n },\n \"x\": {\n \"value\": [\n {\n \"column_index\": 0,\n \"phrase_index\": 0,\n \"hits_this_column_this_row\": 1,\n \"hits_this_column_all_rows\": 2,\n \"docs_with_hits\": 2\n }\n ],\n \"title\": \"Details for each phrase/column combination\"\n },\n \"n\": {\n \"value\": 3,\n \"title\": \"Number of rows in the FTS4 table\"\n },\n \"a\": {\n \"title\":\"Average number of tokens in the text values stored in each column\",\n \"value\": [\n {\n \"column_index\": 0,\n \"average_num_tokens\": 2\n }\n ]\n },\n \"l\": {\n \"title\": \"Length of value stored in current row of the FTS4 table in tokens for each column\",\n \"value\": [\n {\n \"column_index\": 0,\n \"length_of_value\": 2\n }\n ]\n }\n}\n```\n\n\n",
"bugtrack_url": null,
"license": "Apache License, Version 2.0",
"summary": "Python functions for working with SQLite FTS4 search",
"version": "1.0.3",
"project_urls": {
"CI": "https://github.com/simonw/sqlite-fts4/actions",
"Changelog": "https://github.com/simonw/sqlite-fts4/releases",
"Homepage": "https://github.com/simonw/sqlite-fts4",
"Issues": "https://github.com/simonw/sqlite-fts4/issues"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "51290096e8b1811aaa78cfb296996f621f41120c21c2f5cd448ae1d54979d9fc",
"md5": "28909a861078e1f3323a88752b7ff3c0",
"sha256": "0359edd8dea6fd73c848989e1e2b1f31a50fe5f9d7272299ff0e8dbaa62d035f"
},
"downloads": -1,
"filename": "sqlite_fts4-1.0.3-py3-none-any.whl",
"has_sig": false,
"md5_digest": "28909a861078e1f3323a88752b7ff3c0",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": null,
"size": 9972,
"upload_time": "2022-07-30T01:14:24",
"upload_time_iso_8601": "2022-07-30T01:14:24.942080Z",
"url": "https://files.pythonhosted.org/packages/51/29/0096e8b1811aaa78cfb296996f621f41120c21c2f5cd448ae1d54979d9fc/sqlite_fts4-1.0.3-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "c26d9dad6c3b433ab8912ace969c66abd595f8e0a2ccccdb73602b1291dbda29",
"md5": "03b27f20173c3a2ccd15ccbec8e56566",
"sha256": "78b05eeaf6680e9dbed8986bde011e9c086a06cb0c931b3cf7da94c214e8930c"
},
"downloads": -1,
"filename": "sqlite-fts4-1.0.3.tar.gz",
"has_sig": false,
"md5_digest": "03b27f20173c3a2ccd15ccbec8e56566",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 9718,
"upload_time": "2022-07-30T01:14:26",
"upload_time_iso_8601": "2022-07-30T01:14:26.943861Z",
"url": "https://files.pythonhosted.org/packages/c2/6d/9dad6c3b433ab8912ace969c66abd595f8e0a2ccccdb73602b1291dbda29/sqlite-fts4-1.0.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2022-07-30 01:14:26",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "simonw",
"github_project": "sqlite-fts4",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "sqlite-fts4"
}