2.5. Querying Lucene sources

This chapter describes the querying functionality of the Lucene module.

2.5.1. Creating the Querydsl query types

With fields year and title a manually created query type could look something like this :

 
public class QDocument extends EntityPathBase<Document>{
    private static final long serialVersionUID = -4872833626508344081L;
        
    public QDocument(String var) {
        super(Document.class, PathMetadataFactory.forVariable(var));
    }

    public final StringPath year = createString("year");
        
    public final StringPath title = createString("title");
}

QDocument represents a Lucene document with the fields year and title.

2.5.2. Querying

Querying with Querydsl Lucene is as simple as this :

 
QDocument doc = new QDocument("doc");

IndexSearcher searcher = new IndexSearher(index);
LuceneQuery query = new LuceneQuery(true, searcher); 
List<Document> documents = query
    .where(doc.year.between("1800", "2000").and(doc.title.startsWith("Huckle"))
    .list();

which is transformed into the following Lucene query :

     
+year:[1800 TO 2000] +title:huckle*

2.5.3. General usage

Use the the cascading methods of the LuceneQuery class like this

where : Define the query filters, either in varargs form separated via commas or cascaded via the and-operator. Supported operations are operations performed on PStrings except matches, indexOf, charAt. Currently in is not supported, but will be in the future.

orderBy : Define the ordering of the result as an varargs array of order expressions. Use asc() and desc() on numeric, string and other comparable expression to access the OrderSpecifier instances.

limit, offset, restrict : Define the paging of the result. Limit for max results, offset for skipping rows and restrict for defining both in one call.

2.5.4. Ordering

The syntax for declaring ordering is

 
query
    .where(doc.title.like("*"))
    .orderBy(doc.title.asc(), doc.year.desc())
    .list();

which is equivalent to the following Lucene query

  
title:*

The results are sorted ascending based on title and year.

2.5.5. Limit

The syntax for declaring a limit is

 
query
    .where(doc.title.like("*"))
    .limit(10)
    .list();

2.5.6. Offset

The syntax for declaring an offset is

 
query
    .where(doc.title.like("*"))
    .offset(3)
    .list();

2.5.7. Fuzzy searches

Fuzzy searches can be expressed via fuzzyLike methods in the com.mysema.query.lucene.LuceneUtils class :

 
query
    .where(LuceneUtils.fuzzyLike(doc.title, "Hello"))
    .offset(3)
    .list();