seecr-sil 3.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- seecr_sil-3.4.0.dist-info/METADATA +62 -0
- seecr_sil-3.4.0.dist-info/RECORD +22 -0
- seecr_sil-3.4.0.dist-info/WHEEL +5 -0
- seecr_sil-3.4.0.dist-info/licenses/LICENSE +21 -0
- seecr_sil-3.4.0.dist-info/top_level.txt +1 -0
- sil/__init__.py +16 -0
- sil/_version.py +24 -0
- sil/ascii_folding_test.py +89 -0
- sil/commit.py +42 -0
- sil/cql.py +342 -0
- sil/cql_test.py +207 -0
- sil/drilldown.py +110 -0
- sil/drilldown_test.py +132 -0
- sil/engine.py +140 -0
- sil/engine_test.py +59 -0
- sil/index.py +599 -0
- sil/index_test.py +998 -0
- sil/indexfield.py +337 -0
- sil/indexprofile.py +40 -0
- sil/suggester.py +93 -0
- sil/testdata/restart-opstamp.tar.gz +0 -0
- sil/utils.py +38 -0
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: seecr-sil
|
|
3
|
+
Version: 3.4.0
|
|
4
|
+
Summary: Seecr Indexing Lib: search, sorting, drilldown and suggestions on tantivy
|
|
5
|
+
Author-email: Thijs Janssen <thijs@seecr.nl>, Johan Jonkers <johan@seecr.nl>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Documentation, https://github.com/seecr/sil/blob/master/doc/reference.md
|
|
8
|
+
Project-URL: Source, https://github.com/seecr/sil
|
|
9
|
+
Project-URL: Issues, https://github.com/seecr/sil/issues
|
|
10
|
+
Project-URL: Changelog, https://github.com/seecr/sil/blob/master/CHANGELOG.md
|
|
11
|
+
Keywords: search,index,full-text,tantivy,drilldown,facets,cql,seecr
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Operating System :: POSIX
|
|
20
|
+
Classifier: Intended Audience :: Developers
|
|
21
|
+
Classifier: Topic :: Database
|
|
22
|
+
Classifier: Topic :: Text Processing :: Indexing
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
License-File: LICENSE
|
|
27
|
+
Requires-Dist: tantivy<0.28,>=0.27.0
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# sil – Seecr Indexing Lib
|
|
31
|
+
|
|
32
|
+
A search index for Python applications, on [tantivy](https://github.com/quickwit-oss/tantivy):
|
|
33
|
+
an index profile in Python, a forgiving query language, sorting on several fields,
|
|
34
|
+
drilldown (counts per value), suggestions while typing, and commits on a timer. One index
|
|
35
|
+
is one directory; no server, no JVM.
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from sil.index import Index
|
|
39
|
+
from sil.indexfield import IndexField
|
|
40
|
+
from sil.indexprofile import IndexProfile
|
|
41
|
+
|
|
42
|
+
index = Index(path, IndexProfile([
|
|
43
|
+
IndexField.unqualified("all"),
|
|
44
|
+
IndexField.untokenized("genre", drilldown=True),
|
|
45
|
+
IndexField.int("year", sortable=True),
|
|
46
|
+
]), immediate_commit=True)
|
|
47
|
+
|
|
48
|
+
index.add_record("book-1", {"all": "Dune Frank Herbert", "genre": "sf", "year": 1965})
|
|
49
|
+
index.search_query("dune", sort="year", drilldown=[{"name": "genre"}])
|
|
50
|
+
# {"count": 1, "docs": [{"__id__": "book-1"}], "drilldown": {"genre": [("sf", 1)]}}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Install with `pip install seecr-sil` (the package is `sil`). It needs Python 3.11 or
|
|
54
|
+
newer and tantivy.
|
|
55
|
+
|
|
56
|
+
The [reference](https://github.com/seecr/sil/blob/master/doc/reference.md) describes
|
|
57
|
+
everything; the [changelog](https://github.com/seecr/sil/blob/master/CHANGELOG.md) says
|
|
58
|
+
what changed. sil was built on Lucene (through JCC) up to 2.x; 3.0 replaced it with
|
|
59
|
+
tantivy.
|
|
60
|
+
|
|
61
|
+
MIT licensed, see [LICENSE](https://github.com/seecr/sil/blob/master/LICENSE). By
|
|
62
|
+
[Seecr](https://seecr.nl).
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
seecr_sil-3.4.0.dist-info/licenses/LICENSE,sha256=nq9QCRLQlighwTdCwjAx3Qcb7Xa0rUuVUI4wB_K1Ad4,1104
|
|
2
|
+
sil/__init__.py,sha256=XrEeID-WVWYKU1FvlhEwmpTzj7Y7bz4y7eCAgNT3iyE,391
|
|
3
|
+
sil/_version.py,sha256=HloDv9wD3xbpSAtf7HX3RIIpKI820y3gsxdxxBUcuIc,528
|
|
4
|
+
sil/ascii_folding_test.py,sha256=1Jw41f34_C6HRuzsWejmOmfuqN6OS-mzE08991gWX6Y,2965
|
|
5
|
+
sil/commit.py,sha256=BnVu2ro8aiwb2b_WGcBCBuYjE8CpqF7OZ4hZay8sBD8,1044
|
|
6
|
+
sil/cql.py,sha256=NyZy357fgMF5ZSuxTKmbExosOjSsut2JK-7_w9PKsOk,11841
|
|
7
|
+
sil/cql_test.py,sha256=zCaSNM7mbt99hm4Rld7vn9sI_WffsDUQEZpuaTbWQeA,6989
|
|
8
|
+
sil/drilldown.py,sha256=Ebu7aUe4X6GRwVbkgYANlhXb6FG1d2SbxPpS3mw8Dg8,4016
|
|
9
|
+
sil/drilldown_test.py,sha256=suREQg9c0vkFcJ1qOMFDx2dO0b9wgPML7mDtpfFmUcY,4714
|
|
10
|
+
sil/engine.py,sha256=O779jAjtwRaEAfxxc8Sbs1qUWyPCocIXC-QBZ2TnxHk,5156
|
|
11
|
+
sil/engine_test.py,sha256=AMqJIjFDnD8X1iY-pI9byALolUIKf15sba0dzXjGlm4,2247
|
|
12
|
+
sil/index.py,sha256=EGlTWAHqvqXSMzJ4FQyDSyvJNaPX-ZX3C1DbGyDc3HU,23476
|
|
13
|
+
sil/index_test.py,sha256=XReEC6eYhck4jkHVgKBkIwbMkopflQ-7S0hQgYpFPNA,34060
|
|
14
|
+
sil/indexfield.py,sha256=d4F8nhK2k1c-dWJ0leO5Gh_qEOICCGHScWphX81wtkg,12206
|
|
15
|
+
sil/indexprofile.py,sha256=zmoWGV8wX5sUZUJRxTeOrEYisO9ZpN_2Po-FgIPg2XQ,1160
|
|
16
|
+
sil/suggester.py,sha256=Khw6_hPSs9cBqvYWf70s1Aj8cjS_T5G7PPa4G1yLBYQ,2962
|
|
17
|
+
sil/utils.py,sha256=dCFlxIGl2em9FH9EQuzz_-DN5KEuR8HCkg2lzsCD9qM,904
|
|
18
|
+
sil/testdata/restart-opstamp.tar.gz,sha256=t-jtv1KsCbF9G6_bc7DQ8RYyDDWaYfTraJs6HzRatlE,14981
|
|
19
|
+
seecr_sil-3.4.0.dist-info/METADATA,sha256=Fby5eyM-p3y-OdGhzBHhvFwWtP7j3VnUj1sB66BlJmo,2697
|
|
20
|
+
seecr_sil-3.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
21
|
+
seecr_sil-3.4.0.dist-info/top_level.txt,sha256=sol_T3SRwC1mPuQz1U2tw7G5IM6RzkcGTi0DHHYl3ec,4
|
|
22
|
+
seecr_sil-3.4.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Seecr (Seek You Too B.V.) https://seecr.nl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sil
|
sil/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
## begin license ##
|
|
2
|
+
#
|
|
3
|
+
# "SIL"(Seecr Indexing Lib) provides a search index on tantivy
|
|
4
|
+
#
|
|
5
|
+
# Copyright (C) 2025-2026 Seecr (Seek You Too B.V.) https://seecr.nl
|
|
6
|
+
#
|
|
7
|
+
# This file is part of "sil"
|
|
8
|
+
#
|
|
9
|
+
# "sil" is licensed under the MIT License; see the LICENSE file.
|
|
10
|
+
# SPDX-License-Identifier: MIT
|
|
11
|
+
#
|
|
12
|
+
## end license ##
|
|
13
|
+
|
|
14
|
+
from ._version import __version__ # noqa: E402
|
|
15
|
+
|
|
16
|
+
VERSION = __version__.split("+")[0]
|
sil/_version.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '3.4.0'
|
|
22
|
+
__version_tuple__ = version_tuple = (3, 4, 0)
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = 'g143afa0be'
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
## begin license ##
|
|
2
|
+
#
|
|
3
|
+
# "SIL"(Seecr Indexing Lib) provides a search index on tantivy
|
|
4
|
+
#
|
|
5
|
+
# Copyright (C) 2025-2026 Seecr (Seek You Too B.V.) https://seecr.nl
|
|
6
|
+
#
|
|
7
|
+
# This file is part of "sil"
|
|
8
|
+
#
|
|
9
|
+
# "sil" is licensed under the MIT License; see the LICENSE file.
|
|
10
|
+
# SPDX-License-Identifier: MIT
|
|
11
|
+
#
|
|
12
|
+
## end license ##
|
|
13
|
+
|
|
14
|
+
import pytest
|
|
15
|
+
|
|
16
|
+
from .index import Index
|
|
17
|
+
from .indexfield import IndexField
|
|
18
|
+
from .indexprofile import IndexProfile
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def profile(ascii_folding=True):
|
|
22
|
+
return IndexProfile(
|
|
23
|
+
[
|
|
24
|
+
IndexField.unqualified("ALL", ascii_folding=ascii_folding),
|
|
25
|
+
IndexField.text("title", ascii_folding=ascii_folding),
|
|
26
|
+
]
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def add(index):
|
|
31
|
+
index.add_record("1", {"ALL": "Café de Paris", "title": "Café de Paris"})
|
|
32
|
+
index.add_record("2", {"ALL": "École Straße", "title": "École Straße"})
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def ids(result):
|
|
36
|
+
return sorted(hit["__id__"] for hit in result["docs"])
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_accents_are_folded(tmp_path):
|
|
40
|
+
index = Index(tmp_path, profile(), immediate_commit=True)
|
|
41
|
+
add(index)
|
|
42
|
+
for query in ["cafe", "café", "CAFÉ", "title:cafe", "title:Café"]:
|
|
43
|
+
assert ids(index.search_query(query)) == ["1"], query
|
|
44
|
+
assert ids(index.search_query("strasse")) == ["2"]
|
|
45
|
+
assert ids(index.search_query("ecol*")) == ["2"]
|
|
46
|
+
assert ids(index.search_query("écol*")) == ["2"]
|
|
47
|
+
assert ids(index.search_query('"ecole strasse"')) == ["2"]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def test_accents_are_folded_in_cql(tmp_path):
|
|
51
|
+
index = Index(tmp_path, profile(), immediate_commit=True)
|
|
52
|
+
add(index)
|
|
53
|
+
assert ids(index.search_cql("cafe")) == ["1"]
|
|
54
|
+
assert ids(index.search_cql("title = École")) == ["2"]
|
|
55
|
+
assert ids(index.search_cql("écol*")) == ["2"]
|
|
56
|
+
assert ids(index.search_cql('title = "ecole strasse"')) == ["2"]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_without_ascii_folding_accents_count(tmp_path):
|
|
60
|
+
index = Index(tmp_path, profile(ascii_folding=False), immediate_commit=True)
|
|
61
|
+
add(index)
|
|
62
|
+
assert ids(index.search_query("café")) == ["1"]
|
|
63
|
+
assert ids(index.search_query("cafe")) == []
|
|
64
|
+
assert ids(index.search_cql("cafe")) == []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_the_tokenizer_is_there_after_reopening(tmp_path):
|
|
68
|
+
index = Index(tmp_path, profile(), immediate_commit=True)
|
|
69
|
+
add(index)
|
|
70
|
+
index.shutdown()
|
|
71
|
+
|
|
72
|
+
index = Index(tmp_path, profile(), immediate_commit=True)
|
|
73
|
+
assert not index.needs_reindex
|
|
74
|
+
assert ids(index.search_query("cafe")) == ["1"]
|
|
75
|
+
index.add_record("3", {"ALL": "Crème brûlée", "title": "Crème brûlée"})
|
|
76
|
+
assert ids(index.search_query("creme brulee")) == ["3"]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def test_switching_ascii_folding_needs_a_reindex(tmp_path):
|
|
80
|
+
Index(tmp_path, profile(ascii_folding=False), immediate_commit=True).shutdown()
|
|
81
|
+
index = Index(tmp_path, profile(ascii_folding=True), immediate_commit=True)
|
|
82
|
+
assert index.needs_reindex
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def test_only_text_fields_fold():
|
|
86
|
+
with pytest.raises(ValueError):
|
|
87
|
+
IndexField.untokenized("code", ascii_folding=True)
|
|
88
|
+
with pytest.raises(ValueError):
|
|
89
|
+
IndexField.int("year", ascii_folding=True)
|
sil/commit.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
## begin license ##
|
|
2
|
+
#
|
|
3
|
+
# "SIL"(Seecr Indexing Lib) provides a search index on tantivy
|
|
4
|
+
#
|
|
5
|
+
# Copyright (C) 2025-2026 Seecr (Seek You Too B.V.) https://seecr.nl
|
|
6
|
+
#
|
|
7
|
+
# This file is part of "sil"
|
|
8
|
+
#
|
|
9
|
+
# "sil" is licensed under the MIT License; see the LICENSE file.
|
|
10
|
+
# SPDX-License-Identifier: MIT
|
|
11
|
+
#
|
|
12
|
+
## end license ##
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
import logging
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Commit:
|
|
21
|
+
def __init__(self, timeout=10):
|
|
22
|
+
self._timeout = timeout
|
|
23
|
+
self._targets = []
|
|
24
|
+
|
|
25
|
+
def add_target(self, target):
|
|
26
|
+
self._targets.append(target)
|
|
27
|
+
|
|
28
|
+
def do(self):
|
|
29
|
+
for target in self._targets:
|
|
30
|
+
target.commit()
|
|
31
|
+
|
|
32
|
+
async def _watch(self):
|
|
33
|
+
while True:
|
|
34
|
+
try:
|
|
35
|
+
self.do()
|
|
36
|
+
except Exception:
|
|
37
|
+
# keep committing: an uncaught error would end this task silently
|
|
38
|
+
logger.exception("Commit failed; retrying after the timeout")
|
|
39
|
+
await asyncio.sleep(self._timeout)
|
|
40
|
+
|
|
41
|
+
def as_task(self):
|
|
42
|
+
return asyncio.create_task(self._watch())
|
sil/cql.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
## begin license ##
|
|
2
|
+
#
|
|
3
|
+
# "SIL"(Seecr Indexing Lib) provides a search index on tantivy
|
|
4
|
+
#
|
|
5
|
+
# Copyright (C) 2025-2026 Seecr (Seek You Too B.V.) https://seecr.nl
|
|
6
|
+
#
|
|
7
|
+
# This file is part of "sil"
|
|
8
|
+
#
|
|
9
|
+
# "sil" is licensed under the MIT License; see the LICENSE file.
|
|
10
|
+
# SPDX-License-Identifier: MIT
|
|
11
|
+
#
|
|
12
|
+
## end license ##
|
|
13
|
+
|
|
14
|
+
"""CQL (Contextual Query Language, https://www.loc.gov/standards/sru/cql/) for sil.
|
|
15
|
+
|
|
16
|
+
parse() gives a tree of SearchClause and Boolean; Index.cql_query() turns a tree or a
|
|
17
|
+
CQL string into a sil query. It follows what meresco (cqlparser and meresco-lucene)
|
|
18
|
+
did, so CQL that worked there gives the same hits here:
|
|
19
|
+
|
|
20
|
+
- OR binds weakest; AND and NOT bind stronger, left to right: "a OR b AND c" is
|
|
21
|
+
"a OR (b AND c)", "a AND b OR c" is "(a AND b) OR c". (The CQL standard gives all
|
|
22
|
+
booleans the same precedence; cqlparser did not.)
|
|
23
|
+
- "a NOT b" is a and not b.
|
|
24
|
+
- relations: "=", "==", "exact", "<", "<=", ">", ">="; the modifier "/boost=2" on a
|
|
25
|
+
relation. Other relations, modifiers and prefix assignments raise CqlError.
|
|
26
|
+
- A term in a text field (and a term without index, in the unqualified field) is
|
|
27
|
+
analysed as the field is indexed: one word is a term query, more words a phrase,
|
|
28
|
+
"word*" (at least two letters, digits, "_" or "-") a prefix. A term without words
|
|
29
|
+
(e.g. "*" in a text field) is left out of the query. "*" without index is
|
|
30
|
+
everything.
|
|
31
|
+
- "exact" and "==" (and "=" on an untokenized field) look for the term as it is, not
|
|
32
|
+
analysed. On a hierarchical field "a>b" is a path.
|
|
33
|
+
- "<", "<=", ">", ">=" are ranges on int fields only.
|
|
34
|
+
- An index that is not in the profile matches nothing (as Lucene did).
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
import re
|
|
38
|
+
from dataclasses import dataclass, replace
|
|
39
|
+
|
|
40
|
+
import tantivy
|
|
41
|
+
|
|
42
|
+
from .indexfield import INT, TEXT
|
|
43
|
+
|
|
44
|
+
COMPARATORS = ("=", "==", "exact", "<", "<=", ">", ">=")
|
|
45
|
+
# comparators CQL has but sil does not: an error, not a search for their name
|
|
46
|
+
UNSUPPORTED_COMPARATORS = ("<>", "any", "all", "adj", "within", "encloses")
|
|
47
|
+
RANGES = {"<", "<=", ">", ">="}
|
|
48
|
+
EXACT = {"==", "exact"}
|
|
49
|
+
|
|
50
|
+
# as cqlparser's tokenizer: symbols, a quoted string (\" inside), or a word
|
|
51
|
+
_TOKEN = re.compile(r'(?s)\s*(\(|\)|>=|<>|<=|==|>|<|=|/|".*?(?<!\\)"|[^"()>=<\s/]+)')
|
|
52
|
+
_SYMBOLS = {"(", ")", ">=", "<>", "<=", "==", ">", "<", "=", "/"}
|
|
53
|
+
# meresco-lucene made "pr*" into a prefix query only for this form
|
|
54
|
+
_PREFIX = re.compile(r"^([\w-]{2,})\*$")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class CqlError(ValueError):
|
|
58
|
+
"""CQL that can not be parsed, or that sil does not support."""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@dataclass(frozen=True)
|
|
62
|
+
class SearchClause:
|
|
63
|
+
"""A term, or index relation term: 'fiets', 'title = fiets'."""
|
|
64
|
+
|
|
65
|
+
term: str
|
|
66
|
+
index: str | None = None
|
|
67
|
+
relation: str | None = None
|
|
68
|
+
boost: float | None = None
|
|
69
|
+
|
|
70
|
+
def __str__(self):
|
|
71
|
+
term = _quoted(self.term)
|
|
72
|
+
if self.index is None:
|
|
73
|
+
return term
|
|
74
|
+
boost = "" if self.boost is None else f"/boost={self.boost:g}"
|
|
75
|
+
return f"{_quoted(self.index)} {self.relation}{boost} {term}"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class Boolean:
|
|
80
|
+
"""left operator right; operator is "and", "or" or "not"."""
|
|
81
|
+
|
|
82
|
+
operator: str
|
|
83
|
+
left: "SearchClause | Boolean"
|
|
84
|
+
right: "SearchClause | Boolean"
|
|
85
|
+
|
|
86
|
+
def __str__(self):
|
|
87
|
+
def side(node):
|
|
88
|
+
return f"({node})" if isinstance(node, Boolean) else str(node)
|
|
89
|
+
|
|
90
|
+
return f"{side(self.left)} {self.operator.upper()} {side(self.right)}"
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def parse(text):
|
|
94
|
+
"""The tree of a CQL string. Raises CqlError."""
|
|
95
|
+
return _Parser(_tokenize(text)).parse()
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def rewrite(node, function):
|
|
99
|
+
"""The tree with every SearchClause replaced by function(clause), which returns a
|
|
100
|
+
SearchClause (dataclasses.replace(clause, index=...)) or a Boolean."""
|
|
101
|
+
if isinstance(node, Boolean):
|
|
102
|
+
return replace(
|
|
103
|
+
node, left=rewrite(node.left, function), right=rewrite(node.right, function)
|
|
104
|
+
)
|
|
105
|
+
return function(node)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def to_cql(node):
|
|
109
|
+
"""The tree as a CQL string again."""
|
|
110
|
+
return str(node)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _kind(node):
|
|
114
|
+
return "or" if node.operator == "or" else "and"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _quoted(text):
|
|
118
|
+
if (
|
|
119
|
+
text
|
|
120
|
+
and not re.search(r'[\s"()>=</]', text)
|
|
121
|
+
and text.lower()
|
|
122
|
+
not in (
|
|
123
|
+
"and",
|
|
124
|
+
"or",
|
|
125
|
+
"not",
|
|
126
|
+
"prox",
|
|
127
|
+
)
|
|
128
|
+
):
|
|
129
|
+
return text
|
|
130
|
+
return '"' + text.replace('"', r"\"") + '"'
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _tokenize(text):
|
|
134
|
+
tokens = _TOKEN.findall(text)
|
|
135
|
+
if re.sub(r"\s+", "", "".join(tokens)) != re.sub(r"\s+", "", text):
|
|
136
|
+
raise CqlError(f"Unrecognized token in {text!r}")
|
|
137
|
+
return tokens
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class _Parser:
|
|
141
|
+
def __init__(self, tokens):
|
|
142
|
+
self._tokens = tokens
|
|
143
|
+
self._pos = 0
|
|
144
|
+
|
|
145
|
+
def parse(self):
|
|
146
|
+
if not self._tokens:
|
|
147
|
+
raise CqlError("No tokens found, at least one token expected.")
|
|
148
|
+
if self._tokens[0] == ">":
|
|
149
|
+
raise CqlError("Unsupported CQL: prefix assignment (>)")
|
|
150
|
+
tree = self._or()
|
|
151
|
+
if self._pos < len(self._tokens):
|
|
152
|
+
raise CqlError(f"Unexpected token: {self._tokens[self._pos]!r}")
|
|
153
|
+
return tree
|
|
154
|
+
|
|
155
|
+
def _peek(self, offset=0):
|
|
156
|
+
pos = self._pos + offset
|
|
157
|
+
return self._tokens[pos] if pos < len(self._tokens) else None
|
|
158
|
+
|
|
159
|
+
def _next(self):
|
|
160
|
+
token = self._peek()
|
|
161
|
+
if token is None:
|
|
162
|
+
raise CqlError("Unexpected end of query")
|
|
163
|
+
self._pos += 1
|
|
164
|
+
return token
|
|
165
|
+
|
|
166
|
+
def _boolean(self):
|
|
167
|
+
token = self._peek()
|
|
168
|
+
if token is None:
|
|
169
|
+
return None
|
|
170
|
+
if token.lower() == "prox":
|
|
171
|
+
raise CqlError("Unsupported CQL: prox")
|
|
172
|
+
if token.lower() in ("and", "or", "not"):
|
|
173
|
+
if self._peek(1) == "/":
|
|
174
|
+
raise CqlError("Unsupported CQL: modifiers on a boolean")
|
|
175
|
+
return token.lower()
|
|
176
|
+
return None
|
|
177
|
+
|
|
178
|
+
def _or(self):
|
|
179
|
+
left = self._and()
|
|
180
|
+
if self._boolean() == "or":
|
|
181
|
+
self._pos += 1
|
|
182
|
+
return Boolean("or", left, self._or())
|
|
183
|
+
return left
|
|
184
|
+
|
|
185
|
+
def _and(self):
|
|
186
|
+
left = self._clause()
|
|
187
|
+
while (operator := self._boolean()) in ("and", "not"):
|
|
188
|
+
self._pos += 1
|
|
189
|
+
left = Boolean(operator, left, self._clause())
|
|
190
|
+
return left
|
|
191
|
+
|
|
192
|
+
def _clause(self):
|
|
193
|
+
if self._peek() == "(":
|
|
194
|
+
self._pos += 1
|
|
195
|
+
tree = self._or()
|
|
196
|
+
if self._next() != ")":
|
|
197
|
+
raise CqlError("Missing )")
|
|
198
|
+
return tree
|
|
199
|
+
following = self._peek(1)
|
|
200
|
+
if following in COMPARATORS or following in UNSUPPORTED_COMPARATORS:
|
|
201
|
+
index = self._term()
|
|
202
|
+
relation = self._next()
|
|
203
|
+
if relation in UNSUPPORTED_COMPARATORS:
|
|
204
|
+
raise CqlError(f"Unsupported comparator: {relation}")
|
|
205
|
+
boost = self._boost()
|
|
206
|
+
return SearchClause(self._term(), index, relation, boost)
|
|
207
|
+
return SearchClause(self._term())
|
|
208
|
+
|
|
209
|
+
def _boost(self):
|
|
210
|
+
if self._peek() != "/":
|
|
211
|
+
return None
|
|
212
|
+
self._pos += 1
|
|
213
|
+
name = self._next()
|
|
214
|
+
if name != "boost" or self._next() != "=":
|
|
215
|
+
raise CqlError(f"Unsupported modifier: {name}")
|
|
216
|
+
value = self._term()
|
|
217
|
+
try:
|
|
218
|
+
return float(value)
|
|
219
|
+
except ValueError:
|
|
220
|
+
raise CqlError(f"Not a number for boost: {value!r}") from None
|
|
221
|
+
|
|
222
|
+
def _term(self):
|
|
223
|
+
token = self._next()
|
|
224
|
+
if token.startswith('"'):
|
|
225
|
+
return token[1:-1].replace(r"\"", '"')
|
|
226
|
+
if token in _SYMBOLS:
|
|
227
|
+
raise CqlError(f"Unexpected token: {token!r}")
|
|
228
|
+
return token
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
class Translator:
|
|
232
|
+
"""A CQL tree as a tantivy query for an index (used by Index.cql_query)."""
|
|
233
|
+
|
|
234
|
+
_OCCUR = {"and": tantivy.Occur.Must, "or": tantivy.Occur.Should}
|
|
235
|
+
|
|
236
|
+
def __init__(self, index):
|
|
237
|
+
self._index = index
|
|
238
|
+
self._schema = index._schema
|
|
239
|
+
self._profile = index._profile
|
|
240
|
+
|
|
241
|
+
def query(self, tree):
|
|
242
|
+
"""(tantivy query, constant score)"""
|
|
243
|
+
translated = self._node(tree)
|
|
244
|
+
if translated is None:
|
|
245
|
+
# meresco: an empty BooleanQuery, which matches nothing
|
|
246
|
+
return tantivy.Query.empty_query(), True
|
|
247
|
+
return translated
|
|
248
|
+
|
|
249
|
+
def _node(self, node):
|
|
250
|
+
if isinstance(node, Boolean):
|
|
251
|
+
return self._boolean(node)
|
|
252
|
+
query = self._clause(node)
|
|
253
|
+
if query is not None and node.boost is not None:
|
|
254
|
+
return tantivy.Query.boost_query(query[0], node.boost), False
|
|
255
|
+
return query
|
|
256
|
+
|
|
257
|
+
def _operands(self, node, kind):
|
|
258
|
+
"""[(occur, node)] of a run of ORs, or of ANDs and NOTs, flattened as
|
|
259
|
+
cqlparser's cqltoexpression did; the right side of a NOT is one operand."""
|
|
260
|
+
if isinstance(node, Boolean) and _kind(node) == kind:
|
|
261
|
+
operands = self._operands(node.left, kind)
|
|
262
|
+
if node.operator == "not":
|
|
263
|
+
operands.append((tantivy.Occur.MustNot, node.right))
|
|
264
|
+
else:
|
|
265
|
+
operands.extend(self._operands(node.right, kind))
|
|
266
|
+
return operands
|
|
267
|
+
return [(self._OCCUR[kind], node)]
|
|
268
|
+
|
|
269
|
+
def _boolean(self, node):
|
|
270
|
+
clauses = []
|
|
271
|
+
constant = True
|
|
272
|
+
for occur, operand in self._operands(node, _kind(node)):
|
|
273
|
+
translated = self._node(operand)
|
|
274
|
+
if translated is None:
|
|
275
|
+
# as meresco-lucene: an empty query is left out
|
|
276
|
+
continue
|
|
277
|
+
query, operand_constant = translated
|
|
278
|
+
clauses.append((occur, query))
|
|
279
|
+
constant = constant and operand_constant
|
|
280
|
+
if not clauses:
|
|
281
|
+
return None
|
|
282
|
+
return tantivy.Query.boolean_query(clauses), constant
|
|
283
|
+
|
|
284
|
+
def _clause(self, clause):
|
|
285
|
+
if clause.index is None:
|
|
286
|
+
if clause.term == "*":
|
|
287
|
+
return tantivy.Query.all_query(), True
|
|
288
|
+
field = self._profile.unqualified
|
|
289
|
+
if field is None:
|
|
290
|
+
return None
|
|
291
|
+
return self._analysed(field, clause.term)
|
|
292
|
+
|
|
293
|
+
field = self._profile.get(clause.index)
|
|
294
|
+
if field is None or field.is_unqualified and clause.relation in RANGES:
|
|
295
|
+
return tantivy.Query.empty_query(), True
|
|
296
|
+
|
|
297
|
+
if clause.relation in RANGES:
|
|
298
|
+
return self._range(field, clause)
|
|
299
|
+
if field.field_type == INT:
|
|
300
|
+
return self._term_query(field, clause.term)
|
|
301
|
+
if clause.relation in EXACT or field.field_type != TEXT:
|
|
302
|
+
return self._term_query(field, clause.term)
|
|
303
|
+
return self._analysed(field, clause.term)
|
|
304
|
+
|
|
305
|
+
def _term_query(self, field, value):
|
|
306
|
+
try:
|
|
307
|
+
query = self._index.term_query(field.name, value)
|
|
308
|
+
except ValueError:
|
|
309
|
+
raise CqlError(f"Not a number for {field.name}: {value!r}") from None
|
|
310
|
+
return query.query, query.constant_score
|
|
311
|
+
|
|
312
|
+
def _analysed(self, field, term):
|
|
313
|
+
name = field.name
|
|
314
|
+
words = field.analyzer.analyze(term)
|
|
315
|
+
if not words:
|
|
316
|
+
return None
|
|
317
|
+
if len(words) == 1:
|
|
318
|
+
if _PREFIX.match(term):
|
|
319
|
+
pattern = re.escape(words[0]) + ".*"
|
|
320
|
+
return tantivy.Query.regex_query(self._schema, name, pattern), True
|
|
321
|
+
return tantivy.Query.term_query(self._schema, name, words[0]), False
|
|
322
|
+
return tantivy.Query.phrase_query(self._schema, name, words), False
|
|
323
|
+
|
|
324
|
+
def _range(self, field, clause):
|
|
325
|
+
if field.field_type != INT:
|
|
326
|
+
raise CqlError(f"{clause.relation} is only supported on int fields")
|
|
327
|
+
try:
|
|
328
|
+
value = int(clause.term)
|
|
329
|
+
except ValueError:
|
|
330
|
+
raise CqlError(f"Not a number for {field.name}: {clause.term!r}") from None
|
|
331
|
+
lower = value if ">" in clause.relation else None
|
|
332
|
+
upper = value if "<" in clause.relation else None
|
|
333
|
+
query = tantivy.Query.range_query(
|
|
334
|
+
self._schema,
|
|
335
|
+
field.name,
|
|
336
|
+
tantivy.FieldType.Integer,
|
|
337
|
+
lower,
|
|
338
|
+
upper,
|
|
339
|
+
include_lower=clause.relation == ">=" or lower is None,
|
|
340
|
+
include_upper=clause.relation == "<=" or upper is None,
|
|
341
|
+
)
|
|
342
|
+
return query, True
|