Text Search Best Practice

This page is a guide to getting dependable results from Waratah’s optional full-text index: what to settle before the first load, which query form to reach for, the shapes that fail, and what to check when a search comes back empty. Every example runs on the small dataset in Example setup, and every answer shown is what that dataset returns.

The Text Search page describes the feature itself. Configuration has the text.toml reference.

The short version

  • List the predicates you search in text.toml. With no predicates key the index holds only a built-in list of common text predicates, and text:query finds nothing outside it.

  • Enable the plugin for every command that loads data — import as well as start — or rows are loaded that text search can never find. The simplest way is one text.toml with enabled = true and the same --config-dir everywhere.

  • Pick the analyzer before the first load. Changing it later is a full rebuild.

  • When you only need the matching resources, use the subject form, text:query(?subject, <predicate>, "…"), and bind the subject with a triple pattern in the same group.

  • text:query works only as a plain, top-level FILTER conjunct. Use UNION for alternatives and FILTER NOT EXISTS for exclusion.

  • Operators in the search string are uppercase, a term is excluded with a leading minus sign, and there is no wildcard.

  • Language tags match exactly and are written in lowercase (lang:en-us).

  • After changing analyzer, seed_chars, or predicates, stop the store and run waratah text rebuild-index.

Decide what the index holds before the first load

The index does not hold every string literal. It holds literals under the predicates named in text.toml, and three settings choose that list:

  • No predicates key (the default): a built-in list of common text predicates applies. It covers rdfs:label and rdfs:comment, the SKOS label and definition predicates, dcterms:title, dcterms:description, dcterms:abstract, and dcterms:subject, several Schema.org text predicates, dcat:keyword, and the FOAF name predicates. The full list is in Configuration.

  • predicates = []: every string-literal predicate is indexed.

  • A list of IRIs: exactly those predicates are indexed. A list replaces the built-in one; it does not extend it.

The list is part of the index’s identity and takes effect only after a rebuild, so decide it up front. A workable rule is to list the predicates your queries actually search — labels, names, titles, abstracts — and to leave identifiers, URLs, and dates out. A narrower index is smaller, and a search for a common word does not drag in a vocabulary nobody meant to search.

The list decides what both forms of text:query can find:

  • The literal form, text:query(?value, "…"), finds only literals the index holds. A literal under a predicate outside the list is not found: the query returns no rows and raises no error.

  • The subject form, text:query(?subject, <predicate>, "…"), fails with a query error when a named predicate is not in the list.

STRSTARTS, STRENDS, and anchored REGEX keep their exact answers in every case. Outside the list they run without the index.

Data that uses the built-in predicates needs no predicates key. A store holding rdfs:label triples is searchable as soon as the plugin is enabled.

Example setup

The examples use a small catalogue. One book lives in a named graph, so the file is TriG: save it as books.trig.

@prefix ex:   <http://example.org/> .
@prefix base: <http://example.org/graphs/> .

ex:book1 a ex:Book ;
    ex:title "The Laser Printer Handbook" ;
    ex:abstract "A practical guide to laser printers, toner, and maintenance."@en ;
    ex:author ex:ada .

ex:book2 a ex:Book ;
    ex:title "Inkjet Printing at Home" ;
    ex:abstract "Choosing and running an inkjet printer on a budget."@en ;
    ex:author ex:ada .

ex:book3 a ex:Book ;
    ex:title "Laser Physics" ;
    ex:abstract "How stimulated emission produces coherent light."@en ;
    ex:author ex:bruno .

ex:ada ex:name "Ada Bell" .
ex:bruno ex:name "Bruno Costa" .

base:archive {
    ex:book4 a ex:Book ;
        ex:title "Le Tonner Moderne"@fr ;
        ex:abstract "Un guide des imprimantes laser."@fr ;
        ex:author ex:bruno .
}

None of the catalogue’s three text predicates is in the built-in list, so the examples list them. Save this as config/text.toml:

enabled = true
predicates = [
  "http://example.org/title",
  "http://example.org/abstract",
  "http://example.org/name",
]

Load the catalogue and open the store, giving both commands the same configuration directory. With enabled = true in the file, the --with-text flag is not needed.

waratah import books.trig --data-dir ./waratah-data --offline --config-dir ./config
waratah standalone --data-dir ./waratah-data --config-dir ./config

To use a separate cluster instead of the single-process standalone, start it with waratah start --data-dir ./waratah-data --config-dir ./config and load with waratah import books.trig --connect --config-dir ./config.

Check the index before running any query:

waratah text status --data-dir ./waratah-data --config-dir ./config
text: config ./config/text.toml
text: ./waratah-data/main/o-text-index: analyzer simple, seed_chars 16, fingerprint text-index-v2;analyzer=simple;seed_chars=16;predicates=http://example.org/abstract,http://example.org/name,http://example.org/title, epoch Some(1795870566581), trusted true
text: predicates: 3 configured
text:   http://example.org/abstract
text:   http://example.org/name
text:   http://example.org/title
text: live documents: 10

trusted true means the server can answer text:query from this index. The ten documents are four titles, four abstracts, and two names: the index keeps one document per predicate and literal pair.

Load the same file with a text.toml that has no predicates key, and waratah text status reports live documents: 0. The index is built and trusted, but it holds none of the catalogue. The literal form returns no rows without an error, and the subject form fails with text:query names <http://example.org/title>, which is not an indexed text predicate. An index that holds nothing is the first thing to rule out when a search returns nothing.

Turn the plugin on for every command that loads data

A command that loads data writes the text documents for the rows it loads, and only when the text plugin is enabled for that command. Each waratah import therefore needs the plugin too: pass --with-text, or give it a --config-dir whose text.toml says enabled = true. The flag turns the plugin on; it never turns off a file that says enabled = true.

What goes wrong when an import runs without the plugin depends on the order:

  • Rows loaded with the plugin off, then the store opened with it on: the server finds no build stamp, builds the index over the whole store before it answers the first query, and everything works.

  • An index already built and trusted, then an import with the plugin off: the rows load, but no documents are written for them. waratah text status still reports trusted true, and text:query does not find the new rows, while ordinary triple patterns and CONTAINS do. A restart does not help; only waratah text rebuild-index repairs the index.

The simplest safe arrangement is the one the examples use: one text.toml with enabled = true, and the same --config-dir on every start, standalone, and import.

Choose the analyzer once

analyzer in text.toml decides how text:query matches words. It is part of the index’s identity, so changing it after the first load is a full rebuild. Three analyzers are available:

Setting A term matches Suits

simple (default)

Whole words, ignoring case. run matches Run but not running.

Data where an exact word is the intent: codes, keywords, names.

en_stem

Whole words, ignoring case, reduced to an English stem. run also matches running, and guides matches guide.

English prose such as titles and abstracts.

whitespace

Words split only on whitespace, ignoring case; punctuation stays attached. printers does not match printers,.

Text where punctuation belongs to a token: tags, identifiers.

On the catalogue’s abstracts the difference is direct:

  • A search for run finds the abstract of ex:book2 with en_stem and nothing with the other two.

  • A search for guides finds the abstract of ex:book1 with en_stem and nothing with the other two.

  • A search for printers finds that abstract with simple and en_stem, and nothing with whitespace, because the stored word is printers,.

  • A search for laser finds it with all three.

Two things stay the same whatever the analyzer:

  • The search string is lowercased with the text, so LASER finds Laser.

  • Stemming is not prefix matching. print matches neither printer nor printers, even with en_stem. For a prefix, use STRSTARTS.

Prefer the subject form when you need the resources

The two forms of text:query answer different questions.

The literal form takes the value and keeps the rows whose value matches. Use it when the matched text is part of the result:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?title WHERE {
  ?book ex:title ?title .
  FILTER(text:query(?title, "laser"))
}

Answers: The Laser Printer Handbook and Laser Physics.

The subject form names the predicates and returns the subjects whose property matches. Use it when you need to know which resources match:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book WHERE {
  ?book a ex:Book .
  FILTER(text:query(?book, ex:title, "laser"))
}

Answers: ex:book1 and ex:book3. Bind the subject with a triple pattern in the same group, as ?book a ex:Book does here, and leave the searched predicate out of the pattern: it appears only inside text:query.

The subject form has three advantages over a plain filter:

  • One index search covers every named predicate. Name several to search them together: text:query(?book, ex:title, ex:abstract, "inkjet") answers ex:book2, whose title and abstract both match.

  • A subject with several matching values appears once.

  • The matched values are not read back from storage; only the subjects are.

The second matters for counts. Searching ex:title and ex:abstract together, text:query(?book, ex:title, ex:abstract, "laser") answers ex:book1 once and ex:book3 once. The plain filter below answers ex:book1 twice, which skews any count or aggregate built on it:

PREFIX ex: <http://example.org/>

SELECT ?book WHERE {
  ?book a ex:Book .
  ?book ex:title|ex:abstract ?value .
  FILTER(CONTAINS(LCASE(?value), "laser"))
}

Write the search string

The second argument of text:query is a search expression over the indexed words, not a SPARQL expression. The search string must be a plain string literal — not language-tagged, not a number — and must not be empty. After it, the only further argument is a language restriction.

These forms work. Each searches the catalogue’s abstracts with the default simple analyzer:

# Any of the words (book1, book2) — the default for a list of words
FILTER(text:query(?abstract, "laser printer"))

# All of the words (book1)
FILTER(text:query(?abstract, "guide AND laser"))

# Grouped with parentheses (book1)
FILTER(text:query(?abstract, "guide AND (laser OR emission)"))

# Two adjacent words, in quotes (book1)
FILTER(text:query(?abstract, "\"practical guide\""))

# One word without another (book1)
FILTER(text:query(?abstract, "+laser -physics"))

Five habits avoid the common surprises, each observed on the same abstracts:

Avoid What happens instead Do this

Lower-case operators: and, or, not

They are searched as ordinary words, so laser and not physics also matches ex:book2.

Write operators in upper case.

AND NOT

laser AND NOT physics returns no rows at all.

Put a minus sign on the excluded word.

A query made only of exclusions

It is a query error (Only excluding terms given).

Include at least one word to match.

A trailing asterisk as a wildcard

las followed by one matches nothing.

Use STRSTARTS for a prefix.

A field prefix such as abstract:laser

It is a query error (Field does not exist).

Leave the field out.

Restrict a search to a language

A third argument, lang:xx, limits the search to literals carrying that language tag. Write it as a string:

PREFIX ex: <http://example.org/>
PREFIX base: <http://example.org/graphs/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?abstract WHERE {
  GRAPH base:archive {
    ?book ex:abstract ?abstract .
    FILTER(text:query(?abstract, "laser", "lang:fr"))
  }
}

Answers: Un guide des imprimantes laser., with its @fr tag. The GRAPH clause matters: that abstract lives in the base:archive graph, so the same search over the default graph finds nothing.

Tags are compared exactly, and the store keeps them in lower case, so write the tag in lower case. For four ex:title values Laser Tag, tagged @en-US, @en, and @en-GB, and one left untagged:

Search string Finds

laser

All four values.

laser with lang:en

Only the @en value. lang:en does not match @en-US.

laser with lang:en-us

Only the @en-US value.

laser with lang:en-gb

Only the @en-GB value.

laser with lang:_none

Only the untagged value.

laser with lang:en-US

Nothing: the tag is stored as en-us.

Mind the graph scope

A text search sees exactly the graphs the rest of the query sees. A bare pattern reads the default graph, so the French book in base:archive is invisible to this search even though its title matches:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book WHERE {
  ?book a ex:Book .
  FILTER(text:query(?book, ex:title, "tonner"))
}

Answers: none. Name the graph to reach it:

PREFIX ex: <http://example.org/>
PREFIX base: <http://example.org/graphs/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?title WHERE {
  GRAPH base:archive {
    ?book ex:title ?title .
    FILTER(text:query(?title, "tonner"))
  }
}

Answers: Le Tonner Moderne. With a graph variable, each answer carries the graph it came from:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?g ?book WHERE {
  GRAPH ?g {
    ?book a ex:Book .
    FILTER(text:query(?book, ex:title, "tonner"))
  }
}

Answers: base:archive and ex:book4. FROM base:archive on the query restricts the search in the same way.

With --default-union on the server, the default graph is the union of every graph and the search follows it: the language example above then answers without its GRAPH clause.

Test a single value

When the variable holds known values — bound by VALUES, or by BIND of a constant — text:query becomes a membership test and answers directly:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book WHERE {
  VALUES ?book { ex:book1 ex:book2 }
  FILTER(text:query(?book, ex:title, "laser"))
}

Answers: ex:book1. The literal form works the same way over literal values, and BIND(ex:book3 AS ?book) in place of the VALUES answers ex:book3.

Combine with other patterns

A text:query filter composes with the rest of the query. The index answers the text question, and the surviving rows join with the other patterns as usual:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?title ?authorName WHERE {
  ?book ex:title ?title ;
        ex:author ?author .
  ?author ex:name ?authorName .
  FILTER(text:query(?title, "laser"))
}

Answers: The Laser Printer Handbook with Ada Bell, and Laser Physics with Bruno Costa.

One filter is evaluated once per query, however many patterns bind its variable, so a query never needs restructuring to protect it.

Inside an OPTIONAL

A text:query inside an OPTIONAL body works when it tests a variable the body itself binds:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book ?title WHERE {
  ?book a ex:Book .
  OPTIONAL {
    ?book ex:title ?title .
    FILTER(text:query(?title, "laser"))
  }
}

Answers: ex:book2 with no title, then ex:book1 and ex:book3 with theirs.

When the filter tests a variable bound outside the OPTIONAL, the query fails when it is planned, with a message saying the filter cannot answer inside an OPTIONAL. Move the filter after the OPTIONAL:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book ?abstract WHERE {
  ?book ex:title ?title .
  OPTIONAL { ?book ex:abstract ?abstract . }
  FILTER(text:query(?title, "laser"))
}

Answers: ex:book1 and ex:book3, each with its abstract.

Inside a UNION

Each arm of a UNION can carry its own text:query, searched within that arm:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book ?matches WHERE {
  { ?book a ex:Book . FILTER(text:query(?book, ex:title, "laser")) BIND("title" AS ?matches) }
  UNION
  { ?book a ex:Book . FILTER(text:query(?book, ex:abstract, "toner")) BIND("abstract" AS ?matches) }
}

Answers: ex:book1 twice, once with title and once with abstract, and ex:book3 with title.

Shapes that fail, and what to write instead

text:query is accepted only as a plain, top-level FILTER conjunct. Every other shape is rejected when the query is planned — the client receives HTTP 400 with the reason — and never answered silently. The common cases:

Shape What happens Write instead

text:query used as a triple predicate, with a string as the object

Error: it is a FILTER function, not a graph pattern.

FILTER(text:query(?book, ex:title, "laser"))

Two text filters joined with ||, or a call inside !, IF, or COALESCE

Error: only a top-level FILTER conjunct is supported.

A UNION of two arms, or FILTER NOT EXISTS (below).

text:query(STR(?title), "laser")

Error: unsupported form.

Pass the variable itself.

text:query(?book, "laser") where ?book only ever appears as a subject

Error naming the subject form.

text:query(?book, ex:title, "laser")

text:query(?title, ex:title, "laser") where ?title only ever appears as an object

Error naming the literal form.

text:query(?title, "laser")

A subject form with no triple pattern binding the subject

Error (column length mismatch).

Add a pattern such as ?book a ex:Book.

A subject form naming a predicate outside predicates

Error naming the predicate.

Add it to text.toml and rebuild, or drop it.

A language-tagged or numeric search string, an empty one, or a third argument other than lang:xx

Error.

A plain, non-empty string literal.

The plugin disabled, or the index not trusted

Error naming waratah text rebuild-index.

Enable the plugin; rebuild the index.

To negate a text search, use FILTER NOT EXISTS with a pattern that binds the subject:

PREFIX ex: <http://example.org/>
PREFIX text: <http://jena.apache.org/text#>

SELECT ?book WHERE {
  ?book a ex:Book .
  FILTER NOT EXISTS {
    ?book a ex:Book .
    FILTER(text:query(?book, ex:title, "laser"))
  }
}

Answers: ex:book2, the only book in the default graph whose title does not match.

Know when the string functions use the index

STRSTARTS, STRENDS, and an anchored REGEX keep their exact SPARQL meaning. The index only narrows the rows that are tested, so they give the same answers with or without it:

PREFIX ex: <http://example.org/>

SELECT ?title WHERE {
  ?book ex:title ?title .
  FILTER(STRSTARTS(?title, "Laser"))
}

Answers: Laser Physics. FILTER(REGEX(?title, "^Laser")) answers the same, and FILTER(STRENDS(?title, "Handbook")) answers The Laser Printer Handbook.

Three things differ from text:query:

  • They are exact and case-sensitive: STRSTARTS(?title, "laser") answers nothing.

  • The index is used only when every value of the searched variable comes from an indexed predicate. Otherwise the filter runs over every row: same answers, no shortcut.

  • They never fail because the index is missing.

To see whether the index was used, start the server with --debug and look for text_scan on the plan-tree: line of the debug log. It is present when the index narrowed the rows and absent when the filter ran over every row. (waratah explain plans a query without the text plugin and never shows it.)

Keep the index usable

Three settings define the index: analyzer, seed_chars, and predicates. Together they form the index’s identity, shown as the fingerprint in waratah text status. The server and the import commands refuse to open a store whose existing index was built with a different identity — including one built by Waratah 0.6.1 or earlier, whose layout differs — and never rebuild an index on their own. To change any of the three:

waratah stop --data-dir ./waratah-data
waratah text rebuild-index --data-dir ./waratah-data --config-dir ./config
waratah text status --data-dir ./waratah-data --config-dir ./config

seed_chars is the number of characters kept per literal for prefix and suffix matching (1 to 64, default 16). A pattern up to that length is answered from the index alone; a longer one is narrowed by its first (or last) seed_chars characters.

A rebuild is needed after:

  • changing analyzer, seed_chars, or predicates;

  • upgrading from 0.6.1 or earlier;

  • an import that ran without the plugin, as described above;

  • large deletes. Documents are not removed when triples are deleted. They do not change any answer, but they take space until a rebuild.

A rebuild is not needed when:

  • the plugin is enabled on a store that has no index yet: the server builds it at startup, before it answers the first query;

  • an import --connect runs against a text-enabled cluster whose index is not built yet: the import builds it over the existing rows first, then loads. The cluster keeps refusing text:query with the repair hint until it is restarted, because a server reads its index state at startup;

  • the server restarts.

waratah text rebuild-index runs on a stopped store and replaces a mismatched index. If a rebuild cannot index every string — a value longer than 1 MiB, or one whose text cannot be read — it reports the counts and leaves the index untrusted, and text:query keeps failing with the repair hint until a rebuild completes.

When a search returns nothing

Work down this list. Each item is a cause this page has shown.

  1. Is the plugin enabled for the server? Without it, text:query is an unknown function.

  2. Run waratah text status. Is the index trusted, and is live documents greater than zero?

  3. Is the searched predicate in the list that status prints? For the literal form, a predicate outside the list means no rows and no error.

  4. Were the rows loaded by an import that ran without the plugin? If so, rebuild the index.

  5. Is the data in a named graph that the query does not name?

  6. Does the language restriction match? Tags are exact and in lower case.

  7. Are the operators in upper case, with exclusions written as a minus sign?

  8. With en_stem, remember that a stem is not a prefix.

  9. Does a subject-form filter have a triple pattern binding the subject?

Limits of this release

  • A string literal longer than 1 MiB cannot be written while the text plugin is enabled (Size limit).

  • CONTAINS and an unanchored REGEX are not indexed; they run as ordinary filters.

  • text:query has no scoring, highlighting, or limit argument, no wildcard, and no field prefix.

  • A text:query that tests a variable bound outside an OPTIONAL is rejected.