PhraseQuery is used to search for a sequence of terms. The following matches the phrase "Hello World" (after being indexed with StandardAnalyzer
)
Query query = new PhraseQuery.Builder()
.add(new Term("text", "hello"))
.add(new Term("text", "world"))
.build();
PhraseQuery can also handle "slop", or extra terms within a query, by setting a maximum edit distance with setSlop
. This will match "Lorem ipsum sit amet dolor":
Query query = new PhraseQuery.Builder()
.add(new Term("text", "lorem"))
.add(new Term("text", "amet"))
.setSlop(2)
.build();
You can also set exact position increments:
Query query = new PhraseQuery.Builder()
.add(new Term("text", "lorem"), 0)
.add(new Term("text", "sit"), 2)
.add(new Term("text", "dolor"), 4)
.build();