London guy
London guy

Reputation: 28032

Lucene WildcardQuery to start and end with a token

I want to write a Lucene WildcardQuery and mention that the field should start and end with the token used for searching. If I use ^box$ as a pattern in my query for Wildcard, it fails to work.

Upvotes: 0

Views: 536

Answers (2)

Mark Leighton Fisher
Mark Leighton Fisher

Reputation: 5703

To expand upon femtoRgon's answer: Stupid Lucene Tricks: Exact Match, Starts With, Ends With.

Upvotes: 0

femtoRgon
femtoRgon

Reputation: 33351

One possibility would be, if this is the typical case, and you don't intend to query this fields as full text, then store it as a StringField, and query using a simple TermQuery. This makes the query you are looking for the trivial case. If this fits your needs, it is ideal, since here you are simply designing the index to best support your needs.

If you do need to run a full text search on the field elsewhere, I'd recommend perhaps placing a unique known term at the beginning (and possibly end) of the field. Using a PhraseQuery would then make this simple enough to achieve. Of course, running this style of query on the same field you are running full text search seems a very strange use case to me.

The other possibility would be to use SpanQueries, particularly SpanFirstQuery, something like:

SpanFirstQuery query = new SpanFirstQuery(new SpanTermQuery(new Term(field, "box")), 1);

Upvotes: 1

Related Questions