Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/modules/ROOT/nav.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
** xref:how-to/dataframes-and-columns.adoc[DataFrames, Arrow and columns]
** xref:how-to/functions-and-events.adoc[Python functions and record events]
** xref:how-to/vectors.adoc[Vectors]
** xref:how-to/full-text-search.adoc[Full-text search]
** xref:how-to/agent-memory.adoc[Agent memory]
** xref:how-to/columnar-index.adoc[The COLUMNAR index and its settings]
** xref:how-to/facets.adoc[Faceted queries]
Expand Down
220 changes: 220 additions & 0 deletions docs/modules/ROOT/pages/how-to/full-text-search.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
= Full-text search
:description: Index a text property with FULL_TEXT, search it with SEARCH_INDEX, SEARCH_FIELDS, CONTAINSTEXT or openCypher, choose an analyzer, and fuse the result with a vector search, from Python on both packages.

// Sources: ArcadeDB 26.11.1 and later: the FULL_TEXT index (BM25), SEARCH_INDEX, SEARCH_FIELDS, CONTAINSTEXT, db.index.fulltext.queryNodes and vector.fuse. Every block on this page is run by tests/test_docs_full_text_page.py, which runs on arcadedb-jvm and on the native arcadedb. examples/29_hybrid_memory_retrieval.py is the hybrid search with a tenant filter and graph hops.

A `FULL_TEXT` index splits a text property into terms and ranks the records that hold the terms of a query with BM25. The search belongs to the engine, and it is a statement like any other, so it composes with `WHERE`, `ORDER BY`, projections and graph traversal. This page shows the statements from Python, the forms that return the same records, what an analyzer changes, and how to put a vector search next to a text search.

The blocks on this page run one after the other against one empty database, and a test in the repository runs them that way (`tests/test_docs_full_text_page.py`). Each block that prints something is followed by its output. Every block assumes that `db` is an open database, as on xref:how-to/databases-and-queries.adoc[Databases and queries].

== The data

Five short notes. `body` is the text, and `vec` is a two-number vector for the hybrid search at the end of the page.

[source,python]
----
notes = {
"a": ("the cat sat on the mat", [1.0, 0.0]),
"b": ("a dog chased the cat around the garden", [0.9, 0.1]),
"c": ("stock markets fell on tuesday", [0.0, 1.0]),
"d": ("the cat and the dog are friends", [0.5, 0.5]),
"e": ("cats are running", [0.1, 0.9]),
}

db.command("sql", "CREATE DOCUMENT TYPE Note")
db.command("sql", "CREATE PROPERTY Note.key STRING")
db.command("sql", "CREATE PROPERTY Note.body STRING")
db.command("sql", "CREATE PROPERTY Note.vec ARRAY_OF_FLOATS")
db.command("sql", "CREATE INDEX ON Note (body) FULL_TEXT")
db.command(
"sql",
"CREATE INDEX ON Note (vec) LSM_VECTOR "
"METADATA {dimensions: 2, similarity: 'COSINE'}",
)

with db.transaction():
for key, (body, vec) in notes.items():
db.command(
"sql",
"INSERT INTO Note SET key = :key, body = :body, vec = :vec",
{"key": key, "body": body, "vec": vec},
)
----

The index is named `Note[body]`. A search names it, or names the property.

== Search and rank

`SEARCH_INDEX` takes the name of the index and the query text, and `$score` is the BM25 score of the record. Order by it, and the best match comes first.

[source,python]
----
rows = db.query(
"sql",
"SELECT key FROM Note WHERE SEARCH_INDEX('Note[body]', :q) = true "
"ORDER BY $score DESC",
{"q": "cat dog"},
).to_list()
print([row["key"] for row in rows])
----

The note with both words and the shortest text comes first, and the note with only one of the words comes last.

[source,text]
----
['d', 'b', 'a']
----

A query that holds several terms finds a record that has any of them. The query text takes the Lucene syntax: `AND`, a `-` before a term to leave it out, and a phrase in quotes.

[source,python]
----
for text in ["cat AND dog", "cat -dog", '"sat on the mat"']:
rows = db.query(
"sql",
"SELECT key FROM Note WHERE SEARCH_INDEX('Note[body]', :q) = true "
"ORDER BY key",
{"q": text},
).to_list()
print(text, [row["key"] for row in rows])
----

The last query is a phrase in quotes, and it finds note `a`. Whether a phrase also checks the order of its terms depends on the engine version, so do not rely on the order.

[source,text]
----
cat AND dog ['b', 'd']
cat -dog ['a']
"sat on the mat" ['a']
----

== Other ways to ask the same

`SEARCH_FIELDS` names the properties and not the index, and `CONTAINSTEXT` is an operator on one property. They find the same records as `SEARCH_INDEX` for a single term. openCypher has the procedure `db.index.fulltext.queryNodes`, which returns each record as `node` with its `score`.

[source,python]
----
def keys(language, statement):
return sorted(row["key"] for row in db.query(language, statement).to_list())


print(
keys("sql", "SELECT key FROM Note WHERE SEARCH_FIELDS(['body'], 'cat') = true")
)
print(keys("sql", "SELECT key FROM Note WHERE body CONTAINSTEXT 'cat'"))
print(
keys(
"opencypher",
"CALL db.index.fulltext.queryNodes('Note[body]', 'cat') "
"YIELD node RETURN node.key AS key",
)
)
----

[source,text]
----
['a', 'b', 'd']
['a', 'b', 'd']
['a', 'b', 'd']
----

Use `SEARCH_INDEX` when you want the ranking in SQL: it names the index, and `$score` ranks its matches.

== A write is visible to the next search

A record is searchable after its commit, in the same process, with no refresh step. The first search below finds nothing, and the second finds the record that was written between them.

[source,python]
----
sql = "SELECT key FROM Note WHERE SEARCH_INDEX('Note[body]', 'garden party') = true"
print(keys("sql", sql))

with db.transaction():
db.command(
"sql", "INSERT INTO Note SET key = 'f', body = 'garden party', vec = [0.2, 0.2]"
)
print(keys("sql", sql))
----

`garden party` also finds note `b`, which holds `garden`, so the first search is not empty. The second one adds `f`.

[source,text]
----
['b']
['b', 'f']
----

== Choose an analyzer

The default analyzer does not stem: `running` is not `run`. An index takes another Lucene analyzer by its class name in `METADATA`. This one stems English words.

[source,python]
----
db.command("sql", "CREATE DOCUMENT TYPE Memo")
db.command("sql", "CREATE PROPERTY Memo.body STRING")
db.command(
"sql",
"CREATE INDEX ON Memo (body) FULL_TEXT "
'METADATA {"analyzer": "org.apache.lucene.analysis.en.EnglishAnalyzer"}',
)
with db.transaction():
db.command("sql", "INSERT INTO Memo SET body = 'cats are running'")

for name, query in [("Note", "run"), ("Memo", "run")]:
count = db.query(
"sql",
f"SELECT count(*) AS n FROM {name} "
f"WHERE SEARCH_INDEX('{name}[body]', :q) = true",
{"q": query},
).first().get("n")
print(name, count)
----

`Note` has the default analyzer and finds nothing for `run`. `Memo` has the English analyzer and finds the note with `running`.

[source,text]
----
Note 0
Memo 1
----

The analyzer is part of the index and applies to the text of a record and to a query alike, so a change of analyzer needs a new index. Set it before the load.

== Put a vector search next to it

`vector.fuse` merges ranked lists into one. Here the nearest notes to a query vector and the best text matches for a query go in, and reciprocal rank fusion (`RRF`) returns one list. A note that both lists rank high comes first. The vector search is approximate, so the lower ranks can change places between runs and engine builds. Rely on the top of the list.

[source,python]
----
rows = db.query(
"sql",
"""
SELECT record.key AS key FROM (
SELECT expand(`vector.fuse`(
`vector.neighbors`('Note[vec]', :qvec, 3),
(SELECT @rid, $score FROM Note
WHERE SEARCH_INDEX('Note[body]', :q) = true
ORDER BY $score DESC LIMIT 3),
{ fusion: 'RRF' }
))
) ORDER BY score DESC LIMIT 2
""",
{"qvec": [1.0, 0.0], "q": "cat"},
).to_list()
print([row["key"] for row in rows])
----

Note `a` is the nearest vector to the query and matches `cat`, and `b` is next on both lists, so they lead the fused list.

[source,text]
----
['a', 'b']
----

Give the vector as a list next to another parameter, or by name, as here. `examples/29_hybrid_memory_retrieval.py` adds a filter by tenant on both sides and hops through the graph from every fused record. The vector side is on xref:how-to/vectors.adoc[Vectors] and xref:how-to/agent-memory.adoc[Agent memory].

== What to know

* A query reads the postings of every term it holds, so its time grows with the number of records that hold those terms. It is not a reason to avoid the index. When the text is large, an analyzer that drops stop words keeps the words that match nearly every record out of the index. The engine side of this is tracked in https://github.com/ArcadeData/arcadedb/issues/13912[ArcadeData/arcadedb#13912].
* A phrase may match its terms in any order on some engine versions, because the index keeps no term positions there. Test the engine you run before you depend on the order.
* The PostgreSQL text-search forms (`to_tsvector`, `@@`, `ts_rank`) and the Cypher 25 `SEARCH` clause have no full-text form on engine 26.11.1. Use the statements on this page.
61 changes: 61 additions & 0 deletions tests/test_docs_full_text_page.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Every Python block of the Antora page ``docs/modules/ROOT/pages/how-to/full-text-search.adoc`` runs, and prints what the page says.

The blocks of the page are chained on purpose: they run in the order of the page, in one namespace, against one fresh
temporary database that the namespace holds as ``db`` (the page says that each block assumes an open ``db``). A block that
is followed by a ``[source,text]`` block must print exactly that text. The test uses no Java object, so it runs on the JVM
build and the native build alike, on every engine from 26.11.1.
"""

import contextlib
import io
import re
from pathlib import Path

PAGE = (
Path(__file__).resolve().parents[1]
/ "docs"
/ "modules"
/ "ROOT"
/ "pages"
/ "how-to"
/ "full-text-search.adoc"
)

# a Python listing, then (optionally, after one line of prose) the text listing with its output
BLOCK_RE = re.compile(
r"\[source,python[^\]\n]*\]\n----\n(?P<code>.*?)\n----\n"
r"(?:\n[^\[\n][^\n]*\n)?" # one line of prose between the listings
r"(?:\n\[source,text\]\n----\n(?P<out>.*?)\n----\n)?",
re.DOTALL,
)


def _blocks():
text = PAGE.read_text(encoding="utf-8")
found = [(m.group("code"), m.group("out")) for m in BLOCK_RE.finditer(text)]
# no Python listing may escape the extraction (a different spelling of the block header would run nowhere)
assert text.count("[source,python") == len(found)
return found


def test_the_page_has_its_blocks():
blocks = _blocks()
assert len(blocks) == 7
assert sum(1 for _, out in blocks if out is not None) == 6


def test_every_block_runs_in_order_and_prints_what_the_page_says(temp_db):
namespace = {"db": temp_db, "__name__": "full_text_page"}
for number, (code, expected) in enumerate(_blocks(), start=1):
captured = io.StringIO()
compiled = compile(code, f"full-text-search.adoc python block {number}", "exec")
with contextlib.redirect_stdout(captured):
exec(compiled, namespace) # nosec B102 - the page of this repository
if expected is not None:
assert (
captured.getvalue().strip() == expected.strip()
), f"block {number} printed other text than the page shows:\n{code}"
else:
assert (
captured.getvalue() == ""
), f"block {number} prints, the page shows no output"
Loading