Querying Lucene

The querydsl-lucene module turns Querydsl predicates into Apache Lucene 10 queries. It also writes documents using an IndexWriter. Lucene 10 needs Java 21. Because of this, this module is compiled for Java 21, but the rest of Querydsl targets Java 17.

Maven Integration

<dependency>
  <groupId>io.github.openfeign.querydsl</groupId>
  <artifactId>querydsl-lucene</artifactId>
  <version>7.1</version>
</dependency>

lucene-core comes in transitively. Add lucene-analysis-common or other analyzer modules as your index needs them.

Lucene has no mapping annotations. Add @QueryEntity to the classes that describe your documents, and @QueryEmbeddable to nested types. Then generate the query types with the general annotation processor:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-compiler-plugin</artifactId>
  <version>3.15.0</version>
  <configuration>
    <proc>full</proc>
    <generatedSourcesDirectory>${project.build.directory}/generated-sources/java</generatedSourcesDirectory>
    <annotationProcessorPaths>
      <path>
        <groupId>io.github.openfeign.querydsl</groupId>
        <artifactId>querydsl-apt</artifactId>
        <version>7.1</version>
        <classifier>general</classifier>
      </path>
    </annotationProcessorPaths>
  </configuration>
</plugin>
@QueryEntity
public class Book {
  private String isbn;
  private String title;
  private String author;
  private Integer year;
  private Address publisher; // @QueryEmbeddable, stored as "publisher.city", ...
  // getters and setters
}

Property names become field names. For example, a nested property publisher.city maps to the field publisher.city. You cannot generate query types from an existing index, because an index does not store the Java type of each field.

The serializer

LuceneSerializer decides how each path is matched, and the writing clauses use it to decide how each path is indexed, so use one serializer for both:

QBook book = QBook.book;
LuceneSerializer serializer = new LuceneSerializer(true, true, book.isbn);
  • Number paths (Integer, Short, Byte, Long, Float, Double) are points. A constant or parameter that does not fit the path’s type exactly, such as 4294967295L on an Integer path or 1.5 on a Long path, is rejected with an IllegalArgumentException.
  • Keyword paths, listed after the two flags, and paths of any type other than String or a number (dates, enums, Boolean, UUID, …) are one untokenized term holding the value’s toString(). Their values are matched unchanged.
  • Other String paths are tokenized text. String values are matched against indexed terms. LuceneSerializer(lowerCase, splitTerms) controls how a value becomes terms: lowerCase matches fields indexed with a lower casing analyzer, and splitTerms splits on whitespace for tokenized fields. The default serializer splits but does not lower case. PhraseElement and TermElement pass a value through unchanged:
new LuceneQuery(serializer, searcher)
    .where(book.title.eq(new PhraseElement("jurassic park")));

Querying

IndexSearcher searcher = new IndexSearcher(DirectoryReader.open(directory));

List<Document> documents = new LuceneQuery(serializer, searcher)
    .where(book.author.eq("Michael Crichton"), book.year.between(1980, 2000))
    .orderBy(book.year.desc())
    .limit(10)
    .fetch();

LuceneQuery returns Lucene Documents. TypedQuery maps each document with a Function<Document, T>, or reads stored fields into a projection:

List<Book> books = new TypedQuery<>(serializer, searcher, Projections.bean(Book.class, book.title, book.year))
    .where(book.title.startsWith("jurassic"))
    .fetch();

Results are ordered by relevance unless orderBy is given, with order specifiers or a Lucene Sort; orderBy(Sort.INDEXORDER) restores the index order used by the old querydsl-lucene5 module. fetch, fetchFirst, fetchOne, fetchCount, fetchResults, iterate and stream are available, as are limit (limit(0) returns no results), offset, parameters, loadOnlyFields(...) to read only some stored fields and filter(Query) to add non-scoring Lucene clauses.

Lucene keeps the top offset + limit hits in memory before the first result is returned. Without a limit, fetch, iterate and stream collect up to one entry per document in the index. Set a limit on large indexes and page with offset.

Operators

Querydsl Lucene
and, or, not, ne, notIn BooleanQuery (MUST, SHOULD, MUST_NOT)
eq on text TermQuery, or PhraseQuery when the value has several words
eq on keywords and other types TermQuery of the whole value
eq, in, lt, gt, loe, goe, between on numbers IntPoint, LongPoint, FloatPoint, DoublePoint queries
lt, gt, loe, goe, between on strings TermRangeQuery; bounds are not split into words
in BooleanQuery of SHOULD clauses; an empty in matches nothing
startsWith PrefixQuery
like, endsWith, contains WildcardQuery; like accepts */? and %/_
LuceneExpressions.fuzzyLike FuzzyQuery
LuceneExpressions.knn KnnFloatVectorQuery, see Vector search
LuceneExpressions.wrapQuery(Query) any Lucene query, as is

like passes its pattern to Lucene as is, so a value from a lower-trust source can add wildcards, including a leading * that scans every term of the field. Use startsWith, endsWith or contains for such values, which escape *, ? and \, or escape them first.

Range operators work only on String and number paths. On other types the toString() order is not the value order (Mon sorts before Tue whatever the date), so they throw an UnsupportedOperationException; index such values as numbers, for example epoch days, to compare them. Other operators (case-insensitive variants, isNull, length(), arithmetic, comparisons between two paths, …) throw an UnsupportedOperationException too, when the query is built. lower() and upper() are accepted only by a serializer with lowerCase enabled. Joins, grouping, aggregation and subqueries are not part of the API.

Index number fields as points, as IntField, LongField, FloatField and DoubleField do. Sorting uses doc values: SortedNumericDocValues for numbers (written by those fields) and SortedDocValues for strings. For other layouts, override LuceneSerializer.toSortField or pass a Sort.

Add querydsl-vector to the annotation processor path to generate float[] properties as VectorPath:

<path>
  <groupId>io.github.openfeign.querydsl</groupId>
  <artifactId>querydsl-vector</artifactId>
  <version>7.1</version>
</path>

DefaultFieldMapper indexes each float[] value as a KnnFloatVectorField and also stores it, so projections can read it back. Vectors use Lucene’s default EUCLIDEAN similarity. Pass another VectorSimilarityFunction to the mapper to change it:

var mapper = new DefaultFieldMapper(serializer, VectorSimilarityFunction.COSINE);
new LuceneInsertClause(writer, serializer, mapper).populate(article, sample).execute();

LuceneExpressions.knn(path, target, k) finds the k nearest documents and ranks them first. Predicates that are and-ed with it, and filter(Query) clauses, become the KnnFloatVectorQuery filter. This means they narrow the candidates before the search, so the query still returns up to k hits:

List<Document> nearest = new LuceneQuery(serializer, searcher)
    .where(knn(article.embedding, question, 10), article.category.eq("faq"))
    .fetch();

You can use knn with or and not like any other clause. Lucene computes no distance values. It only ranks hits by the similarity of the field. Because of this, l2Distance, cosineDistance and the other VectorPath operations throw an UnsupportedOperationException in where, orderBy and projections. So does any other operator on a vector path.

Writing

Insert, update and delete clauses work on an IndexWriter. They never commit: call writer.commit() when the changes must be durable, and reopen readers (for example with SearcherManager.maybeRefresh() or DirectoryReader.openIfChanged) before searching for them.

Insert

new LuceneInsertClause(writer, serializer)
    .set(book.isbn, "978-0-394-58816-2")
    .set(book.title, "Jurassic Park")
    .set(book.year, 1990)
    .addBatch()
    .populate(book, otherBook)
    .execute();

populate copies every property that has a path in the query type, including embedded types. The default DefaultFieldMapper stores every value and picks the field kind from the declared type of the path, not from the value:

  • number paths as IntField, LongField, FloatField or DoubleField; a value that does not fit the path’s type exactly is rejected;
  • keyword paths and paths of other types as untokenized StringFields (toString()), with sort doc values when single valued;
  • other String paths as tokenized TextFields.

A value of another type than the path’s is rejected before it reaches Lucene. Pass your own LuceneFieldMapper to the three-argument constructor for other choices, or addField a field directly. Null values are skipped and collection values become several fields with the same name.

Update

Lucene cannot change a document in place; IndexWriter.updateDocument deletes the documents that contain a term and adds a new one. LuceneUpdateClause therefore takes a key and the whole replacement document. The key must be a keyword path of the serializer, so inserts made with the same serializer index it as the term the update matches:

new LuceneUpdateClause(writer, serializer, book.isbn, "978-0-394-58816-2")
    .set(book.title, "Jurassic Park")
    .set(book.year, 1991)
    .execute();

Fields that are not set again are gone after the update.

Delete

long deleted = new LuceneDeleteClause(writer, serializer)
    .where(book.year.lt(1950))
    .enableAffectedCount()
    .execute();

Without where every document is deleted. IndexWriter applies deletes later and closes itself when one of them fails, so execute() rejects a query with more clauses than IndexSearcher.getMaxClauseCount() right away.

Affected counts

Lucene does not report how many documents a delete or update removed, so execute() returns -1 (unknown) by default. Call enableAffectedCount() to count them on a near real-time reader just before the write. For an update, 0 then means the key was not found and the document was added. Opening that reader flushes pending changes into a new small segment on every call, and the count can be off while other threads write to the index. Leave it off for bulk or concurrent writes. The insert clause always returns the number of documents added.